Utilizing dotenv in payload.config.ts

default discord avatar
Jakey
7 months ago
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

.

    Open the post
    Continue the discussion in Discord
    Like what we're doing?
    Star us on GitHub!

    Star

    Connect with the Payload Community on Discord

    Discord

    online

    Can't find what you're looking for?

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