Use dotenv to store configurations in Reactjs


A modern Reactjs app can be consisting of multiple components, connection to different databases, APIs etc. In other Nodejs projects we can use the dotenv package to store configuration details and can access with process.env.

Is dotenv useful for Reactjs ? Yeh.

Suppose you have using an API in many of the components and wanna some correction in API path, may be a change in basic URL. What we do ? Go through all of the component and change the base URL. Tiresome job !

For such case place the URL in .env (/src) file and use the process.env.REACT_APP_API_SERVER in all of the component. Yo need to change only the .env file for updating base URL.

First up all install the package using

npm i dotenv

and in the App.js , require the package as follows and use it in the component

....
require("dotenv").config();
 .get(`${process.env.REACT_APP_API_SERVER}/post/find`)
      .then((response) => {

        if (response.data.length > 0) {
          this.setState({
            posts: response.data,
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.