Using Environment Files in a React Application
Environment files allow you to configure and manage sensitive or environment-specific data, such as API keys, URLs, and feature toggles, without hardcoding them into your application. In React applications created with Create React App (CRA), environment variables are managed through .env files. Let’s dive into how this works and how to use them effectively.
How React Handles Environment Variables
-
Default Environment Files: CRA supports multiple
.envfiles based on the environment:-
.env: Loaded for all environments. -
.env.development: Loaded whenNODE_ENVis set todevelopment. -
.env.production: Loaded whenNODE_ENVis set toproduction. -
.env.<custom>: Loaded whenNODE_ENVis set to<custom>.
These files are loaded in a specific priority order:
-
.env(lowest priority) -
.env.<NODE_ENV>(highest priority)
If the same variable is defined in multiple files, the value in the file with the highest priority takes precedence.
-
-
Environment Variable Naming Rules:
- Variables must start with the prefix
REACT_APP_to be available in your React app. For example:REACT_APP_API_URL=https://api.example.com - Variables without the
REACT_APP_prefix are ignored.
- Variables must start with the prefix
-
Accessing Variables:
- You can access these variables in your React code using
process.env:const apiUrl = process.env.REACT_APP_API_URL; console.log(apiUrl); // Outputs the API URL from the environment file
- You can access these variables in your React code using
Setting Up .env Files
-
Create
.envFiles:- In the root of your project, create the
.envfiles you need:-
.envfor default values. -
.env.developmentfor development-specific values. -
.env.productionfor production-specific values.
-
Example
.envfile:REACT_APP_API_URL=https://api.example.com REACT_APP_PUSHER_APP_KEY=your-pusher-key REACT_APP_PUSHER_CLUSTER=mt1 - In the root of your project, create the
-
Set Up Scripts:
- CRA automatically sets
NODE_ENVtodevelopmentwhen runningnpm startandproductionwhen runningnpm build. - To use a custom environment, you can set
NODE_ENVmanually:"scripts": { "start": "NODE_ENV=custom react-scripts start", "build": "NODE_ENV=custom react-scripts build" }
- CRA automatically sets
Using Environment Variables in Your App
Here’s an example of using environment variables in a React application:
// src/config.js
const apiUrl = process.env.REACT_APP_API_URL;
const pusherKey = process.env.REACT_APP_PUSHER_APP_KEY;
const pusherCluster = process.env.REACT_APP_PUSHER_CLUSTER;
export { apiUrl, pusherKey, pusherCluster };
// src/App.js
import React from 'react';
import { apiUrl } from './config';
function App() {
return (
<div>
<h1>API URL: {apiUrl}</h1>
</div>
);
}
export default App;
Key Points to Remember
-
Restart the App After Changes:
- Environment variables are loaded at build time. If you modify a
.envfile, restart your development server.
- Environment variables are loaded at build time. If you modify a
-
Don’t Commit Sensitive Data:
- Never commit
.envfiles to your version control system. Use.gitignoreto exclude them:# .gitignore .env .env.*
- Never commit
-
Use a .env Template:
- Create a
.env.examplefile with placeholder values to share the required variables with your team:REACT_APP_API_URL=<your-api-url> REACT_APP_PUSHER_APP_KEY=<your-pusher-key> REACT_APP_PUSHER_CLUSTER=<your-pusher-cluster>
- Create a
-
Security Note:
- Environment variables in React are bundled into the final build and accessible in the browser’s JavaScript. Avoid storing highly sensitive information, such as private keys or passwords, in
.envfiles.
- Environment variables in React are bundled into the final build and accessible in the browser’s JavaScript. Avoid storing highly sensitive information, such as private keys or passwords, in
Debugging Environment Variables
If an environment variable isn’t working as expected:
- Ensure it starts with
REACT_APP_. - Verify it’s defined in the correct
.envfile for the currentNODE_ENV. - Confirm that your
.envfile is in the project root directory. - Restart the development server after making changes.
Conclusion
Environment files are a powerful way to manage configuration in a React application. By leveraging .env files, you can keep your code clean, avoid hardcoding sensitive data, and streamline deployment for different environments. Just remember to use them securely and follow best practices to get the most out of this feature!