Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Utilizing dotenv in payload.config.ts

default discord avatar
Jakey2 years 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

.

    Star on GitHub

    Star

    Chat on Discord

    Discord

    online

    Can't find what you're looking for?

    Get dedicated engineering support directly from the Payload team.