0
0
NextJSframework~5 mins

Environment variables in production in NextJS

Choose your learning style9 modes available
Introduction

Environment variables let you keep secret or changing information outside your code. In production, they help keep your app safe and flexible.

You want to hide API keys so others can't see them.
You need to change settings like database URLs without changing code.
You want to keep different settings for development and production.
You want to avoid putting passwords or secrets directly in your code.
You want to update configuration without redeploying your app.
Syntax
NextJS
NEXT_PUBLIC_API_URL=https://api.example.com
DATABASE_PASSWORD=supersecretpassword

Variables starting with NEXT_PUBLIC_ are exposed to the browser.

Other variables are only available on the server side.

Examples
This file holds environment variables for production. The NEXT_PUBLIC_API_URL is accessible in the browser, but DATABASE_PASSWORD is only on the server.
NextJS
# .env.production
NEXT_PUBLIC_API_URL=https://api.example.com
DATABASE_PASSWORD=supersecretpassword
You can access public environment variables in your React components using process.env.NEXT_PUBLIC_API_URL.
NextJS
console.log(process.env.NEXT_PUBLIC_API_URL)
// prints the API URL in the browser
Server-only variables like DATABASE_PASSWORD are accessible in API routes or getServerSideProps.
NextJS
console.log(process.env.DATABASE_PASSWORD)
// only works on server side, not in browser
Sample Program

This simple Next.js component shows how to display a public environment variable in the browser. The secret DATABASE_PASSWORD is not shown here and stays safe on the server.

NextJS
import React from 'react'

export default function Home() {
  return (
    <main>
      <h1>API URL:</h1>
      <p>{process.env.NEXT_PUBLIC_API_URL}</p>
    </main>
  )
}

// .env.production file content:
// NEXT_PUBLIC_API_URL=https://api.example.com
// DATABASE_PASSWORD=supersecretpassword
OutputSuccess
Important Notes

Always restart your Next.js server after changing environment variables.

Never expose secrets by prefixing them with NEXT_PUBLIC_.

Use .env.production for production variables and .env.local for local development.

Summary

Environment variables keep secrets and settings outside your code.

Prefix with NEXT_PUBLIC_ to expose variables to the browser.

Use different files for production and development to keep environments separate.