process.env.BRANCH is returning undefined

I have a site where I’m using React and I’m doing some split tests and to track the branches I’m using the process.env.BRANCH like this.

//Sends branch name to GTM/GA for Netlify split-testing
window.ab_branch = process.env.BRANCH

but process.env.BRANCH always is undefined.

1 Like

@BrunoQuaresma do you happened to be using create-react-app ?

If so, you will have to make sure to have the value passed to an environment variable that starts with REACT_ (i.e. REACT_BRANCH)

1 Like

Have same issue with process.env.BRANCH but not on create-react-app, though if I embed this script to Snippet injection it does return correct value.

<script>
  ga('send', 'pageview', {
    'Branch':  '{{ BRANCH }}'
  });
</script>

Hi @spondbob do you have an example repo? You said you aren’t using create-react-app but you didn’t tell me what you are using. Is it pure node or a framework/library?

@futuregerald Sorry it’s just a simple react@16 app with webpack but it’s in a private repo.

One thing CRA does is automatically add environment variables prefixed with REACT_APP_ to your JS bundle. If you aren’t using CRA then you’ll need to pass that variable in to your JS files or it won’t be available to your React app when it runs. You can see the script they use to do this in the CRA repo: https://github.com/facebook/create-react-app/blob/4562ab6fd80c3e18858b3a9a3828810944c35e36/packages/react-scripts/config/env.js

@futuregerald Sorry if I’m still not clear enough but that’s what I’ve been trying to do in my simple react app without CRA. The app trying to read process.env.BRANCH but it returns undefined which I believe should be assigned during build process.

1 Like

Let’s take a step back. When is that code running?

//Sends branch name to GTM/GA for Netlify split-testing
window.ab_branch = process.env.BRANCH

It can ONLY run successfully during build. If you try to do it at browse time, yes, it will be undefined. BRANCH is only defined when BUILDING your site, so you have to interpolate at that time.

This is an article going into much more detail about how to use env vars, and it also explains some situations where even during build, your build pipeline “throws away” the environment and you’d have to fix that if it is what’s happening (that would cause “BRANCH” to be undefined even during build):