Oussama GHAIEB

Tips, tricks, and code snippets for developers

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

  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: 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:
      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:

    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:
      "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:

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

  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: 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!

Tags: #react
Oussama GHAIEB - Laravel Certified Developer in Paris

Oussama GHAIEB

Laravel Certified Developer | Full-Stack Web Developer in Paris

14+ years experience 20+ projects
Read more about me →

Comments (0)

No comments yet. Be the first to comment!


Leave a Comment