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.

Payload not using correct serverUrl

default discord avatar
iamroot3 years ago
21

I have my server url setup as this right now


serverURL: process.env.PAYLOAD_URL || "http://localhost:5000",

This allows me to not have to set a url for development


Then in my dockerfile I have


ENV PAYLOAD_URL http://production.domain.org

and in my docker compose I also have PAYLOAD_URL set as an env var



However when I run it and try to go to the admin panel, it's still picking up localhost:5000 somewhere and I have no clue why



it only works if i do

serverURL: process.env.PAYLOAD_URL || "http://production.domain.org"

in my config

  • default discord avatar
    jessrynkar3 years ago

    Hi

    @148846159564111872

    (great username btw),



    Since the issue you are getting is CORS - can I first check that you have cors declared in your payload.config file?



    cors: [ 'http://localhost:5000', process.env.PAYLOAD_URL, ],
  • default discord avatar
    iamroot3 years ago

    Cors is '*'



    Localhost:5000 isnt accessible from client aswell

  • default discord avatar
    jessrynkar3 years ago

    When you set

    serverURL: process.env.PAYLOAD_URL

    without

    the OR operator - what happens?

  • default discord avatar
    skry.3 years ago

    I have the same issue and the problem is that my env variable is undefined, you have an idea why ?

  • default discord avatar
    jessrynkar3 years ago
    @122444319054495746

    how are you setting your env? are you using a

    .env

    file or is this happening to you in production?

  • default discord avatar
    iamroot3 years ago

    Ya I get undefined too, using system envs not .env

  • default discord avatar
    skry.3 years ago
    @854377910689202256

    I'm using the .env generated at installation and its doing it in local and production

  • default discord avatar
    jessrynkar3 years ago
    @148846159564111872

    if you update your env name from

    PAYLOAD_URL

    to

    PAYLOAD_PUBLIC_URL

    it should fix your problem, here is a little background:



    By default, env variables are not provided to the Admin panel for security and safety reasons. But, Payload provides you with a way to still provide env vars to your frontend code.

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

    Source:

    https://payloadcms.com/docs/admin/webpack#admin-environment-vars

    @122444319054495746

    does the information above help in your situation?

  • default discord avatar
    skry.3 years ago
    @854377910689202256

    Ahhhh yes its good now, totally forgot to look this part of the docs, thanks !

  • default discord avatar
    6orion3 years ago

    This doesn't work for me and I've tried it in so many ways.


    payload.config.js is simply not processing

    PAYLOAD_PUBLIC_URL

    variable on the client side, while on the server-side, when starting the server, it's read and used properly. I know that payload.config.js is used both on client side and server side - but can some ENV variables be included in it and sent to the client side?

  • default discord avatar
    4000degrees3 years ago

    Might be related to the fact that for the admin dashboard build env variables are read only during compiling. So whatever you had in the PAYLOAD_PUBLIC_URL will be saved as a static string in js.

  • default discord avatar
    6orion3 years ago

    Yeah, but then it should arrive to Admin's React client when it's being loaded on client-side.


    If you add a console.log there to payload.config.js to log the PAYLOAD_PUBLIC_URL variable, you can see that payload.config.js get's requested and loaded both on server- (Express) and client-side (React).

    On the server-side, .env variables are loaded properly, but on the client-side they just become undefined.

    It's kind of a mess and I don't know how I am supposed to use environmental variables there.

  • default discord avatar
    skry.3 years ago

    I created 2 files in /src, generateEnvData.js which contains the following code :

    const fs = require("fs");
    const dotenv = require("dotenv");
    const result = dotenv.config();
    if (result.error) {
      throw result.error;
    }
    const envConfig = result.parsed;
    const envConfigPublic = {};
    Object.keys(envConfig).forEach((key) => {
      if (key.startsWith("PAYLOAD_PUBLIC")) {
        envConfigPublic[key] = envConfig[key];
        console.log(key, envConfig[key]);
      }
    });
    fs.writeFileSync(
      "./src/env.js",
      `export default ${JSON.stringify(envConfigPublic, null, 2)}`
    );


    Then I created env.js which contains :

    export default {};


    In package.json in the scripts I added

        "build:env": "node ./src/generateEnvData.js",

    and in the build script I added

    && yarn build:env

    just after

    yarn copyfiles


    Then you can import env.js in payload.config.js and you should be able to access to public env variables

    const appType = envData?.PAYLOAD_PUBLIC_APP_ENV || null;
    const appUrl = envData?.PAYLOAD_PUBLIC_URL || null;


    Its probably a bad way to do it but at least it works and its public variables so it doesn't really matter

  • discord user avatar
    jarrod_not_jared
    3 years ago
    @449718968077254658

    are you having this issue in dev or build? env vars prefixed with PAYLOAD_PUBLIC are available on the client

  • default discord avatar
    skry.3 years ago

    This issue is in dev and build, my PAYLOAD_PUBLIC_URL is also undefined, that's why I generate a file at build which contains the public variables.

  • discord user avatar
    jarrod_not_jared
    3 years ago

    Where are you importing and using dotenv?

  • default discord avatar
    6orion3 years ago
    @281120856527077378

    It's an issue in build/production. In server.ts (express), env variables are imported via dotenv and they are working okay. It's the payload.config.ts that's having issues. I am actually not importing them via anything, since dotenv is breaking the React client as well in that file, but I am just kind of using them as a raw process.env.PAYLOAD_PUBLIC_URL variable for serverUrl. Nothing more, nothing less. That same variable is used in server.ts and works well, in both files, on the server side (I've logged them), which draw a conclusion that somehting is happening only on the client side, when payload.config.ts is read by the client.



    This is the

    server.ts

    file:


    import express from 'express';
    import payload from 'payload';
    import cors from 'cors';
    import * as dotenv from 'dotenv';
    dotenv.config()
    
    const app = express();
    
    app.use(cors())
    
    // Redirect root to Admin panel
    app.get('/', (_, res) => {
      res.redirect('/admin');
    });
    
    // Initialize Payload
    payload.init({
      secret: process.env.PAYLOAD_SECRET || 'TESTING',
      mongoURL: process.env.MONGODB_URI || 'mongodb://0.0.0.0:27017/payload',
      express: app,
      onInit: () => {
        payload.logger.info(\`Payload Admin URL: ${payload.getAdminURL()}\`)
      },
    })
    
    // Add your own express routes here
    app.listen(process.env.PAYLOAD_PUBLIC_PORT || 3001);


    And this is

    public.config.ts

    file:



    import { buildConfig } from 'payload/config';
    import path from 'path';
    import BeforeLogin from './components/BeforeLogin';
    
    export default buildConfig({
      serverURL: `http://${PAYLOAD_PUBLIC_URL || 'localhost'}:${PAYLOAD_PUBLIC_PORT || '3001'}`,
      admin: {
        components: {
          beforeLogin: [BeforeLogin],
        },
      },
      collections: [
        //
      ],
      routes: {
        admin: '/admin'
      },
      typescript: {
        outputFile: path.resolve(__dirname, 'payload-types.ts')
      },
      graphQL: {
        schemaOutputFile: path.resolve(__dirname, 'generated-schema.graphql'),
      },
      onInit: async (payload) => {
        //
      },
    });
  • discord user avatar
    jarrod_not_jared
    3 years ago

    In the payload config you should be accessing the same way you are in the server file, i.e. process.env.PAYLOD_PUBLIC_VARIABLE

  • default discord avatar
    6orion3 years ago

    Yeah, I did that - the above c/p has a typo (It was a quickly edited file from an actual one that I am using with a work-around)



    In other words, even with process.env.PAYLOAD_PUBLIC_URL used in payload config, it's no use.


    P.S. variable is defined in .env file as PAYLOAD_PUBLIC_URL=... (ip address) - maybe I am naming it wrong?

  • discord user avatar
    jarrod_not_jared
    3 years ago
    @449718968077254658

    can you take a look at this thread:

    https://github.com/payloadcms/payload/issues/1654
  • default discord avatar
    6orion3 years ago

    Thanks a lot! This solved the issue!

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.