Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS + Environment Variables

Just another React Question. I want to store some URL information globally and divided by environment (dev, production etc...).

Searching on web, the usual method is .env files that are naturally supported by react.

I have create a .env and a .env.development so the first will be the production and the second the development file.

Inside the file, I put my configuration like:

# .env.development
REACT_APP_TEST=newyork

I tried to print the values with:

console.log(process.env);
console.log(process.env.REACT_APP_TEST);   

What I get is:

Object
  NODE_ENV:"development"
  PUBLIC_URL:""

The second is undefined.

Where is the problem?

like image 615
RetroMime Avatar asked Jan 23 '26 09:01

RetroMime


2 Answers

If you are using create-react-app, you will need to update your env.js to include your new environment variable in the build.

The function getClientEnvironment(publicUrl) sets the environment variables that get injected into the build for your use. Here, you can add your custom env variable like so:

  {
    // Useful for determining whether we’re running in production mode.
    // Most importantly, it switches React into the correct mode.
    NODE_ENV: process.env.NODE_ENV || 'development',
    // Useful for resolving the correct path to static assets in `public`.
    // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
    // This should only be used as an escape hatch. Normally you would put
    // images into the `src` and `import` them in code to get their paths.
    PUBLIC_URL: publicUrl,
    CUSTOM: process.env.CUSTOM || 'fallback'
  }

UPDATE:

If you're not using CRA, you can use the webpack DefinePlugin to do the same thing.

UPDATE 2:

@DimitarChristoff pointed out that you should use the REACT_APP_* format for declaring env variables. If you prepend your env variable with REACT_APP_, CRA will automatically pick it up and add it to the Webpack DefinePlugin:

// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;
like image 170
Chase DeAnda Avatar answered Jan 25 '26 23:01

Chase DeAnda


It was more simple than expected. The .env files has to be placed in the root of the project NOT in the SRC folder.

That's all!

like image 21
RetroMime Avatar answered Jan 25 '26 22:01

RetroMime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!