0
0
NextjsHow-ToBeginner · 4 min read

How to Use Environment Variables in Next.js: Simple Guide

In Next.js, you use environment variables by creating files like .env.local and prefixing variables with NEXT_PUBLIC_ to expose them to the browser. Access them in code via process.env.VARIABLE_NAME. Restart the server after changes to load new variables.
📐

Syntax

Environment variables in Next.js are defined in files named .env.local, .env.development, or .env.production. Variables meant for client-side use must start with NEXT_PUBLIC_. Access variables in your code using process.env.VARIABLE_NAME.

Example parts:

  • .env.local: file to store variables locally.
  • NEXT_PUBLIC_API_URL: variable exposed to browser.
  • process.env.NEXT_PUBLIC_API_URL: how to read it in code.
bash
# .env.local
NEXT_PUBLIC_API_URL=https://api.example.com
SECRET_API_KEY=12345
💻

Example

This example shows how to define environment variables and use them in a Next.js component. The variable NEXT_PUBLIC_API_URL is accessible in the browser, while SECRET_API_KEY is only available on the server.

javascript
/* .env.local */
NEXT_PUBLIC_API_URL=https://api.example.com
SECRET_API_KEY=12345

// 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>Secret Key (server only):</h2>
      <p>{typeof window === 'undefined' ? process.env.SECRET_API_KEY : 'Not accessible on client'}</p>
    </div>
  );
}
Output
API URL: https://api.example.com Secret Key (server only): Not accessible on client
⚠️

Common Pitfalls

Common mistakes include:

  • Not prefixing variables with NEXT_PUBLIC_ when you want to use them in the browser, so they won't be available client-side.
  • Forgetting to restart the Next.js server after changing environment variables, so changes don't take effect.
  • Exposing sensitive keys by prefixing them with NEXT_PUBLIC_, which makes them visible in the browser.
javascript
// Wrong: Trying to use secret key on client
<p>{process.env.SECRET_API_KEY}</p>

// Right: Use only public variables on client
<p>{process.env.NEXT_PUBLIC_API_URL}</p>
📊

Quick Reference

ConceptDescriptionExample
Environment fileWhere to put variables.env.local
Public variable prefixExpose to browserNEXT_PUBLIC_
Access in codeUse process.envprocess.env.NEXT_PUBLIC_API_URL
Server-only variableNot exposed to browserSECRET_API_KEY
Restart serverApply changesStop and start dev server

Key Takeaways

Prefix environment variables with NEXT_PUBLIC_ to use them in browser code.
Access variables in Next.js using process.env.VARIABLE_NAME.
Keep sensitive keys without NEXT_PUBLIC_ to keep them server-only.
Always restart the Next.js server after changing environment variables.
Use .env.local for local environment variables that should not be committed.