Incorrect environment variable setup in .env file

Loading

Proper Environment Variable Setup in React Applications

Environment variables are crucial for configuring your React application across different environments (development, testing, production). Here’s how to set them up correctly to avoid common pitfalls.

Common Mistakes with .env Files

# ❌ Problematic .env examples
API_KEY=12345  # No prefix, will not work in React
SECRET_KEY=mysecret # Exposed in client-side code
BASE_URL=localhost:3000 # Missing REACT_APP_ prefix

Correct .env File Setup

1. Naming Convention (Create React App)

# ✅ Correct - REACT_APP_ prefix required
REACT_APP_API_KEY=your_api_key_here
REACT_APP_BASE_URL=https://api.example.com
REACT_APP_ENVIRONMENT=development

2. Environment-Specific Files

# Project structure
.env                # Default
.env.local          # Local overrides (ignored by git)
.env.development    # Dev environment
.env.test           # Test environment
.env.production     # Production environment

How to Access Environment Variables

// ✅ Accessing in your React components
const apiUrl = process.env.REACT_APP_BASE_URL;

function App() {
  return (
    <div>
      <h1>Environment: {process.env.REACT_APP_ENVIRONMENT}</h1>
    </div>
  );
}

Best Practices

  1. Prefix with REACT_APP_ for Create React App projects
  2. Never commit sensitive data – add .env to .gitignore
  3. Use different files for each environment
  4. Validate variables at application startup
  5. Provide defaults for optional variables
// Example validation
if (!process.env.REACT_APP_API_URL) {
  console.error('Missing required env var: REACT_APP_API_URL');
}

Advanced Configuration

1. Custom Environment Variables (Without CRA)

// If not using Create React App, configure webpack:
// webpack.config.js
const webpack = require('webpack');
const dotenv = require('dotenv');

module.exports = () => {
  const env = dotenv.config().parsed;

  return {
    plugins: [
      new webpack.DefinePlugin({
        'process.env': JSON.stringify(env)
      })
    ]
  };
};

2. TypeScript Support

// env.d.ts
declare namespace NodeJS {
  interface ProcessEnv {
    REACT_APP_API_URL: string;
    REACT_APP_ENV: 'development' | 'production' | 'test';
  }
}

// Access with type safety
const apiUrl: string = process.env.REACT_APP_API_URL;

Security Considerations

  1. Never expose secrets in client-side code
  2. Use server-side environment variables for sensitive data
  3. Consider runtime configuration for dynamic variables
  4. Implement secret rotation for production keys
# ❌ Never do this - secrets will be exposed in bundle
REACT_APP_DB_PASSWORD=supersecret

Troubleshooting

If environment variables aren’t working:

  1. Verify the REACT_APP_ prefix
  2. Restart your development server
  3. Check for typos in variable names
  4. Ensure .env file is in the root directory
  5. Confirm the correct .env file is being loaded
# Debug which env vars are being loaded
console.log(process.env);

Remember that proper environment variable setup is essential for maintaining different configurations across your development, staging, and production environments while keeping sensitive information secure.

Leave a Reply

Your email address will not be published. Required fields are marked *