React - how to use environment variables

0 points
Created by:

In this article, we would like to show you how to use environment variables in React.

While working with React, environment variables are variables that are available through a global process. Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

1. Defining environment variables in .env file

To define environment variables you need to:

  1. Create new file in the root of your project and call it .env,
  2. Inside .env file create a variable beginning with "REACT_APP_" and assign it a value.


You must create custom environment variables beginning with "REACT_APP_". Any other variables will be ignored.


Setting example environment variable in .env file
Setting example environment variable in .env file


Don't store secret data inside the .env file because anyone can see them by inspecting your app's files.

2. Defining temporary environment variable in command line 

The following examples show how to add an environment variable from the command line. This variable has higher priority over those defined in the .env file so it will be used instead of the existing one.

Windows (cmd.exe) example:

set "REACT_APP_MY_VARIABLE=12345" && npm start

Linux, macOS (Bash) example:

REACT_APP_MY_VARIABLE=12345 npm start


If we use this approach we have to add a variable every time we start the application from cmd/bash.

3. Using environment variable

Regardless of which of the above approaches we choose, we use environment variables the same way.

These environment variables will be defined for you on process.env, for example REACT_APP_MY_VARIABLE will be exposed in JS as process.env.REACT_APP_MY_VARIABLE.

Practical example:

const App = () => {
  return (
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.


React - environment variables
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā