Environment variables
Environment variables are settings that differ between your computer and the server: the database path, API keys, the site address. They are not written into code but placed in a .env.local file that does not go into Git.
The .env.local file
Create .env.local in the project root, next to package.json:
DATABASE_FILE=blog.db
API_SECRET=k3y-for-local-tests
NEXT_PUBLIC_SITE_NAME=My blogNext.js reads this file on start. After editing .env.local, restart npm run dev.
Reading on the server
In server code a variable is available through process.env:
// db/index.ts
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
export const db = drizzle({ client: new Database(process.env.DATABASE_FILE ?? 'blog.db') });Now the database file name is a setting: the server can use another path without code changes. The type of process.env.DATABASE_FILE is string | undefined, hence the default value.
The NEXT_PUBLIC_ rule
Only variables whose names start with NEXT_PUBLIC_ reach the browser. Next.js inserts their values right into the code at build time:
// components/SiteName.tsx
'use client';
export default function SiteName() {
return <span>{process.env.NEXT_PUBLIC_SITE_NAME}</span>;
}The component shows "My blog". If the variable were called SITE_NAME, it would be undefined in a client component.
| Variable | Server | Browser |
|---|---|---|
API_SECRET | Yes | No |
NEXT_PUBLIC_SITE_NAME | Yes | Yes, the value is visible to everyone |
That is why secrets — passwords, payment system keys — are never named with NEXT_PUBLIC_.
Which files exist
| File | When it is read | In Git |
|---|---|---|
.env | Always | Allowed, without secrets |
.env.development | On npm run dev | Allowed, without secrets |
.env.production | On npm run build and start | Allowed, without secrets |
.env.local | Always, overrides the others | No |
The starter .gitignore excludes all .env* files; to keep a file without secrets such as .env in Git, take it out of that rule. On hosting, variables are usually set in the control panel rather than in a file.
Common mistake
Changing the value of a NEXT_PUBLIC_ variable on the server and expecting the site to pick it up. Such values are baked into the JavaScript during npm run build. After changing a NEXT_PUBLIC_ variable, rebuild the project.