Utilizing dotenv in payload.config.ts

default discord avatar
Jakeylast year
1

This was a problem I couldn't find an easy answer to so I figured I would just post it here.



The issue:


Attempting to use

require('dotenv').config()

in

payload.config.ts

results in an error at runtime.



The fix:


- Prefix the environment variable in your .env with

PAYLOAD_PUBLIC_

.


- Use the

import

method of including the dotenv package:

import dotenv from 'dotenv'

- Invoke dotenv like so

dotenv.config()

- Access your environment variable like so:

process.env.PAYLOAD_PUBLIC_EXAMPLE

When I do this, there is no build error

and

there is no js/network error at runtime.



Hope this helps someone in the future!



@jmikrut, we had chatted about this briefly in another prost. Just a heads up in case you're curious where this landed.



I found the answer here and implemented it how I described it above:

https://github.com/payloadcms/payload/issues/1654#issuecomment-1419012718

.

    Star on GitHub

    Star

    Chat on Discord

    Discord

    online

    Can't find what you're looking for?

    Get help straight from the Payload team with an Enterprise License.