Next.js

Environment Variables & Runtime Boundaries

28 min Lesson 51 of 80

Environment Variables & Runtime Boundaries

This lesson expands the Next.js path with an advanced topic from the official Next.js documentation. The goal is not only to memorize an option or file name, but to understand its impact on rendering, caching, security, and deployment.

After this lesson you should be able to apply the topic in a real project, choose the right boundary for it, and explain it as a reviewable engineering decision.

Core Concepts

  • NEXT_PUBLIC exposure
  • server-only secrets
  • build-time values
  • runtime values
  • schema validation

Practical Example

// app/lib/env.ts import 'server-only' import { z } from 'zod' const schema = z.object({ DATABASE_URL: z.string().url(), STRIPE_SECRET_KEY: z.string().min(1), }) export const env = schema.parse(process.env) // app/lib/public-env.ts export const publicEnv = { appUrl: process.env.NEXT_PUBLIC_APP_URL }
This lesson is aligned with these official Next.js documentation areas: Environment variable and server-only docs.

Why It Matters

In production applications, this topic affects page speed, data freshness, authorization clarity, and operational reliability after deployment.

Implementation Workflow

  • Decide whether the data is public or user-specific.
  • Choose the smallest part of the tree that needs this behavior.
  • Connect the example to a real route and add a small verification check.
  • Document the effect on caching and deployment.

Hands-on Practice

Create separate server-only and public environment modules and validate required variables at startup.

Never put secrets behind NEXT_PUBLIC_ because those values are bundled for the browser.

Summary

Judge the implementation by how clear the decision is, whether the behavior is correct after build, and how easily it can be traced in production.