How to add Environment variables in React Application

In this tutorial, we will learn about the use of environment variable using the dotenv package. We will study reasons to use environment variables and how to configure them and use in any file of the project.

What are environment variables?

  • They are dynamic-named values that can affect the behaviour of the running process on a computer.
  • They are part of the environment which execute the process
  • We use dotenv package to store the environment variables and they can be used in the files like app.js and other files of the project.

Why we use environment variables?

  • The major reason to use the environment variables to hide the sensitive information of the web app.
  • Eg:- database link we use, as the database has stored all the user information and the whole and soul of a website.
  • This address and cannot be passed directly hence they are stored in the form of environment variable and then passed.

Note:- We use the dotenv package of npm to store and config the variables.

What is dotenv?

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.


  1. Install the package using the below command in the project directory.
    PS D:\work\Codebun\tutorial> npm i dotenv
  2. Create a file specifically named as .env in the root directory.
  3. Require the package in app.js.
  4. Create the variables of database link and PORT number in the .env file.
  5. Use the express to setup server.
  6. Use Mongoose to connect to the database
  7. Use the process.env_varaible name to configure and use the environment variable.


app.js file


const express = require("express");
const app = express();
const mongoose = require('mongoose');

    console.log("DB Connected Successfully");

app.get("/",(req, res)=>{
    res.send("Hello World");

    console.log(`Listening on port ${process.env.PORT}`);

⇒Use the command node app.js to start the server and run the web app.

PS D:\work\Codebun\tutorial> node app.js


Custom Environment Variables in React APP

Create React App supports the use of custom environment variables. To set an environment variable simply follow these steps.

  1. Create a .env file in the root directory of the react application.
  2. To set a custom environment variable use “REACT_APP” as the prefix of any variable. eg:-
  3. This custom environment variable can be processed in any file of the project using process.env. Eg:-
  4. The output will be print as 12345 in the terminal.