How to Use .env File in Next.js for Environment Variables
In Next.js, create a
.env.local file at your project root to store environment variables. Prefix variables with NEXT_PUBLIC_ to expose them to the browser, then access them in code via process.env.VARIABLE_NAME.Syntax
The .env.local file contains key-value pairs for environment variables. Use the format KEY=VALUE with no spaces around the equals sign.
Variables prefixed with NEXT_PUBLIC_ are exposed to client-side code. Others remain server-only.
Access variables in your Next.js code using process.env.KEY.
bash
NEXT_PUBLIC_API_URL=https://api.example.com
DATABASE_PASSWORD=supersecret123Example
This example shows how to define environment variables in .env.local and use them in a Next.js component.
javascript
// .env.local NEXT_PUBLIC_API_URL=https://api.example.com DATABASE_PASSWORD=supersecret123 // pages/index.js import React from 'react'; export default function Home() { return ( <div> <h1>API URL:</h1> <p>{process.env.NEXT_PUBLIC_API_URL}</p> <h2>Server Secret (undefined on client):</h2> <p>{process.env.DATABASE_PASSWORD || 'Not accessible on client'}</p> </div> ); }
Output
<h1>API URL:</h1>
<p>https://api.example.com</p>
<h2>Server Secret (undefined on client):</h2>
<p>Not accessible on client</p>
Common Pitfalls
- Not restarting the Next.js server after changing
.env.localwill prevent new variables from loading. - Forgetting to prefix variables with
NEXT_PUBLIC_if you want to use them in client-side code. - Committing
.env.localto version control can expose secrets; it should be gitignored.
javascript
/* Wrong: Trying to access server-only variable on client */ console.log(process.env.DATABASE_PASSWORD); // undefined in browser /* Right: Use NEXT_PUBLIC_ prefix for client variables */ console.log(process.env.NEXT_PUBLIC_API_URL); // accessible in browser
Quick Reference
| Concept | Description | Example |
|---|---|---|
| File name | Use .env.local for local env variables | .env.local |
| Variable format | Key-value pairs without spaces | API_URL=https://api.example.com |
| Client exposure | Prefix with NEXT_PUBLIC_ | NEXT_PUBLIC_API_URL=https://api.example.com |
| Access in code | Use process.env.VAR_NAME | process.env.NEXT_PUBLIC_API_URL |
| Security | Do not commit secrets, use .gitignore | Add .env.local to .gitignore |
Key Takeaways
Create a .env.local file at your project root to store environment variables.
Prefix variables with NEXT_PUBLIC_ to make them available in browser code.
Always restart the Next.js server after changing environment variables.
Never commit .env.local to version control to keep secrets safe.
Access variables in code using process.env.VARIABLE_NAME.