How to Set Environment Variable in React: Simple Guide
In React, set environment variables by creating a file named
.env in your project root and prefix variables with REACT_APP_. Access them in code using process.env.REACT_APP_YOUR_VARIABLE. Restart the development server after changes to load new variables.Syntax
Environment variables in React must be defined in a .env file at the project root. Each variable name must start with REACT_APP_ to be accessible in your React code. Use process.env.REACT_APP_VARIABLE_NAME to read the value.
Example parts:
REACT_APP_API_URL=https://api.example.com— defines a variableprocess.env.REACT_APP_API_URL— accesses the variable in code
env
REACT_APP_API_URL=https://api.example.com
REACT_APP_MODE=developmentExample
This example shows how to define environment variables and use them inside a React component to display their values.
javascript
/* .env file at project root */ REACT_APP_GREETING=Hello from environment! // src/App.js import React from 'react'; function App() { return ( <div> <h1>{process.env.REACT_APP_GREETING}</h1> </div> ); } export default App;
Output
Hello from environment!
Common Pitfalls
Common mistakes when using environment variables in React include:
- Not prefixing variable names with
REACT_APP_, so React ignores them. - Changing the
.envfile without restarting the development server, so changes don't apply. - Trying to use environment variables directly in the browser console (they are replaced at build time).
- Committing sensitive keys to public repositories (environment variables are visible in the built code).
env
/* Wrong: Missing prefix */ API_KEY=12345 /* Right: With prefix */ REACT_APP_API_KEY=12345
Quick Reference
Summary tips for environment variables in React:
- Always use
REACT_APP_prefix for variables. - Place variables in a
.envfile at the project root. - Restart the React server after editing
.env. - Access variables with
process.env.REACT_APP_VARIABLE_NAME. - Do not store secrets in environment variables for frontend apps.
Key Takeaways
Prefix React environment variables with REACT_APP_ to make them accessible in code.
Define variables in a .env file at the project root and restart the server after changes.
Access variables using process.env.REACT_APP_VARIABLE_NAME inside React components.
Never store sensitive secrets in frontend environment variables as they are exposed in the build.
Use environment variables to configure URLs, modes, and feature flags safely.