To use an .env
file in a React application, especially when built with Create React App, you define environment-specific variables within this file and then access them throughout your application via the global process.env
object.
Here's a step-by-step guide to effectively utilize .env
files in your React projects:
Why Use .env
Files?
.env
files provide a convenient way to manage configuration settings that vary between different deployment environments (development, production, testing). They allow you to:
- Hide Sensitive Information: Keep API keys, database credentials, or other sensitive data out of your public code repository.
- Manage Environment-Specific Settings: Easily switch between different API endpoints, debug modes, or other configurations based on the environment your app is running in.
- Improve Maintainability: Centralize configuration, making your application easier to manage and deploy.
Step-by-Step Guide to Using .env
in React (Create React App)
Create React App (CRA) provides built-in support for .env
files without requiring additional packages.
1. Create Your .env
File
First, create a new file named .env
in the root directory of your React project. This is the same level as your package.json
file.
my-react-app/
├── public/
├── src/
├── .env <-- Create this file
└── package.json
2. Define Environment Variables
Inside your newly created .env
file, add your key-value pairs. It's crucial that all custom environment variables in a Create React App project begin with REACT_APP_
. Variables without this prefix will be ignored by Create React App and will not be accessible in your application.
Example .env
file:
REACT_APP_API_URL=https://api.example.com/v1
REACT_APP_ANALYTICS_ID=UA-XXXXX-Y
REACT_APP_MODE=development
Important Note: Do not add quotes around your values unless you intend for the quotes to be part of the value itself. For instance, REACT_APP_SOME_VAR="Hello World"
will include the quotes in the variable's value.
3. Restart Your Development Server
After creating or modifying your .env
file, you must restart your development server for the changes to take effect. Environment variables are loaded when the server starts.
To restart:
- If your server is running, stop it (usually by pressing
Ctrl + C
in the terminal). - Start it again using your usual command:
npm start
yarn start
4. Access Variables in Your React App
Once your server is restarted, your new variables will be available throughout your React application via the global process.env
object.
Example of accessing a variable in a React component:
import React from 'react';
function MyComponent() {
const apiUrl = process.env.REACT_APP_API_URL;
const analyticsId = process.env.REACT_APP_ANALYTICS_ID;
return (
<div>
<p>API URL: {apiUrl}</p>
<p>Analytics ID: {analyticsId}</p>
<p>Current Mode: {process.env.REACT_APP_MODE}</p>
</div>
);
}
export default MyComponent;
Best Practices and Important Considerations
- Security: Never commit sensitive API keys or credentials directly to your public Git repository. Add your
.env
file to your.gitignore
file to prevent it from being tracked and pushed.# .gitignore .env
- Environment-Specific Files: For different environments (e.g., development, production, testing), Create React App supports specific
.env
files:.env.development
: Loaded in development mode (npm start
)..env.production
: Loaded in production mode (npm run build
)..env.test
: Loaded when running tests (npm test
)..env.local
: Overrides any other environment file (e.g.,.env.development.local
will override.env.development
).
Variables from specific files will take precedence over those in the generic.env
file.
- Build Process: When you build your application for production (
npm run build
), Create React App embeds the values of yourREACT_APP_
prefixed environment variables directly into the static HTML, CSS, and JavaScript bundle. This means that once built, the values are fixed for that specific build. If you need to change them without rebuilding, you'll need a different strategy (e.g., server-side environment variables, or a runtime configuration solution). - Client-Side Exposure: Remember that any variable starting with
REACT_APP_
will be embedded into the client-side JavaScript bundle. This means anyone can inspect your code and see these values. For truly sensitive data (e.g., secret keys that should only ever be used on a server), they should be stored on your backend server and never exposed directly to the React frontend.
Summary of .env
Usage in React
Here's a quick overview of the key aspects:
Feature | Description | Example |
---|---|---|
File Location | Must be in the root directory of your project. | my-react-app/.env |
Variable Prefix | All custom variables accessible in the client-side React app must start with REACT_APP_ when using Create React App. |
REACT_APP_API_URL=https://myapi.com |
Access Method | Variables are exposed through the global process.env object. |
process.env.REACT_APP_API_KEY |
Server Restart | Any changes to .env files require restarting the development server to load the new variables. |
Stop and restart npm start / yarn start |
Security Best Practice | Add .env to .gitignore to prevent sensitive data from being committed to version control. |
Add .env to your project's .gitignore file. |
Environment-Specific | Use .env.development , .env.production , etc., for different environments. |
REACT_APP_MODE=development (in .env.development ) |
By following these steps, you can effectively manage environment variables in your React applications, making them more robust and secure.