Topic 43 of 47
.env.local
Overview
Next.js has built-in support for environment variables. By default, variables are only accessible on the server. To expose a variable to the browser (Client Components), you must prefix it with `NEXT_PUBLIC_`.
Syntax
tsx
// .env.local
DATABASE_URL="postgresql://user:pass@localhost:5432/db" # Server only
STRIPE_SECRET_KEY="sk_test_123" # Server only
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_test_123" # Server AND Client
// In a Server Component (app/page.tsx)
const db = process.env.DATABASE_URL; // ✅ Works
const pubKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY; // ✅ Works
// In a Client Component (app/Button.tsx - 'use client')
const secret = process.env.STRIPE_SECRET_KEY; // ❌ UNDEFINED!
const pubKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY; // ✅ WorksCommon Pitfalls
- Never store secrets (passwords, private API keys) in variables prefixed with `NEXT_PUBLIC_`. They will be visible in the compiled JavaScript sent to the browser.
- `.env.local` should be added to your `.gitignore`. Do not commit it to your repository.
Real-World Example
Defining and accessing API URLs safely:
example
tsx
// .env.local
NEXT_PUBLIC_API_URL="https://api.myapp.com/v1"
// lib/apiClient.ts
// This can be safely used in both Server and Client components
export const fetchApi = async (endpoint: string) => {
const baseUrl = process.env.NEXT_PUBLIC_API_URL;
const res = await fetch(`${baseUrl}${endpoint}`);
return res.json();
};