Search code examples
reactjscreate-react-app

Loading values from environment variables in my React application not working


In my React app (using create react app) I have a Constants.js file that has the folowing constants:

export const API_ROOT = process.env.REACT_APP_API_ROOT || 'http://www.example.com.com:4000/api';
export const APP_ROOT = process.env.REACT_APP_APP_ROOT || 'http://app.example.com:3001';

For some reason this is not being picked up on my server even though I have defined the ENV variables on the server. I changed the values around just to see where the values are being picked up from.

API_ROOT=http://dev.example.com/api
APP_ROOT=http://app.example.com
REACT_APP_API_ROOT=http://www.example.com:3002/api
REACT_APP_APP_ROOT=http://app.example.com:3002

I wasn't sure of the naming convention so I defined all 4 of the above. When I push to my server I still see the API_ROOT and APP_ROOT values being the defaults i.e. not from the ENV variable:

  http://www.example.com.com:4000/api
  http://app.example.com:3001

I did verify by logging into the server and verifying the ENV variables existed:

echo $API_ROOT
echo $REACT_APP_API_ROOT

What am I doing wrong in terms of getting the values from ENV variables?


Solution

  • process.env is a global Object provided by your environment through NodeJs. Because we don't have NodeJS in browser, it won't understand process.env.API_ROOT. You init your app using react-create-app with webpack included by default, so I recommend you to use .env file to set environment variables by using dotenv.

    Note: dotenv is included in create-react-app v0.2.3 and higher

    1. Create .env file include

      API_ROOT=http://dev.example.com/api
      APP_ROOT=http://app.example.com
      REACT_APP_API_ROOT=http://www.example.com:3002/api
      REACT_APP_APP_ROOT=http://app.example.com:3002
      
    2. Config webpack:

      const webpack = require('webpack');
      const dotenv = require('dotenv');
      
      module.exports = () => {
        // call dotenv and it will return an Object with a parsed key 
        const env = dotenv.config().parsed;
      
        // reduce it to a nice object, the same as before
        const envKeys = Object.keys(env).reduce((prev, next) => {
          prev[`process.env.${next}`] = JSON.stringify(env[next]);
          return prev;
        }, {});
      
        return {
          plugins: [
            new webpack.DefinePlugin(envKeys)
          ]
        };
      

    Reference:

    Hope this will help.