Using Environment Variables in Next.js – Secure Loading, Browser Access, and Runtime Configuration

Next.js has built-in support for environment variables. This article explains how to load variables from .env files, expose them to the browser using NEXT_PUBLIC_, access them at runtime, configure them for testing, and understand the load order across environments.

Environment variablesNEXT_PUBLICRuntime access.env test

~2 min read · Updated Oct 27, 2025

Loading Environment Variables


Next.js automatically loads environment variables from .env* files into process.env. Example:

# .env
DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

These variables are available in the Node.js environment, such as in Route Handlers:

export async function GET() {
  const db = await myDB.connect({
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
  })
}

Multiline Variable Support


You can define multiline secrets using line breaks or \n:

PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END DSA PRIVATE KEY-----"

Loading Outside Next.js Runtime with @next/env


To load variables in config files or test runners, use the @next/env package:

import { loadEnvConfig } from '@next/env'

const projectDir = process.cwd()
loadEnvConfig(projectDir)

Referencing Other Variables


You can reference other variables using $:

# .env
TWITTER_USER=nextjs
TWITTER_URL=https://x.com/$TWITTER_USER

To use $ literally, escape it with \$.


Browser Access with NEXT_PUBLIC_


To expose a variable to the browser, prefix it with NEXT_PUBLIC_:

NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk

It will be inlined into the JavaScript bundle at build time:

setupAnalyticsService(process.env.NEXT_PUBLIC_ANALYTICS_ID)

Note: Dynamic references like process.env[varName] won’t be inlined.


Runtime Environment Variables


During dynamic rendering, you can access variables at runtime:

export default async function Component() {
  await connection()
  const value = process.env.MY_VALUE
}

This is useful for Docker images promoted across multiple environments.


Environment Variables in Testing


Use .env.test for test-specific variables. .env.local is ignored in test mode to ensure consistency.

To load variables during tests:

import { loadEnvConfig } from '@next/env'

export default async () => {
  const projectDir = process.cwd()
  loadEnvConfig(projectDir)
}

Environment Variable Load Order


Variables are resolved in the following order:

  1. process.env
  2. .env.$(NODE_ENV).local
  3. .env.local (ignored in test)
  4. .env.$(NODE_ENV)
  5. .env

For example, if NODE_ENV is development, .env.development.local takes priority.


Good to Know


  • .env files must be in the root directory, not inside /src
  • If NODE_ENV is unset, Next.js defaults to development for next dev and production otherwise
  • .env.local files should be gitignored and not committed

Conclusion


Environment variables in Next.js offer a secure and flexible way to manage configuration across environments. By using .env files, NEXT_PUBLIC prefixes, and runtime access, you can build scalable and secure applications with ease.


Written & researched by Dr. Shahin Siami

Related Articles

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

Continue

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

Continue

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

Continue

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

Continue

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

Continue

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

Continue