# Using Environment Files in a React Application

> Author: [Oussama Ghaieb](https://oussama.ghaieb.com/about-me)
> Canonical: https://oussama.ghaieb.com/posts/using-environment-files-in-a-react-application

# <span class="hover:bg-yellow-100">Using Environment Files in a React Application</span>

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

1. **Default Environment Files:**
   CRA supports multiple `.env` files based on the environment:
   - `.env`: Loaded for all environments.
   - `.env.development`: Loaded when `NODE_ENV` is set to `development`.
   - `.env.production`: Loaded when `NODE_ENV` is set to `production`.
   - `.env.<custom>`: Loaded when `NODE_ENV` is 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.

2. **Environment Variable Naming Rules:**
   - Variables must start with the prefix `REACT_APP_` to be available in your React app. For example:
     ```env
     REACT_APP_API_URL=https://api.example.com
     ```
   - Variables without the `REACT_APP_` prefix are ignored.

3. **Accessing Variables:**
   - You can access these variables in your React code using `process.env`:
     ```javascript
     const apiUrl = process.env.REACT_APP_API_URL;
     console.log(apiUrl); // Outputs the API URL from the environment file
     ```

## Setting Up `.env` Files

1. **Create `.env` Files:**
   - In the root of your project, create the `.env` files you need:
     - `.env` for default values.
     - `.env.development` for development-specific values.
     - `.env.production` for production-specific values.

   Example `.env` file:
   ```env
   REACT_APP_API_URL=https://api.example.com
   REACT_APP_PUSHER_APP_KEY=your-pusher-key
   REACT_APP_PUSHER_CLUSTER=mt1
   ```

2. **Set Up Scripts:**
   - CRA automatically sets `NODE_ENV` to `development` when running `npm start` and `production` when running `npm build`.
   - To use a custom environment, you can set `NODE_ENV` manually:
     ```json
     "scripts": {
       "start": "NODE_ENV=custom react-scripts start",
       "build": "NODE_ENV=custom react-scripts build"
     }
     ```

## Using Environment Variables in Your App

Here’s an example of using environment variables in a React application:

```javascript
// 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 };
```

```javascript
// 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

1. **Restart the App After Changes:**
   - Environment variables are loaded at build time. If you modify a `.env` file, restart your development server.

2. **Don’t Commit Sensitive Data:**
   - Never commit `.env` files to your version control system. Use `.gitignore` to exclude them:
     ```
     # .gitignore
     .env
     .env.*
     ```

3. **Use a .env Template:**
   - Create a `.env.example` file with placeholder values to share the required variables with your team:
     ```env
     REACT_APP_API_URL=<your-api-url>
     REACT_APP_PUSHER_APP_KEY=<your-pusher-key>
     REACT_APP_PUSHER_CLUSTER=<your-pusher-cluster>
     ```

4. **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 `.env` files.

## 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 `.env` file for the current `NODE_ENV`.
- Confirm that your `.env` file 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!
