React  

How to Handle Environment Variables in React and Next.js Applications

Introduction

Environment variables are a simple but powerful way to manage configuration in modern web applications. Instead of hardcoding values like API URLs, keys, or feature flags inside your code, you store them outside the codebase and load them at runtime or build time.

In React and Next.js applications, environment variables help you manage different environments like development, staging, and production safely and efficiently. They also improve security by keeping sensitive data out of your source code.

In this article, you will learn how to handle environment variables in React and Next.js using simple language, clear examples, and production-ready practices.

What Are Environment Variables?

Environment variables are key-value pairs stored outside your application code.

Example:

API_URL=https://api.example.com
API_KEY=123456

These values can change depending on the environment without modifying your code.

Why Use Environment Variables?

  • Keep sensitive data secure

  • Avoid hardcoding values

  • Easily switch between environments

  • Improve maintainability

  • Support scalable deployments

Types of Environment Variables

  • Development variables

  • Production variables

  • Public variables (safe for frontend)

  • Private variables (server-only)

Environment Variables in React (Create React App)

In React apps (especially Create React App), environment variables must follow a specific naming rule.

Rule: Must start with REACT_APP_

Example:

REACT_APP_API_URL=https://api.example.com

Step 1: Create .env File

Create a .env file in the root folder:

REACT_APP_API_URL=https://api.example.com
REACT_APP_APP_NAME=MyApp

Step 2: Use Variables in Code

const apiUrl = process.env.REACT_APP_API_URL;
console.log(apiUrl);

Step 3: Restart Server

After changing .env, restart your React app:

npm start

Important Notes for React

  • Variables are embedded at build time

  • Do not store secrets (visible in browser)

  • Always prefix with REACT_APP_

Environment Variables in Next.js

Next.js provides more flexibility compared to React.

Step 1: Create .env Files

Next.js supports multiple environment files:

  • .env.local

  • .env.development

  • .env.production

Example:

DATABASE_URL=mongodb://localhost:27017
NEXT_PUBLIC_API_URL=https://api.example.com

Step 2: Public vs Private Variables

  • NEXT_PUBLIC_ → Accessible in browser

  • Without prefix → Server-side only

Example:

// Public
const apiUrl = process.env.NEXT_PUBLIC_API_URL;

// Private (server only)
const dbUrl = process.env.DATABASE_URL;

Step 3: Using Variables in Pages

export default function Home() {
  return <h1>{process.env.NEXT_PUBLIC_API_URL}</h1>;
}

Step 4: Using in API Routes

export default function handler(req, res) {
  const db = process.env.DATABASE_URL;
  res.status(200).json({ db });
}

Environment Variable Loading Order in Next.js

Next.js loads variables in this order:

  1. .env.local

  2. .env.development / .env.production

  3. .env

This helps override values easily.

Managing Multiple Environments

Example:

Development:

NEXT_PUBLIC_API_URL=http://localhost:5000

Production:

NEXT_PUBLIC_API_URL=https://api.myapp.com

Using Environment Variables with Vercel

If deploying on Vercel:

  • Go to Project Settings

  • Add Environment Variables

  • Redeploy app

Using Environment Variables with Docker

You can pass variables using Docker:

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

Common Mistakes

  • Forgetting prefix (REACT_APP_ or NEXT_PUBLIC_)

  • Not restarting server

  • Exposing secrets in frontend

  • Hardcoding values

Best Practices

  • Store secrets only on server side

  • Use .env.local for sensitive data

  • Never commit .env files to Git

  • Use .env.example for reference

  • Validate environment variables at startup

Example .env.example File

NEXT_PUBLIC_API_URL=
DATABASE_URL=
API_KEY=

Advanced Tip: Validation

Use libraries like dotenv-safe or custom validation:

if (!process.env.NEXT_PUBLIC_API_URL) {
  throw new Error("API URL is missing");
}

Difference Between React and Next.js Environment Variables

FeatureReactNext.js
Prefix RequiredYes (REACT_APP_)Only for public (NEXT_PUBLIC_)
Server-side VariablesNoYes
Multiple .env FilesLimitedSupported
FlexibilityMediumHigh

Conclusion

Handling environment variables properly is essential for building secure and scalable React and Next.js applications. It helps you manage configuration, protect sensitive data, and simplify deployments.

By following the steps and best practices in this guide, you can confidently manage environment variables in both React and Next.js projects and avoid common mistakes in production environments.