Skip to content

Environment Variables

Environment variables store configuration settings that may differ between environments (e.g., development, testing, production). Managing these variables properly ensures a secure and flexible application.


Why Use Environment Variables?

  • Security: Keep sensitive information like API keys out of your codebase.
  • Flexibility: Configure settings for different environments without modifying code.
  • Portability: Share configuration with other team members easily.

Creating Environment Variables

Step 1: Add a .env File

Create a .env file in your project root. This file will store your environment variables.

Example .env file
REACT_APP_API_URL=https://api.example.com
REACT_APP_API_KEY=your_api_key_here
NODE_ENV=development

Step 2: Add .env to .gitignore

To prevent sensitive data from being committed to version control, add .env to your .gitignore file:

.env

Accessing Environment Variables

React Applications

Environment variables in React must start with REACT_APP_ to be accessible within the codebase.

const apiUrl = process.env.REACT_APP_API_URL;
console.log(`API URL: ${apiUrl}`);

Node.js Applications

In Node.js, you can access environment variables directly using process.env.

const apiKey = process.env.API_KEY;
console.log(`API Key: ${apiKey}`);

Best Practices

  1. Prefix Variables for Clarity

    Use prefixes like REACT_APP_ or API_ to categorize variables logically.

  2. Use a Library for Type Safety

    Libraries like dotenv or env-cmd help load and manage environment variables safely.

    npm install dotenv
    
    Example usage
    require("dotenv").config();
    const dbHost = process.env.DB_HOST;
    
  3. Set Defaults

    Provide fallback values in case environment variables are missing:

    const port = process.env.PORT || 3000;
    
  4. Secure Sensitive Information

    Store sensitive variables like API keys in a secure environment, such as cloud provider secrets (e.g., AWS Secrets Manager, Azure Key Vault).


Environment Variable Management Tools

1. dotenv

  • Loads variables from a .env file into process.env.
  • Suitable for local development.

2. env-cmd

  • Handles multiple .env files for different environments.

3. direnv

  • Manages per-directory environment variables.

4. Cloud-Based Solutions

  • AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault for production.

Deployment-Specific Configuration

Vercel

In the Vercel dashboard, go to the project settings and add environment variables under the "Environment Variables" section.

Netlify

In the Netlify dashboard, go to "Site Settings" > "Build & Deploy" > "Environment" and add variables there.

Docker

Pass environment variables using the -e flag:

docker run -e API_URL=https://api.example.com my-app

With proper management of environment variables, you can enhance security, flexibility, and portability in your applications.