How to access environment variables from the front-end

There is a very simple way to to that:

Step one: Go to the root folder of your application and create a text file called .env.

Step two: Create your custom variables in the new file. Create React App(CRA) enforces the prefix REACT_APP on every custom variable. Please note that variables without the prefix are ignored during bundling.

REACT_APP_CLIENT_ID=jfjffffaddfeettgydgdffv
REACT_APP_KEY=aaddddawrfffvvvvssaa

Step three: Assign them to variables, print them to the screen etc, but they are read-only from your Javascript file.

console.log(process.env.REACT_APP_CLIENT_ID); 
console.log(process.env.REACT_APP_KEY);

Step four: There is a built-in environment variable called NODE_ENV. You can access it from process.env.NODE_ENV. This variable changes based on what mode you are currently in. When you run npm start, it is equal to ‘development’, when you run npm test it is equal to ‘test’, and when you run npm run build it is equal to ‘production’. This variable is special as it can be used to access different environment configurations based on your mode. For example, if you have different databases for your production and development (usually to prevent interference) you can use it to conditionally access certain variables. The fact that you cannot override NODE_ENV manually prevents developers from accidentally deploying a development build to production.

Step five: Open the .gitignore file. I like to put .env and other environment variables under #misc.

Why Isn’t It Working Even After Following These Processes?

  • Make sure you used the prefix REACT_APP on every variable

  • Confirm that the variable names on the .env file match the ones on your js file. For example,REACT_APP_KEY in .env versus process.env.REACT_APP_KY

  • If the development server was running, stop it then rerun using npm start it. I really struggled with this (variable is undefined error). Every time you update the .env file, you need to stop the server and rerun it, as the environment variables are only updated during build (variable is undefined error).

  • Remove quotations from the values of the variables.

Wrong

REACT_APP_KEY=”AHEHEHR”

Right

REACT_APP_KEY=AHEHEHR

Note: Putting Sensitive content to environment variables doesn’t make them safe. They are injected into the bundled file during the build process so anyone can see them by inspecting your files. I have found their greatest use to be hiding the information before pushing my code to a remote repository.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)