Assign buildConfig.serverUrl from `.env`

default discord avatar
pooledge
last month
23

Cannot believe no one asked this, prob just cannot find it 😭



Anyway:


// works
export default buildConfig({
  serverURL: 'http://localhost:3000',
  ...
}

// doesn't: NetworkError when attempting to fetch ressource
import dotenv from 'dotenv';
dotenv.config();

export default buildConfig({
  serverURL: `${process.env.PAYLOAD_HOST}:${process.env.PAYLOAD_PORT}`,
  ...
}


# .env
PAYLOAD_HOST=http://localhost
PAYLOAD_PORT=3000


Payload version is 1.13.4

  • default discord avatar
    notchr
    last month

    @pooledge That's odd, apart from that not being the typical way of setting up the buidConfig, the env variables should have been pulled in



    Can you log out the computer value of those enviornment variables please?

  • default discord avatar
    pooledge
    last month
    import dotenv from 'dotenv';
    dotenv.config();
    
    console.log(`${process.env.HOST}:${process.env.PORT}`);
    ...


    [nodemon] restarting due to changes...
    [nodemon] starting `ts-node src/server.ts`
    [12:38:41] INFO (payload): Connected to MongoDB server successfully!
    [12:38:41] INFO (payload): Starting Payload...
    http://localhost:3000
    [12:38:41] INFO (payload): Payload Admin URL: http://localhost:3000/admin
    webpack built a2082b418cb8a08a9fb5 in 1075ms
    webpack compiled successfully


    I'd like to set HOST/PORT as per our pipeline requirements, moreover I'm able to re-use PORT for express. What would be the typical way?

  • default discord avatar
    notchr
    last month

    that seems to be working ,right



    it logged out the .env variables

  • default discord avatar
    pooledge
    last month

    Moreover:


    ...
    onInit: async (payload) => {
      // If the `env` var PAYLOAD_SEED` is set, seed the db
      if (process.env.PAYLOAD_SEED) {
        await seed(payload);
      }
    }
    ...


    this part of the config works!

  • default discord avatar
    notchr
    last month

    Instead of importing, what happens if you do

    require('dotenv').config()


    thats how the doc shows it

  • default discord avatar
    pooledge
    last month

    Build and starts up just fine, same as always



    [Error] TypeError: (__webpack_require__(/*! dotenv */ "./node_modules/payload/dist/bundlers/mocks/dotENV.js").config) is not a function. (In '(__webpack_require__(/*! dotenv */ "./node_modules/payload/dist/bundlers/mocks/dotENV.js").config)()', '(__webpack_require__(/*! dotenv */ "./node_modules/payload/dist/bundlers/mocks/dotENV.js").config)' is undefined)
    
        __webpack_require__ (main.js:211066)
        (anonymous function) (main.js:212531)
        Global Code (main.js:212533)


    In browser



    That's funny bc it

    always

    build and starts up just fine

  • default discord avatar
    notchr
    last month

    OH the env variables dont carry over to the browser



    unless you prefix them



    but you shouldnt need those env variables on your client

  • default discord avatar
    pooledge
    last month

    Exactly



    This is the result of starting up with .env vars instead of a string

    Screenshot_2023-08-14_at_14.46.58.png
  • default discord avatar
    pooledge
    last month

    Seems like I need those vars in client 🙂

    Screenshot_2023-08-14_at_14.48.32.png
  • default discord avatar
    notchr
    last month

    Hmm, this is on the payload admin panel specifically?



    Can we check out your Payload config file?

  • default discord avatar
    pooledge
    last month

    Prefixing like this seems working



    Switched to 2000 for env



    Okay, so basically config is build (and must be) isomorph



    import path from 'path';
    import dotenv from 'dotenv';
    
    import { buildConfig } from 'payload/config';
    import { seed } from './seed';
    
    import Logo from './admin/components/graphics/Logo';
    import Icon from './admin/components/graphics/Icon';
    
    import Users from './collections/Users';
    import Media from './collections/Media';
    import Categories from './collections/Categories';
    
    dotenv.config();
    
    console.log(
        `${process.env.PAYLOAD_PUBLIC_HOST}:${process.env.PAYLOAD_PUBLIC_PORT}`
    );
    
    export default buildConfig({
        // serverURL: 'http://localhost:2000',
        serverURL: `${process.env.PAYLOAD_PUBLIC_HOST}:${process.env.PAYLOAD_PUBLIC_PORT}`,
        admin: {
            components: {
                graphics: {
                    Logo,
                    Icon,
                },
            },
            css: path.resolve(__dirname, 'admin/styles'),
            meta: {
                titleSuffix: '— WKO CMS',
                favicon: '/assets/logo.svg',
                ogImage: '/assets/logo.svg',
            },
            user: Users.slug,
        },
        collections: [Users, Media, Categories],
        localization: {
            locales: ['de', 'en'],
            fallback: true,
            defaultLocale: 'de',
        },
        typescript: {
            outputFile: path.resolve(__dirname, 'types.d.ts'),
        },
        graphQL: {
            schemaOutputFile: path.resolve(__dirname, 'generated-schema.graphql'),
        },
        onInit: async (payload) => {
            // If the `env` var PAYLOAD_SEED` is set, seed the db
            if (process.env.PAYLOAD_SEED) {
                await seed(payload);
            }
        },
        telemetry: false,
    });
    Screenshot_2023-08-14_at_14.51.51.png
  • default discord avatar
    notchr
    last month

    Ah interesting



    I'm glad that fixed it!

  • default discord avatar
    pooledge
    last month

    Yeah, thanks!

  • default discord avatar
    notchr
    last month

    I can see now in my config that I was also prefixing the server URL env var

  • default discord avatar
    pooledge
    last month

    I didn't feel it's such an anti-pattern tbh



    Did you prefix as public?



    At least

  • default discord avatar
    notchr
    last month

    yeah I do..



    let serverUrl: string;
    if (process.env.NODE_ENV === "production") {
      serverUrl = process.env.PAYLOAD_PUBLIC_SERVER_PROD;
    } else if (process.env.NODE_ENV === "beta") {
      serverUrl = process.env.PAYLOAD_PUBLIC_SERVER_BETA;
    } else {
      serverUrl = process.env.PAYLOAD_PUBLIC_SERVER_DEV;
    }
  • default discord avatar
    pooledge
    last month

    yeah quite common isn't it

  • default discord avatar
    notchr
    last month

    Yeah for sure, depen ding on the enviornment

  • default discord avatar
    pooledge
    last month

    Ok so I'm closing this then, thanks for the heads-up!



    Great stuff



    This is why PAYLOAD_SEED works, it doesn't need to be client-side

  • default discord avatar
    notchr
    last month

    Of course, happy to help!

  • default discord avatar
    pooledge
    last month

    So envs are stripped from config on client, obviously

  • default discord avatar
    notchr
    last month

    Right right

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.