1

Everything works fine on my PC, but after I deploy to netlify, my environment variable is undefined. This is what I have in the state.

let apikey;

if(process.env.NODE_ENV !== 'production') {
    apikey = process.env.REACT_APP_APIKEY;
    console.log(apikey);
} else {
    apikey = process.env.APIKEY;
    console.log(apikey);
}

Netlify settings

Yet still getting undefined :)

Console.log telling me the variable is undefined

2 Answers 2

1

In netlify you won’t be able to access environment variables for the client unless you have built them into your scripts during a build. That is why you should not store secret keys in the builds of your client scripts.

There is no server side on Netlify, except when using functions. If you are using Netlify functions (lambda-functions) then there is not an issue accessing environment variables setup through the admin UI.

Only the build environment knows about and can use environment variables in most cases, since they are set in the shell during build, but your code is not served from the build environment - it is served without modification after build.

Store your REACT_APP_APIKEY in the Netlify build environment variables and build the .env using a script prior to running the build command.

scripts/create-env.js

const fs = require('fs')
fs.writeFileSync('./.env',`REACT_APP_APIKEY=${process.env.REACT_APP_APIKEY}`)

Run the script as part of your build

node ./scripts/create-env.js 
Sign up to request clarification or add additional context in comments.

Comments

0

Click to see image example

Just add your keys/variables manually here (i.e. the same ones in your .env file). Then rebuild the app.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.