Next.js Tutorial
- Next.js Introduction
- Next.js Installation
- Project Structure
- Pages & Routing
- Dynamic Routing
- Linking & Navigating
- Data Fetching (SSR)
- Data Fetching (SSG)
- Client-Side Rendering
- API Routes
- Layouts & Components
- Styling
- Image Optimization
- Font Optimization
- Script Optimization
- Middleware
- Environment Variables
- Error Handling
- Authentication
- React Server Components
- Server Actions
- Suspense & Streaming
- Caching & Revalidation
- TypeScript Integration
- Deployment
Environment Variables
Most applications require sensitive configurational values like API Keys, database passwords, and OAuth tokens. Next.js has extensive built-in support for Environment Variables out of the box so you never accidentally commit a secret to GitHub.
The `.env` Files
Next.js automatically looks for several types of `.env` files in your root directory.
.env.local: The main file you use for local development. This overrides everything and must NOT be committed to git..env: Basic defaults. Committing this is fine as long as no secrets are within..env.developmentand.env.production: Apply specifically based on runningnext devornext start.
Server-Side Variables (Secret)
By default, any variable defined in a `.env` file is ONLY available in the Node.js server environment (such as inside `getStaticProps`, Server Components, or API routes).
# .env.local
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
STRIPE_SECRET_KEY="sk_test_123456789"
// Accessing secret variables in an API Route
export async function GET(request) {
// Safe to use here on the server
const dbUrl = process.env.DATABASE_URL;
// Connect to DB...
}If you tried to console.log(process.env.DATABASE_URL) inside a standard Client component, it would safely return undefined to protect your database!
Public Variables (Exposed to Browser)
Sometimes you DO need the browser to know an Environment Variable. For example, your Stripe Publishable Key, or your Firebase Config.
To explicitly tell Next.js to package the variable into the client-side JavaScript bundle, you MUST prefix the variable with NEXT_PUBLIC_.
# .env.local
NEXT_PUBLIC_STRIPE_PUBLIC_KEY="pk_test_987654321"
'use client';
export default function CheckoutForm() {
// This value IS accessible in the browser!
const stripeKey = process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY;
return <button>Pay Now</button>;
}Vercel Configuration
If deploying on Vercel, you do not upload `.env` files. Instead, you enter your keys into the Vercel Dashboard Settings under "Environment Variables". Vercel automatically securely injects them into the Next.js runtime.
Conclusion
Properly splitting your Server and Public environment variables guarantees your app remains secure. Next, let's explore how to gracefully intercept software crashes using Error Handling.