Module: Production Readiness

Environment Variables

Environment variables are crucial for building production-ready React applications. They allow you to configure your application differently based on the environment it's running in (development, staging, production) without modifying the code itself. This enhances security, flexibility, and maintainability.

Why Use Environment Variables?

  • Security: Avoid hardcoding sensitive information like API keys, database credentials, and secrets directly into your code. Environment variables keep these values separate and secure.
  • Configuration Management: Easily switch between different configurations (e.g., different API endpoints for development and production) without code changes.
  • Portability: Make your application more portable across different environments.
  • CI/CD Integration: Seamlessly integrate with Continuous Integration/Continuous Deployment pipelines by injecting environment variables during build and deployment.

How to Use Environment Variables in React

React provides a built-in mechanism for accessing environment variables prefixed with REACT_APP_.

1. .env Files:

Create .env files in the root of your React project. These files store key-value pairs.

  • .env: Used for development. These variables are available during development.
  • .env.development: Specifically for development environment. Overrides .env.
  • .env.test: Specifically for testing environment. Overrides .env and .env.development.
  • .env.production: Specifically for production environment. Overridden by environment variables set directly on the server.

Example .env file:

REACT_APP_API_URL=http://localhost:3001/api
REACT_APP_DEBUG_MODE=true
REACT_APP_APP_NAME=My Awesome App

Important Notes about .env files:

  • Variables in .env files are loaded during the build process.
  • .env files should never be committed to version control (add .env to your .gitignore file).
  • Variable names must start with REACT_APP_ to be accessible in your React code.
  • Values are stringified. You may need to parse them (e.g., JSON.parse() for objects or Boolean() for booleans).

2. Accessing Environment Variables in Code:

Use process.env to access environment variables within your React components.

const apiUrl = process.env.REACT_APP_API_URL;
const debugMode = process.env.REACT_APP_DEBUG_MODE === 'true'; // Convert to boolean
const appName = process.env.REACT_APP_APP_NAME;

console.log("API URL:", apiUrl);
console.log("Debug Mode:", debugMode);
console.log("App Name:", appName);

3. Building for Production:

When you build your React application for production (e.g., using npm run build or yarn build), Create React App (CRA) will:

  • Read the .env files.
  • Replace all occurrences of process.env.REACT_APP_* with the corresponding values during the build process.
  • Embed these values directly into the production bundle.

4. Server-Side Environment Variables (Production):

In a production environment, you should not rely solely on .env files. Instead, set environment variables directly on your server (e.g., using your hosting provider's configuration settings, Docker Compose, Kubernetes, etc.).

  • Server-side environment variables override any values defined in .env.production.
  • This is the most secure and recommended approach for production deployments.

Example (Node.js server):

export REACT_APP_API_URL=https://api.example.com
npm start

Best Practices

  • Never commit .env files to version control.
  • Use server-side environment variables for production.
  • Prefix all environment variables with REACT_APP_.
  • Be mindful of data types. Environment variables are always strings. Parse them as needed.
  • Consider using a secrets management solution (e.g., HashiCorp Vault, AWS Secrets Manager) for highly sensitive information.
  • Validate environment variables: Check if required environment variables are set during application startup to prevent unexpected errors. You can use a library like dotenv-safe for this.
  • Document your environment variables: Clearly document which environment variables are required and their purpose.

Example Validation (using dotenv-safe)

First install: npm install dotenv-safe

// .env file
REACT_APP_API_KEY=your_api_key

// index.js or app.js
require('dotenv-safe').config();

const apiKey = process.env.REACT_APP_API_KEY;

if (!apiKey) {
  console.error("Error: REACT_APP_API_KEY is not set.");
  process.exit(1); // Exit the application if the API key is missing
}

// ... rest of your application code

By following these guidelines, you can effectively manage environment variables in your React applications, ensuring security, flexibility, and a smooth transition to production.