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.

Steps:-

  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.
    require('dotenv').config()
    
  4. Create the variables of database link and PORT number in the .env file.
    URL=mongodb://localhost:27017/Tutorial
    PORT=2000
  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.

Code:- 

app.js file

require('dotenv').config()

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

mongoose.connect(process.env.URL,{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true
}).then(()=>{
    console.log("DB Connected Successfully");
});

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

console.log(process.env.PORT)
app.listen(process.env.PORT,()=>{
    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

Output

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:-
    REACT_APP_TEST=123456
  3. This custom environment variable can be processed in any file of the project using process.env. Eg:-
    console.log(process.env.REACT_APP_test)
  4. The output will be print as 12345 in the terminal.