
Create your App Now!
Topics
How do I add an environment variable in React?
Are env variables secure in React?
Where do I set environment variables in React JS?
Can you use environment variables in the frontend?
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
.envfiles, 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:
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:
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 you can create these files in the root directory to define environment variables for different environments.
Example file for development:
You should create a file called In the root directory, store your environment variables.
This file should be named .env and placed in the same directory as your .
You can create environment-specific files to manage multiple environments:
React automatically picks the correct file based on the current environment. For example, when you run:
CRA loads by default. For a production build:
CRA uses .
Once you have defined variables in your env file, you can use them in React code via:
To access an environment variable inside a React component, you can use:
Make sure to restart the dev server after creating or editing an env file, as variables are read at startup.
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.
“ 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 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 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.production
When you run:
React automatically loads .
When you build for production:
It loads .
You can set temporary environment variables for a single shell session without editing env files.
On macOS/Linux:
On Windows Command Prompt:
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:
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 when running the React app.
Here are some recommendations for managing environment variables in a React project:
In custom setups (without CRA), you can configure webpack to inject environment variables into your React code:
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:
Some projects place environment variable files inside the src folder to manage different configurations, but with , it is recommended to keep your files in the root directory instead of the src folder.
.env.development:
.env.production:
Run:
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.
.env.envjscreate react app.env.envpackage.json.env.development.env.staging.env.production.env.development.env.production.env.env.env.env.development.env.staging.env.development.env.productionprocess.env.REACT_APP_API_URLREACT_APP_BACKEND_API_URLREACT_APP_API_URL.env.env.stagingREACT_APP_.gitignore.env.local.envREACT_APP_create react app.envconst apiUrl = process.env.REACT_APP_API_URL;
console.log(apiUrl);
function MyComponent() {
return <div>API URL: {process.env.REACT_APP_API_URL}</div>;
}
const apiBaseUrl = process.env.REACT_APP_API_URL;
fetch(`${apiBaseUrl}/users`)
.then(response => response.json())
.then(data => console.log(data));
"scripts": {
"start:staging": "env-cmd -f .env.staging npm start"
}
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify('https://custom.example.com/api')
});
REACT_APP_API_URL=https://dev.example.com/api
REACT_APP_ANALYTICS_KEY=dev-12345
npm start
npm run build
REACT_APP_API_URL=https://dev.example.com/api
REACT_APP_API_URL=https://staging.example.com/api
REACT_APP_API_URL=https://prod.example.com/api
npm start
npm run build
REACT_APP_MODE=preview npm start
set REACT_APP_MODE=preview && npm start
my-react-app/
│
├── .env.development
├── .env.staging
├── .env.production
├── src/
│ ├── App.js
│
└── package.json
REACT_APP_API_URL=https://dev.example.com/api
REACT_APP_API_URL=https://prod.example.com/api
npm start