Environment variables in Create React App
In this article, I’ll be sharing about How to create environment variables in Ejected Create React App.
Why we need to use environment variables?
Mostly our app configurations are different in all servers like Development, Testing, Production and more servers like that. Example: Normally Service Worker is not using in Development & Testing Server. It’ll be used only in Production Server.
How to create Environment Variables?
If we want to use custom environment variables in create react app, we need to eject create react app by following command.
npm run eject
Create a .env
file in the root directory of our project. Then we can add environment specific variables on new lines. I’ve placed a example below.
SERVICE_WORKER=0
REACT_APP_API_URL="https://devangbhuva97.github.io/"
Add .env
file in .gitignore
. so it doesn’t find itself in GitHub. Create copy of .env
file as .env.example
for getting reference in Servers.
Find getClientEnvironment
function from config/env.js
for adding .env
files variables. I’ve placed a gist that updated function.
How to use Environment Variables?
Now we can use variables from anywhere in our project as process.env.VARIABLE_NAME
. I’ve placed a example below with use-case of variable.
Example:
Without any condition registerServiceWorker()
function called in main index.js
file. Now, we want to call that function in only Production Server. So define SERVICE_WORKER=1
in production server’s .env
file & SERVICE_WORKER=0
in other server’s .env
file. Now update index.js
file as below gist.
If you have some suggestions/doubts, you can tweet me at @devangbhuva97.
This article is a part of a series on Environment Variables:
1. What are Environment Variables?
2. Environment variables in Create React App
3.Environment Variables : Webpack config using DefinePlugin