Next.js Environment Variables Explained — Configuration Management
In this tutorial, you will learn about Next.js Environment Variables Explained. We cover key concepts, practical examples, and best practices to help you master this topic.
Next.js supports environment variables through .env files with clear naming conventions: private variables (server-only) and public variables prefixed with NEXT_PUBLIC_ (client-accessible).
What You'll Learn
- .env file types and loading order
- NEXT_PUBLIC_ prefix for client variables
- Server-only environment variables
- Runtime environment variables
- Secrets and security best practices
Why It Matters
Environment variables keep sensitive data (API keys, database URLs) out of your codebase. Next.js provides a clear separation between public and private variables.
# .env.local (local development, git-ignored)
DATABASE_URL=postgresql://localhost:5432/mydb
API_SECRET_KEY=sk-secret-key-here
JWT_SECRET=my-jwt-secret
# NEXT_PUBLIC_ variables are available in browser code
NEXT_PUBLIC_API_URL=https://api.example.com
NEXT_PUBLIC_GA_ID=G-XXXXXXXXXX
// pages/api/users.jsx
export default async function handler(req, res) {
const dbUrl = process.env.DATABASE_URL; // Server only
const apiKey = process.env.API_SECRET_KEY; // Server only
res.json({ message: "Using server-side env vars" });
}
// components/Analytics.jsx
"use client";
export default function Analytics() {
const gaId = process.env.NEXT_PUBLIC_GA_ID; // Available in client
return (
<script
src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`}
strategy="afterInteractive"
/>
);
}
Expected output: Server-side env vars are available in API routes and getServerSideProps, while NEXT_PUBLIC_ variables are available in client components.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro