Set environment variables in ReactJS
Today we will show you how to set environment variables in ReactJS. If you are working with a large scale application then you may need to set the different value of the environment variables based on application environment like development, test, production, etc.
create react app set environment variables, react-scripts environment variables, react runtime environment variables, create-react-app environment variables not working, react environment variables webpack.
Checkout more articles on ReactJS
In this article, we are providing the example for create-react-app only and this feature is available with [email protected]
and higher version.
Way to set environment variables in ReactJS
- Create react application
- Store environment variables in .env file
- Referencing environment variables in JSX and HTML
- Output
1. Create react application
Let’s start by creating a simple react application with the help of the create-react-app. If you don’t know how to create a react application then refer to the link below.
2. Store environment variables in .env file
Create .env
file at the root level of the project to store the environment variables in create-react-app and define the variables starting with REACT_APP_
.
By default you will have NODE_ENV defined for you.
.env
1 2 | REACT_APP_TEST_VAR=Clue Mediator REACT_APP_WEBSITE=https://cluemediator.com |
Let’s create another file as .env.development
for further explanation.
.env.development
1 | REACT_APP_FILE_NAME=.env.development |
You can also create the .env
file with a different name. While we execute the below listed command then the priority will be taken from left to right.
npm start
:.env.development.local
,.env.development
,.env.local
,.env
npm run build
:.env.production.local
,.env.production
,.env.local
,.env
npm test
:.env.test.local
,.env.test
,.env
Refer to the example below for more understanding.
3. Referencing environment variables in JSX and HTML
In order to use the environment variables in JSX file, we need to fetch the value from the process.env
variable.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import React from 'react'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <p>NODE_ENV: {process.env.NODE_ENV}</p> <p>TEST_VAR: {process.env.REACT_APP_TEST_VAR}</p> <p>WEBSITE: {process.env.REACT_APP_WEBSITE}</p> <p>FILE_NAME: {process.env.REACT_APP_FILE_NAME}</p> </header> </div> ); } export default App; |
We can also access the environment variables in the public/index.html
page.
public/index.html
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE html> <html lang="en"> <head> ... ... <title>%REACT_APP_TEST_VAR% - %NODE_ENV%</title> </head> <body> ... ... </body> </html> |
Note: If you are updating the environment variables while running the application then you have to restart the development server in order to get the changes.