Set environment variables in ReactJS

Today we will show you how to set environment variables in ReactJS. If you are working with a large scale application then you may need to set the different value of the environment variables based on application environment like development, test, production, etc.

create react app set environment variables, react-scripts environment variables, react runtime environment variables, create-react-app environment variables not working, react environment variables webpack.

In this article, we are providing the example for create-react-app only and this feature is available with [email protected] and higher version.

Way to set environment variables in ReactJS

  1. Create react application
  2. Store environment variables in .env file
  3. Referencing environment variables in JSX and HTML
  4. Output

1. Create react application

Let’s start by creating a simple react application with the help of the create-react-app. If you don’t know how to create a react application then refer to the link below.

Create React Application

2. Store environment variables in .env file

Create .env file at the root level of the project to store the environment variables in create-react-app and define the variables starting with REACT_APP_.

By default you will have NODE_ENV defined for you.

.env

Let’s create another file as .env.development for further explanation.

.env.development

You can also create the .env file with a different name. While we execute the below listed command then the priority will be taken from left to right.

  • npm start: .env.development.local, .env.development, .env.local, .env
  • npm run build: .env.production.local, .env.production, .env.local, .env
  • npm test: .env.test.local, .env.test, .env

Refer to the example below for more understanding.

3. Referencing environment variables in JSX and HTML

In order to use the environment variables in JSX file, we need to fetch the value from the process.env variable.

App.js

We can also access the environment variables in the public/index.html page.

public/index.html

Note: If you are updating the environment variables while running the application then you have to restart the development server in order to get the changes.

4. Output

Output - Set environment variables in ReactJS - Clue Mediator
Output – Set environment variables in ReactJS – Clue Mediator

Demo & Source Code

Github Repository

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *