Sign in
Topics
Create your App Now!
React environment variables help manage configuration across development, staging, and production. They keep settings flexible, prevent hardcoding, and simplify deployment. Learn how to set up
.env
files, map values, and follow best practices.
Environment variables (also known as environmental variables) in a React project let you store configuration values outside the main code, making it easy to manage different settings for development, staging, and production—without hardcoding sensitive data. This keeps your app flexible, secure, and adaptable across environments.
In a React application, environment variables are values that are read from the system or .env files during the build process. These variables make it possible to keep sensitive information such as API keys, URLs, and configuration data separate from the main code.
Storing an API key in an environment variable is a best practice, as it helps prevent exposing the API key in your codebase or version control systems.
For example, if your React app needs different API URLs for development and production, you can store those URLs in different env files and load the correct value based on the active environment.
Environment variables work by being injected into the build process by tools such as webpack configuration in create react app
. In CRA, only variables starting with REACT_APP_
are available in the browser. This restriction exists for security reasons to prevent accidentally exposing server-only variables.
During the build process, React scripts replace these variables with their actual value in the generated static files. The variables are then accessible through the global object process.env
.
A built-in environment variable, such as NODE_ENV
, is a predefined variable available within the environment. It can be used to differentiate between different build or runtime contexts in React, allowing you to manage environment-specific configurations and behaviors.
Got it — here’s the complete Mermaid flowchart, readers can see the entire environment variable journey in React:
What’s new in this complete version:
.env
files clearly mapped to their respective npm scripts.Using environment variables in your React app brings a host of advantages that streamline development and deployment. Here’s why adopting environment variables is a smart move for any React project:
.env
file. This approach keeps your configuration data organized and separate from your application logic, making updates safer and more efficient.js
files. This leads to a cleaner, more maintainable codebase that’s easier to audit and less prone to errors when deploying to multiple environments.In summary, using environment variables in your React application is essential for securely managing sensitive data, supporting multiple environments, and keeping your configuration data flexible and maintainable.
Env files are simple text files containing key-value pairs. In a React project created with create react app
you can create these files in the root directory to define environment variables for different environments.
Example .env
file for development:
1REACT_APP_API_URL=https://dev.example.com/api 2REACT_APP_ANALYTICS_KEY=dev-12345 3
You should create a file called .env
In the root directory, store your environment variables.
This file should be named .env and placed in the same directory as your package.json
.
You can create environment-specific files to manage multiple environments:
.env.development
.env.staging
(used for the staging environment).env.production
(used for the production environment)React automatically picks the correct file based on the current environment. For example, when you run:
1npm start 2
CRA loads .env.development
by default. For a production build:
1npm run build 2
CRA uses .env.production
.
Once you have defined variables in your env file, you can use them in React code via:
1const apiUrl = process.env.REACT_APP_API_URL; 2console.log(apiUrl); 3
To access an environment variable inside a React component, you can use:
1function MyComponent() { 2 return <div>API URL: {process.env.REACT_APP_API_URL}</div>; 3} 4
Make sure to restart the dev server after creating or editing an env file, as variables are read at startup.
1const apiBaseUrl = process.env.REACT_APP_API_URL; 2fetch(`${apiBaseUrl}/users`) 3 .then(response => response.json()) 4 .then(data => console.log(data)); 5
This approach helps you serve a correct URL based on the build target without modifying the source code for different deployments.
Want to manage your React environment variables more easily and securely?
With Rocket.new, you can streamline multi-environment setups and keep your configs organized without hassle.
While environment variables help in separating configuration from code, they do not make sensitive information completely secure in frontend applications. Any variable bundled in the React build can be inspected in the network tab or page source.
“
.env
Files and API Keys: When I Flag Keys but Ignore the Keys to the Keys” How it started:In another session, I was working with the AI to build backend code. For context, I pasted my
.env
file into the chat. This file contained database credentials. Earlier, I had told the AI that the database stored API keys. So even before I sent the.env
file, it knew that those credentials could lead to sensitive data. —- Check the full LinkedIn post here
Mapping environment variables is the process of clearly defining which configuration values belong to each environment in your React application—such as development, staging, and production. This ensures your app behaves correctly in different contexts without needing to modify the codebase every time you switch environments.
A typical example:
Environment | API URL |
---|---|
Development | https://dev.example.com/api |
Staging | https://staging.example.com/api |
Production | https://prod.example.com/api |
React supports environment variables prefixed with REACT_APP_. For example:
.env.development
1REACT_APP_API_URL=https://dev.example.com/api 2
.env.staging
1REACT_APP_API_URL=https://staging.example.com/api 2
.env.production
1REACT_APP_API_URL=https://prod.example.com/api 2
When you run:
1npm start 2
React automatically loads .env.development
.
When you build for production:
1npm run build 2
It loads .env.production
.
process.env.REACT_APP_API_URL
.REACT_APP_BACKEND_API_URL
is clearer than REACT_APP_API_URL
if you have multiple APIs..env
file or environment variables during deployment.You can set temporary environment variables for a single shell session without editing env files.
On macOS/Linux:
1REACT_APP_MODE=preview npm start 2
On Windows Command Prompt:
1set REACT_APP_MODE=preview && npm start 2
Environment variables defined in this way are temporary and only last for the duration of the shell session. Each time you open a new terminal or shell, you will need to define the environment variables again. This is useful for testing different variables quickly.
The env-cmd package allows loading variables from specific env files directly in npm scripts.
Example package.json script:
1"scripts": { 2 "start:staging": "env-cmd -f .env.staging npm start" 3} 4
Tools like env-cmd or Onboardbase can simplify environment configuration by centralizing and securing environment variables, making it easier to manage encrypted, centrally stored variables and integrate them into your workflow.
This command loads .env.staging
when running the React app.
Here are some recommendations for managing environment variables in a React project:
REACT_APP_
– Required by CRA for exposure in React code..gitignore
file – Prevents committing sensitive data to version control..env.local
which overrides other .env
files.REACT_APP_
prefix for variables.In custom setups (without CRA), you can configure webpack to inject environment variables into your React code:
1new webpack.DefinePlugin({ 2 'process.env.API_URL': JSON.stringify('https://custom.example.com/api') 3}); 4
This approach lets you bypass CRA restrictions, but it should be handled carefully.
Avoid storing private API keys, database credentials, or production data in frontend environment variables. Instead, use backend services to manage secrets and provide only necessary information to the frontend.
File structure:
1my-react-app/ 2│ 3├── .env.development 4├── .env.staging 5├── .env.production 6├── src/ 7│ ├── App.js 8│ 9└── package.json 10
Some projects place environment variable files inside the src folder to manage different configurations, but with create react app
, it is recommended to keep your .env
files in the root directory instead of the src folder.
.env.development:
1REACT_APP_API_URL=https://dev.example.com/api 2
.env.production:
1REACT_APP_API_URL=https://prod.example.com/api 2
Run:
1npm start 2
Then check your HTML file output or console logs to verify the variables have the current value expected for that environment.
When running npm test, React loads .env.test if it exists.
Working with React environment variables is a skill every React developer should refine early. Proper usage allows you to switch between different environments effortlessly, keep configuration data organized, and simplify deployment workflows.
Start small—add an .env.development and .env.production file, map your api URLs, and run your builds to confirm the active environment is loading the correct values. Over time, you can expand to more advanced setups with env-cmd, custom webpack configuration, and automated CI/CD pipelines.