| How to Avoid Overengineering React Applications :👈 | 👉:Common React Architecture Mistakes |
How to Manage Environment Variables in React |
How to Manage Environment Variables in React
1. What Are Environment Variables?
Environment variables are configuration values used by an application that can change depending on the environment in which the application runs.
For example, a React application may use different API URLs for development, testing, and production.
- Development: http://localhost:5000/api
- Testing: https://test-api.example.com/api
- Production: https://api.example.com/api
Instead of hardcoding these values throughout the application, we store them in environment variables.
2. Why Use Environment Variables?
- Environment-specific configuration: Use different settings for development, testing, and production.
- Maintainability: Change configuration without modifying application source code.
- Centralized configuration: Keep API URLs and other settings in one place.
- Deployment flexibility: Configure the application differently for each deployment environment.
- Reduced hardcoding: Avoid repeating configuration values throughout components and services.
3. Creating Environment Variables in React
The syntax depends on the React build tool. Two commonly used options are Vite and Create React App.
A. React with Vite
Vite is a modern frontend build tool commonly used for new React applications.
Step 1: Create a .env file
Create a file named .env in the project root directory.
VITE_API_BASE_URL=http://localhost:5000/api
VITE_APP_NAME=My React Application
Step 2: Access environment variables
Use import.meta.env to access environment variables in your React application.
const apiUrl = import.meta.env.VITE_API_BASE_URL;
console.log(apiUrl);
Step 3: Use the variable in an API service
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
export async function getUsers() {
const response = await fetch(`${API_BASE_URL}/users`);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
}
Important: Vite exposes only variables prefixed with VITE_ to client-side application code by default.
B. React with Create React App
Create React App uses a different naming convention.
Step 1: Create a .env file
REACT_APP_API_BASE_URL=http://localhost:5000/api
REACT_APP_NAME=My React Application
Step 2: Access environment variables
Use process.env to access environment variables.
const apiUrl = process.env.REACT_APP_API_BASE_URL;
console.log(apiUrl);
Step 3: Use the variable in an API service
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL;
export async function getUsers() {
const response = await fetch(`${API_BASE_URL}/users`);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
}
Important: Create React App exposes variables prefixed with REACT_APP_. Create React App is deprecated for new projects; Vite or another modern setup is generally preferred.
4. Managing Multiple Environments in Vite
In real-world applications, we generally maintain different configuration files for different environments.
Vite supports environment-specific files.
Example project structure
my-react-app/
│
├── .env
├── .env.development
├── .env.production
├── .env.staging
│
├── src/
│ ├── services/
│ │ └── api.js
│ ├── components/
│ └── App.jsx
│
├── package.json
└── vite.config.js
.env.development
VITE_API_BASE_URL=http://localhost:5000/api
.env.staging
VITE_API_BASE_URL=https://staging-api.example.com/api
.env.production
VITE_API_BASE_URL=https://api.example.com/api
Vite automatically loads the appropriate environment-specific file based on the selected mode.
5. How to Run React in Different Environments
For a Vite application, use the following commands:
Development
npm run dev
Vite uses development mode and loads .env.development, when present.
Production build
npm run build
Vite uses production mode and loads .env.production, when present.
Staging build
npx vite build --mode staging
This command loads .env.staging.
You can also define convenient scripts in package.json:
{
"scripts": {
"dev": "vite",
"build": "vite build",
"build:staging": "vite build --mode staging",
"build:production": "vite build --mode production"
}
}
6. Environment Variable Loading Priority
Vite loads environment files according to the selected mode. More specific mode files take precedence over general files.
For example, in production mode:
.env.production.local.env.production.env.local.env
Existing environment variables supplied by the operating system have higher priority than values from environment files.
7. Centralize Environment Configuration
Instead of accessing environment variables directly in multiple components, create a centralized configuration file.
src/config/env.js
const env = {
apiBaseUrl: import.meta.env.VITE_API_BASE_URL,
appName: import.meta.env.VITE_APP_NAME
};
if (!env.apiBaseUrl) {
throw new Error("VITE_API_BASE_URL is not configured");
}
export default env;
Use it in your API service:
import env from "../config/env";
export async function getProducts() {
const response = await fetch(`${env.apiBaseUrl}/products`);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
return response.json();
}
Benefits:
- All configuration is maintained in one place.
- Missing configuration can be detected early.
- Components do not need to know how environment variables are loaded.
- Configuration changes become easier to maintain.
8. Important Security Considerations
Never store sensitive information in frontend environment variables.
This is one of the most important rules when working with React.
React applications run in the user's browser. Variables exposed to frontend code can be discovered by inspecting the built JavaScript files or browser developer tools.
Examples of values that are generally safe to expose
- Public API base URLs.
- Application display names.
- Public feature flags.
- Non-sensitive analytics configuration.
Examples of values that must remain on the server
- Database passwords.
- Private API keys.
- JWT signing secrets.
- Client secrets.
- Private access tokens.
Incorrect example:
VITE_DATABASE_PASSWORD=myPassword123
VITE_PRIVATE_API_KEY=secret-key
These values are exposed to the frontend bundle if accessed through client-side code.
Correct approach:
Store sensitive credentials in the backend environment configuration. The React application should call the backend API, and the backend should communicate with databases and external services using its private credentials.
9. Environment Variables and .gitignore
Environment files may contain local configuration and sometimes secrets intended for server-side use. Avoid committing local and secret-bearing files to Git.
Add the following entries to .gitignore:
.env
.env.local
.env.*.local
For Vite, you can safely commit example configuration files that contain placeholders and no secrets.
.env.example
VITE_API_BASE_URL=
VITE_APP_NAME=
This helps other developers understand which variables they need to configure.
10. Common Mistakes
| Mistake | Correct Approach |
|---|---|
Using process.env in a standard Vite React project |
Use import.meta.env. |
Forgetting the VITE_ prefix |
Use the required prefix for client-exposed variables. |
| Storing passwords in frontend environment files | Keep secrets in backend configuration. |
| Changing an environment file without restarting the development server | Restart the Vite development server when necessary. |
| Using the wrong environment mode | Check the build command and selected mode. |
| Hardcoding API URLs in multiple components | Centralize configuration in one module. |
| Committing local secret-bearing files to Git | Use .gitignore and provide an example file. |
11. Recommended Best Practices
- Use environment variables for configuration that changes between environments.
- Use
VITE_prefixes for variables exposed to Vite frontend code. - Centralize configuration in a dedicated file such as
src/config/env.js. - Validate required configuration during application startup.
- Maintain separate development, staging, and production configurations when needed.
- Never expose passwords, private keys, or backend secrets in React.
- Use deployment-platform configuration for production values where appropriate.
- Keep an
.env.examplefile to document required variables. - Remember that frontend environment variables are generally embedded during the build process.
12. Build-Time vs Runtime Environment Variables
This distinction is important when deploying React applications.
Build-time configuration
With a typical Vite build, environment variables are replaced or embedded into the generated JavaScript during the build.
For example, if you build with:
VITE_API_BASE_URL=https://api.example.com/api
the generated frontend bundle contains that configured value.
Changing the server's environment variable after the build does not automatically update the already-generated JavaScript bundle.
Runtime configuration
If the same frontend build must run in different environments without rebuilding it, use a runtime configuration mechanism.
For example, the server can provide a public configuration file:
public/config.json
{
"apiBaseUrl": "https://api.example.com/api"
}
The React application can load it before rendering:
async function loadConfig() {
const response = await fetch("/config.json");
if (!response.ok) {
throw new Error("Unable to load application configuration");
}
return response.json();
}
loadConfig().then(config => {
console.log(config.apiBaseUrl);
});
In a real application, load the configuration before rendering components that depend on it, for example through an application bootstrap process.
Important: Runtime configuration is also public. Do not put secrets in config.json.
13. Build-Time vs Runtime Comparison
| Feature | Build-Time | Runtime |
|---|---|---|
| When values are loaded | During application build | When the application runs |
| Changing API URL | Usually requires rebuilding | Can change without rebuilding |
| Implementation | Vite environment variables | Public configuration file or endpoint |
| Typical use | Separate builds for each environment | One build deployed to multiple environments |
14. Real-World Example: React with ASP.NET Core Web API
Consider an application with a React frontend and an ASP.NET Core backend.
Development environment:
VITE_API_BASE_URL=https://localhost:7001/api
Production environment:
VITE_API_BASE_URL=https://api.mycompany.com/api
React reads the API URL from its configuration and calls the ASP.NET Core Web API.
// src/services/userService.js
import env from "../config/env";
export async function getUsers() {
const response = await fetch(`${env.apiBaseUrl}/users`);
if (!response.ok) {
throw new Error("Unable to retrieve users");
}
return response.json();
}
The ASP.NET Core backend maintains its own private configuration, such as database connection strings and API credentials. These values should never be sent to React.
15. Interview Questions and Answers
Q1. What are environment variables in React?
Environment variables are configuration values used to manage environment-specific settings such as API URLs, application names, and feature flags.
Q2. How do you access environment variables in Vite?
Use import.meta.env. For example, import.meta.env.VITE_API_BASE_URL.
Q3. What is the difference between Vite and Create React App environment variables?
Vite uses import.meta.env and the VITE_ prefix, whereas Create React App uses process.env and the REACT_APP_ prefix.
Q4. Can we store API secrets in React environment variables?
No. Frontend environment variables can be exposed in the browser bundle. Sensitive credentials must be stored securely on the backend.
Q5. How do you manage development and production API URLs?
Create environment-specific files such as .env.development and .env.production, then build or run the application using the appropriate mode.
Q6. What is the purpose of a .env.example file?
It documents the environment variables required by the project without exposing actual secrets or machine-specific values.
Q7. What is the difference between build-time and runtime configuration?
Build-time configuration is included when the frontend is built. Runtime configuration is loaded when the application runs and can be changed without rebuilding the frontend.
Q8. Why should environment configuration be centralized?
Centralization improves maintainability, avoids repeated configuration access, and makes it easier to validate required values.
16. Key Takeaways
- Environment variables help manage different configurations for development, staging, and production.
- Vite uses
import.meta.envand theVITE_prefix. - Create React App uses
process.envand theREACT_APP_prefix. - Centralize environment configuration instead of accessing it throughout components.
- Never store sensitive credentials in frontend environment variables.
- Understand the difference between build-time and runtime configuration before deploying React applications.
| How to Avoid Overengineering React Applications :👈 | 👉:Common React Architecture Mistakes |
Comments and Discussion