Environment Variables in React JS

How to use environmental variables in a ReactJS applications.

Advert

React JS being a front end language, its common you might not have realised using environment variable is the solution for your problem to declare different API url’s or any other parameter depending on environment (local, staging build and production build). So before I being let me explain the concept of environment variables.

Environmental variables are variables who's value depends on the environment its being executed in, this is used to isolate the applications between Local , Staging and Production environments. In React JS app typical use case is to define the back end URL the build should use.

If you have used Create React App for your ReactJS application its straight forward, support for custom environment variables is packed in the build system.

react-scripts@0.2.3 and higher required

Just change the way you start your project or build your project to

REACT_APP_MY_VAR=test npm start
// In case of build
REACT_APP_MY_VAR=test npm build

Now anywhere in your app you can access the variable using process.env.REACT_APP_MY_VAR

console.log(process.env.REACT_APP_MY_VAR)

It should print out test.

Note : Only the variables that start with REACT_APP_ are embedded in your app. All the other environment variables are ignored. To use other names for environment variable refer second method.

Secondary Method

If you don't use Create React App, want to specify environmental variables in a file or have any other use case you can use Dotenv. Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env

# with npm
npm install dotenv

# or with Yarn
yarn add dotenv

Install the package using yarn or npm. Require and configure dotenv as early as possible in your application.

require('dotenv').config()

Create a .env file in the root directory of your project. Add environment variables on new lines in the form of NAME=VALUE

MY_VAR_1=test1
MY_VAR_2=test2

That's it, process.env will have the keys and values you defined in your .env file.

console.log(process.env.MY_VAR_2)

It should print out test2.

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. Server Side Render ReactJS Application

     
  2. How to Deploy React JS application

     
  3. Environment Variables in React JS

     
  4. Multiple Serialisers in Django ModelViewSet

     
  5. Security Myths

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.