React  

How to Use Environment Variables in a React App

Introduction

When building a React application, you often need to store configuration details, such as API keys, backend URLs, or feature flags, that differ between development and production environments. Instead of hardcoding these values directly in your source code, you can use environment variables. They help keep your app secure, flexible, and easier to maintain.

What Are Environment Variables?

Environment variables are values that live outside your application’s source code. They are stored in your system or a separate file and can be changed without modifying your app’s actual code.

For example, in a React project, you might want different API endpoints for development and production:

  • Development: http://localhost:5000/api

  • Production: https://myapp-production.com/api

By using environment variables, you can easily switch between these configurations without touching your main codebase.

Why Use Environment Variables in React?

Here are a few key reasons:

  1. Security – Sensitive information, such as API keys or tokens, should not be exposed in your code repository.

  2. Flexibility – Easily change configurations between environments (development, testing, production).

  3. Cleaner Code – Keeps your code organized by separating logic from configuration.

  4. Automation – Facilitates deployment by utilizing environment-specific configurations.

Setting Up Environment Variables in React

React (especially when created using Create React App) makes it very easy to use environment variables. Here’s how you can set them up:

Step 1: Create a .env File

In the root directory of your React app (same level as package.json), create a file called .env.

Example:

my-react-app/
│
├── src/
├── public/
├── package.json
└── .env

Step 2: Add Environment Variables

Inside the .env file, define your variables. All environment variables in React must start with REACT_APP_.

Example:

REACT_APP_API_URL=https://api.myapp.com
REACT_APP_API_KEY=12345-abcdef

Step 3: Use Variables in Your React Code

To access these variables inside your React components, use process.env followed by the variable name.

Example:

function App() {
  const apiUrl = process.env.REACT_APP_API_URL;
  const apiKey = process.env.REACT_APP_API_KEY;

  return (
    <div>
      <h1>Using Environment Variables in React</h1>
      <p>API URL: {apiUrl}</p>
      <p>API Key: {apiKey}</p>
    </div>
  );
}

export default App;

When you run your React app using npm start or yarn start, these values will automatically load from your .env file.

Setting Different Environments

You can create multiple environment files for different stages of your app’s lifecycle:

.env                 # Default
.env.development     # Used in development
.env.production      # Used in production
.env.test            # Used during testing

React automatically picks the right file based on the environment you’re running.

Example content of .env.development:

REACT_APP_API_URL=http://localhost:5000/api

Example content of .env.production:

REACT_APP_API_URL=https://api.myapp.com

When you build your app with npm run build, React will use .env.production automatically.

Important Tips for Using Environment Variables Safely

  1. Never commit .env files to GitHub – Add .env to your .gitignore file.

  2. Do not store sensitive keys in the frontend – Remember, React runs in the browser, so anything in the .env file can still be visible to users. Use backend servers to store truly secret information.

  3. Restart your app – Whenever you change a variable in the .env file, restart your React server for changes to take effect.

  4. Use placeholders for missing variables – You can set defaults in your code if a variable is undefined.

Example:

const apiUrl = process.env.REACT_APP_API_URL || 'http://localhost:5000';

How to Check Your Environment Variables

To debug or verify that your variables are working correctly, you can log them in your console:

console.log('API URL:', process.env.REACT_APP_API_URL);

This helps ensure your variables are loaded properly in both development and production environments.

Summary

Using environment variables in React is an easy and secure way to manage configuration settings for your app. By using .env files and process.env, you can define variables that adjust automatically based on the environment (development, test, or production). This makes your app more flexible, maintainable, and professional.