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>;
}

Join the conversation! Your thoughts help the community grow.