This article's content
Environment variables in NextJS

Next.js has built-in support for loading environment variables from .env.local into process.env.

// .env.local

// you can use variables
// pages/index.js
export async function getStaticProps() {
  const db = await myDB.connect({
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
  // You cannot use destructuring, it will fail:
  // const { NEXT_PUBLIC_PUBLISHABLE_KEY } = process.env.
  // ...

By default all environment variables loaded through .env.local are only available in the Node.js environment, meaning they won’t be exposed to the browser. In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_

// pages/index.js
import setupAnalyticsService from '../lib/my-analytics-service'

// NEXT_PUBLIC_ANALYTICS_ID can be used here as it's prefixed by NEXT_PUBLIC_

function HomePage() {
  return <h1>Hello World</h1>

export default HomePage

Note: .env, .env.development, and .env.production files should be included in your repository as they define defaults. .env*.local should be added to .gitignore, as those files are intended to be ignored. .env.local is where secrets can be stored.

About Author

Mathias Bothe To my job profile

I am Mathias, born 40 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 16 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of, creator of the security service platform BosyProtect© and initiator of several other software projects.