Home
Support Forums

Environment Variables not logging properly

PLEASE help us help you by writing a good post!

Site name is Could you please help me sort out this same issue with my sites too? My sites are deploying fine but none of my environment variables are logging properly.

I have followed the recommended article and I am using REACT_APP… because my project is built using Create-React-App.

My site name is: sendt-dev.netlify.app

My CI/CD setup is git => circleCI => netlify

My issue is with the environment variables set in Netlify UI are not available in my production deployment.

Locally, I use .env and .env.development and .env.production and these are displaying the variables correctly but it is not working on the deployed live Netlify site. When logging process.env, all my expected env vars are undefined :sob:

My .env file is as follows (I’ve starred out the actual values)

REACT_APP_API_BASE_URL=******
REACT_APP_BASE_URL=******
REACT_APP_ENV=******
REACT_APP_FIREBASE_API_KEY=******
REACT_APP_FIREBASE_AUTH_DOMAIN=******
REACT_APP_FIREBASE_PROJECTID=******
REACT_APP_FIREBASE_STORAGE_BUCKET=******
REACT_APP_FIREBASE_SENDER_ID=******
REACT_APP_FIREBASE_APP_ID=******
REACT_APP_FIREBASE_MEASUREMENT_ID=******
REACT_APP_SENTRY_API_KEY=******
REACT_APP_STRIPE_PUBLISHABLE_KEY=******

I am using REACT_APP prefix becuase I am using create-react-app for my project. I have used these same names in Netlify ENV UI.

My CircleCI config.yml is as follows:

executors:
  node-executor:
    docker:
      - image: cimg/node:14.18.2

jobs:
  build-deploy-dev:
    executor: node-executor
    steps:
      - checkout
      - run:
          name: Install Dependencies
          command: yarn install
      - run:
          name: Build Dev
          command: CI=false yarn run build
      - run:
          name: Install Netlify
          command: sudo yarn global add netlify-cli
      - run:
          name: Netlify Deploy
          command: |
            netlify deploy --site $NETLIFY_DEV_SITE_ID --auth $NETLIFY_ACCESS_TOKEN --prod --dir=build
  build-deploy-prod:
    executor: node-executor
    steps:
      - checkout
      - run:
          name: Install Dependencies
          command: yarn install
      - run:
          name: Build Prod
          command: CI=false yarn run build
      - run:
          name: Install Netlify
          command: sudo yarn global add netlify-cli
      - run:
          name: Netlify Deploy
          command: netlify deploy --site $NETLIFY_PROD_SITE_ID --auth $NETLIFY_ACCESS_TOKEN --prod --dir=build

version: 2.1

workflows:
  version: 2
  build-deploy:
    jobs:
      - build-deploy-dev:
          context: SENDTDEV
      - hold:
          type: approval
          requires:
            - build-deploy-dev
      - build-deploy-prod:
          context: SENDTPROD
          requires:
            - hold

Please can someone give me some ideas of how to solve this?

I have gone through the Netlify post on troubleshooting environment variables but I cant quite sort it out and it’s been quite a few days now trying to solve this.

Any help is much appreciated :pray:

Hi @jameslevine

Please don’t use keys such as these in a front-end app as they become exposed in the code. Variables such as this that need to remain secret are safer with a serverless function.

Have you checked out [Support Guide] Using environment variables on Netlify correctly?

I have not encountered such issues before.

I created a test deploy first using environment variables set in a netlify.toml, then .env, and then via the Netlify UI. In all cases the variables set were included in the build.

It’s alright to expose the Sentry DSN (REACT_APP_SENTRY_API_KEY in my case) and the REACT_APP_STRIPE_PUBLISHABLE_KEY is meant to be safe to be publishable too so should be ok.

[Support Guide] Using environment variables on Netlify correctly

I’ve checked this link above and have followed everything exactly, if anyone knows anything that I might need to also check I would greatly appreciate. I’m trying to avoid using netlify.toml and .env because I would rather not commit either of these files in my repo.

As long as you are aware of how this works and are comfortable the keys are safe in the front end.

How are you access the variables? Remembering that variables are available at build time, not when the app is run in the browser.

Can you share a repository, or a section of code, where an environment variable is accessed?

Here is a good example of where I’m using an environment variable as the url base in a POST request. Hopefully makes it a little clearer.

import {
  addCollabOrderCommentEndpoint,
  createCollabCommentEndpoint,
  createCollabOrderEndpoint,
  createOrderEndpoint,
  deleteCollabCommentEndpoint,
  deleteCollabOrderCommentEndpoint,
  getCollabOrderCommentsEndpoint,
} from './constants';

import deepPick from '../utils/lodash';

const createOrder = async (body) => {
  const createOrderBody = {
    ...deepPick(['budget', 'customBudget'], body),
    participants: body.participants.map((participant) =>
      deepPick(['name', 'mobile', 'countryCode'], participant),
    ),
  };

  const url = `${process.env.REACT_APP_API_BASE_URL}${createOrderEndpoint}`;
  const options = {
    body: JSON.stringify(createOrderBody),
    headers: {
      'Content-Type': 'application/json',
    },
    method: 'POST',
  };

  try {
    const response = await fetch(url, options);
    const data = await response.json();
    if (!response.ok) {
      throw new Error(data.error);
    }
    return data;
  } catch (error) {
    throw new Error(error);
  }
};

About being available during build time, the interesting thing is that when I check the static files from the deployment, the environment variables are not in the minified code which would suggest they aren’t being added during build time.

I have tried, but cannot replicate this.

Regardless of the mode (production or development) and regardless of sourcemap generation (true or false I always see the values of the variable, and not the variable name, is the resulting built code.

I’m currrently trying to build a new project bit by bit and see at what stage it fails (I’m hoping not right at the beginning). Will post anything I find here.

I am curious about the sections in main.XXX.chunk.js such as

    S = Object({
      NODE_ENV: 'production',
      PUBLIC_URL: '',
      WDS_SOCKET_HOST: void 0,
      WDS_SOCKET_PATH: void 0,
      WDS_SOCKET_PORT: void 0,
      FAST_REFRESH: !0
    }).REACT_APP_API_BASE_URL;

and

    ft = Object(gt.a) (Object({
      NODE_ENV: 'production',
      PUBLIC_URL: '',
      WDS_SOCKET_HOST: void 0,
      WDS_SOCKET_PATH: void 0,
      WDS_SOCKET_PORT: void 0,
      FAST_REFRESH: !0
    }).REACT_APP_STRIPE_PUBLISHABLE_KEY),

and the source code that has created these.

Perhaps this issue, or this thread might hold some insights (or even this issue.)

Ok so I had some time to strip the project back.

  • I created a new Create-React-App project with the same CircleCI config.yml
  • Added just 1 environment variable in the Netlify UI
  • Created a new Netlify Site, Github project and new CircleCI project so it is completely detached from previous project.

I have discoved that the problem is likely related to the CircleCI steps in my CI/CD pipeline.

When I push code from git, I forgot to turn off the automatic deploy from Github so it deployed the site twice:

The first deploy preview logs the Netlify env variable correctly

The second deploy preview logs the Netlify env variable as undefined - I believe this is the deploy built using the CircleCI pipeline.

So my question turns to is there anything inside these CircleCI steps that looks wrong?

steps:
      - checkout
      - run:
          name: Install Dependencies
          command: yarn install
      - run:
          name: Build Dev
          command: CI=false yarn run build
      - run:
          name: Install Netlify
          command: sudo yarn global add netlify-cli
      - run:
          name: Netlify Deploy
          command: |
            netlify deploy --site $NETLIFY_DEV_SITE_ID --auth $NETLIFY_ACCESS_TOKEN --prod --dir=build

I will continue investigating this but hopefully this added information is helpful.

Great work narrowing things down.

While I don’t know/use CircleCI, looking at the workflow from the point of view of something I might do manually, I see an issue I believe.

It appears the build is happening inside CircleCI, then the built files are deployed to Netlify. So unless the REACT_APP_XXX variables are set in CircleCI they are going to take undefined in the built code as the values are injected at build time not deploy time. This is the same as running yarn build (npm run build) locally then deploying to Netlify (whichever way you choose) and not having the environment variables defined locally when building.

If you are using Netlify CLI to build and deploy and have it linked to a Netlify site, the CLI will pull the environment variables defined in the UI while building.

Edit:
I tested this by first running netlify build with a linked project, then netlify build -o (-o is offline). The resulting code looks like that I previously observed in your deploy and is observable in the last test deploys you made:

netlify build

Object(o.jsx)("div", {
    hidden: !0,
    children: "This is a secret variable"
})

netlify build -o

Object(s.jsx)("div", {
    hidden: !0,
    children: Object({
        NODE_ENV: "production",
        PUBLIC_URL: "",
        WDS_SOCKET_HOST: void 0,
        WDS_SOCKET_PATH: void 0,
        WDS_SOCKET_PORT: void 0,
        FAST_REFRESH: !0
    }).REACT_APP_SECRET_VAR
})

Ah that is interesting, thanks for testing it out. I actually ended up going a slightly different route to bring the build away from circleci. My circleci config is now like this:

      - run: npm install
      - run:
          name: Deploy
          command: curl -X POST -d {} $NETLIFY_BUILD_HOOK

Obviously much shorter and also saves a lot of build minutes.

Most importantly however I can now see the environment variables :raised_hands: so I call that a win for sure.

However, another problem has weirdly arisen.

The deploy preview url in Netlify is showing the correct new build but the new deploy isnt displaying in my netlify.app url for my site or the domain I have set up with my site.

I have tried to fix this all day but no idea why. Any help with this last bit?

YAY! Win :netliconfetti:

Do you have Auto publish disabled by any chance?

Unfortunately not. Seems to be enabled.

When I’ve used a build hook, exactly as you have in the workflow above, always results in the build auto-publishing (at least on the production branch; this may differ on a non-production branch though I have not tested this.)

Oh yeah I set the production branch to a random name to avoid double deploys from GitHub and my circle I pipeline. Any other options here?

So the latest build, as triggered by the webhook, does not have Published next to it in the deploys list?

The build hook is triggering the production branch?

No it does not have published next to it :sob:

Well the deploy preview is showing the correct stuff so I assume the build hook is deploying correctly

From this comment here Triggering publish with a webhook - #3 by FDX

It would suggest that auto publish doesn’t work if you set a different branch (I’ve set the production branch to one I’ll never use to avoid deploying twice - once from GitHub and a second from the webhook)

The thread also seems to suggest another solution possibly? Not sure if you know of this other solution?