Environment Variables in React Projects

Modern web applications make heavy use of various types of APIs. To make them work, they need keys or some other information to identify and track each API use. Holding API keys is one of the many applications of environment variables. In general, their primary purpose is to store credentials essential for web development. It also gives application developers a single space to adjust the configuration data when needed. This way, there’s no need to find and edit every instance of configuration data manually.

At first, React environment variables might be confusing, especially for those who don’t have a back-end experience. However, developers who intend to work on large-scale applications should familiarize themselves with environment variables.

Rules for React Environment Variables

Note that the values stored in environment variables are not private. For instance, they’re not practical for storing secret API keys. Once your app is deployed, the environment variable values will be visible in the source code. Every time you add an environment variable, you must restart your application before referencing the value stored in them.

Environment Variables in create-react-app

React projects built with create-react-app with the react-scripts version @0.5.0 or higher support environment variables, so no external package is needed.

As long as you’ve installed the latest version of the create-react-app package, all you need to do is create a .env.local file in the main directory (the same folder that includes README.md, package.json, and other files) and use it to define the variables. Here’s an example:

REACT_APP_CREDENTIAL_DATA = 'some-credential-data'

The .env.local extension is necessary to ensure that the file is automatically added to the .gitignore file when the project is initialized.

To use create-react-app’s built-in support for environment variables, you must prefix the variable names with REACT_APP.

Environment Variables Without create-react-app

If you have a custom React environment without react-scripts you’ll need to install an external package to use environment variables in React.

To this end, you can install a popular dotenv package built specifically for this purpose.

First, you must open the command line in the project folder and install this package:

npm install dotenv

Then, you must make it available and configure the settings. Add the following code to the app:

require('dotenv').config()

Once you do this, you can create a .env.local file in the folder, just like you would for the apps built with create-react-app. You must also start variable names with REACT_APP prefix.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.