How to Use Environment Variables with Create-React-App
Environment Variables are a critical tool in getting your app set up correctly, but can be tricky for beginners. Create React App also has a couple other nuances to be aware of.
For background, environment variables are how we wire things up to behave differently between different environments (i.e. development vs production). For instance, you often need your dev environment to point to a different API, or for your payments library to only charge money in production, etc.
Setting Values
If you’re using Create-React-App, you can add your own custom environment variables.
- create a file called in the root directory of your project
.env
- add a new line in the file for each variable you need, making sure to prefix the variable name with . For instance:
REACT_APP_
REACT_APP_API_URL=http://api.example.com
🚨 Don’t miss this! The variable name must start with
otherwise it won’t work.REACT_APP_
- Restart the dev server.
Reading Values
Environment variable values can be read using
process.env.REACT_APP_VARIABLE_NAME
render() {
return (
<div>
Current API url: {process.env.REACT_APP_API_URL}.
</div>
)
}
A few more things…
-
Client side
values are not secret. They can be found by anyone who wants to sift through your site’s JavaScript code..env
-
files should be committed and tracked in version control with the rest of your project.
.env
-
You may want some environment variables that are only for you specifically (not necessarily others on your team) that you don’t want to be tracked via version control. For these, you can create another file in the project root, called
. Variables placed here will override the.env.local
value if both are present. This file should not be committed or tracked in version control..env
-
Changes to
files don’t take effect until you restart the server..env
-
To comment out a line in a
file, prefix it with a “#” character, like so:.env
# REACT_APP_API_URL=http://api.example.com
REACT_APP_API_URL=http://api2.example.com
- Create-React-App comes with one default environment variable out-of-the-box: . This will be set to “development”, “test”, or “production” depending on your current environment. It can be read from
NODE_ENV
.process.env.NODE_ENV
For more details, check the official Create React App docs.
Follow me on Twitter!
Want more? Did I get something wrong? @markadamfoster