Next.js environment variables, done right for teams

Next.js has more env rules than any other framework: build-time vs runtime, the NEXT_PUBLIC_ trap, four .env file flavors. Here is the working model, plus how a team keeps them in sync without pasting files in chat.

The two-worlds model

Every variable in Next.js lives in one of two worlds. Server-only variables (no prefix) exist only in Node: API keys, database URLs. Browser-exposed variables need the NEXT_PUBLIC_ prefix and are inlined into the JavaScript bundle at build time. That second part bites everyone once:

The file flavors, in load order

.env                # base, all environments
.env.development    # next dev
.env.production     # next build / next start
.env.local          # machine-local overrides, gitignored, wins over all

The working convention: commit .env and the per-mode files with non-secret defaults only; every real secret lives in .env.local, which stays gitignored. Next.js loads them in that order automatically, no dotenv import needed.

Where teams fall apart

The rules above handle one machine. The team problem is that everyone's .env.local drifts: the new dev is missing three keys, staging points at prod Stripe, and nobody knows who has the current Redis URL. The usual fix is pasting the file in Slack, which is its own disaster.

The clean pattern: treat .env.local as a synced, encrypted artifact:

$ keyline link my-app --env dev
$ keyline pull -f .env.local   # everyone gets the same, decrypted locally
$ keyline push -f .env.local   # after you add a key

Per-environment scoping maps 1:1 to Next.js modes: a dev environment for .env.local in development, a prod one for the values your host needs. Interns get dev, never prod.

Deploy targets

On Vercel or similar, production env vars live in the host's dashboard; your job is keeping the TEAM's local and staging values coherent. One rule saves audits later: the person who rotates a key updates it in one place (the shared environment), and everyone else is one pull from current.

More guides

Two minutes to the first encrypted push

$ curl -fsSL keyline.sh/install | sh

Solo is free forever. Team is $19 flat for up to 10 people, 14-day trial.

See the whole journey

No card for Solo. Your secrets are encrypted before they leave your laptop.