0
0
NextjsHow-ToBeginner · 3 min read

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=supersecret123
💻

Example

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.local will prevent new variables from loading.
  • Forgetting to prefix variables with NEXT_PUBLIC_ if you want to use them in client-side code.
  • Committing .env.local to 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

ConceptDescriptionExample
File nameUse .env.local for local env variables.env.local
Variable formatKey-value pairs without spacesAPI_URL=https://api.example.com
Client exposurePrefix with NEXT_PUBLIC_NEXT_PUBLIC_API_URL=https://api.example.com
Access in codeUse process.env.VAR_NAMEprocess.env.NEXT_PUBLIC_API_URL
SecurityDo not commit secrets, use .gitignoreAdd .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.