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.

Understanging ENV variables in PayloadCMS

default discord avatar
KasparTrlast year
12

Leaving aside public variables and focusing on backend ones.



When I access a variable (e.g. procee.env.ENVIRON) from server.ts file, I can read the value.



When I do the same in my custom core code (called inside custom endpoint inside server.ts file) it is undefined. These variables are not accessed by front-end.



server.ts


import { processGetAccountDetails } from './core/vault/controller';
console.log("server | ENVIRON: ", process.env.ENVIRON) // works
router.get('/vault/accounts', (req: any, res) => {
    processGetAccountDetails(req,res)
});


/vault/controller/index.ts


require('dotenv').config();
console.log("vault controller | ENVIRON: ", process.env.ENVIRON) // undefined


This happens seemingly at random. Some files it works, other not. What am I missing?



I must add, this is only an issue in production, locally all works as expected.

  • default discord avatar
    KasparTrlast year

    Like I said, I explicitly don't need them in admin panel. I need them in backend as I am using them (I have around 30). In some files they are undefined in production and I cannot find any pattern as to why.

  • default discord avatar
    thisisnotchrislast year

    @KasparTr Are they defined in the same .env with your payload env vars?



    If that's the case, then it makes sense

  • default discord avatar
    KasparTrlast year

    Yes, all in the same as payload secret var

  • default discord avatar
    thisisnotchrislast year

    @KasparTr

    Payload will automatically supply any present env variables that are prefixed with PAYLOAD_PUBLIC_ directly to the Admin panel.


    However, it seems like you want to use them in the backend



    Maybe create an additional .env with your custom env vars



    and use dotenv to also include that

  • default discord avatar
    Jarrodlast year

    @KasparTr does this thread help you out?

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


    I chatted back and forth with some others about this same topic in that discussion. Basically, you will need to add



    dotenv.config({
      path: path.resolve(__dirname, '../.env'),
    });

    atop your payload config file, and your server.ts file

  • default discord avatar
    KasparTrlast year

    Yes this helps. For some reason, when I added the following to server.ts, things worked normally.



    import dotenv from 'dotenv';
    dotenv.config();
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..