Next.js Tutorial 0/207 lessons ~6 min read Lesson 12

    Environment Variables

    Use NEXT_PUBLIC_ versus server-only env vars and keep secrets off the client. This Next.js lesson connects the idea to server/client boundaries, production apps, and TechLearningPro.

    Course progress0%
    Focus
    20 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Learning Objectives

    After completing this lesson, you will be able to:

    • Explain Environment Variables using build-time and runtime env injection.
    • Apply it to API keys and public site URL without confusing React with Next.js or Server Components with Client Components.
    • Recognize and correct this failure mode: putting DATABASE_URL in NEXT_PUBLIC_.
    • Decide when Environment Variables is the right tool: default secrets to server-only.
    • Describe where this code runs: server, browser, or both—and why that matters.
    • Relate Environment Variables to App Router, rendering, caching, or security boundaries where relevant.
    • Write a minimal TypeScript-friendly example that keeps secrets on the server.
    • List interview talking points for beginner through architect levels.
    • Identify the Next.js version sensitivity of any caching or proxy behavior you mention.
    • Connect the lesson to TechLearningPro product scenarios.
    • Explain Environment Variables in Next.js framework terms, not as "just React".
    • Describe what runs on the server versus what hydrates in the browser.
    • Keep React, Next.js, TypeScript, and dedicated backends conceptually distinct.
    • Handle loading, error, and not-found paths without leaking internals.
    • Validate untrusted input at runtime before it reaches domain logic.
    • Reason about caching, streaming, and bundle size where the topic touches them.
    • Apply Environment Variables to a TechLearningPro product use case.
    • State when not to use this technique.
    • Defend the design in an interview with trade-offs.

    Introduction

    A TechLearningPro product surface must support API keys and public site URL. Treating Next.js as "React with routing" hides rendering, server, and security costs. The team needs a design that is explicit about build-time and runtime env injection and honest about server versus browser execution.

    Next.js is a React framework — not React itself, and not a replacement for every backend. This lesson treats Environment Variables as an engineering decision: what the runtime does, how the server/client boundary is involved, and how the idea appears in a production TechLearningPro backend.

    What Is This Concept?

    In simple language: Environment variables configure the process; only NEXT_PUBLIC_ values are exposed to the browser bundle.

    Professional explanation: Environment Variables is a Next.js application concern based on build-time and runtime env injection. It helps engineers implement API keys and public site URL while remaining clear that React is the UI library and Next.js is the framework that owns routing, rendering strategies, and server capabilities.

    Why Do We Need It?

    text
    Without Environment Variables
    Fragile React SPA assumptions or blurred server/client boundaries
    Next.js solution
    Clear routing, rendering, and server ownership
    • It makes API keys and public site URL an explicit full-stack responsibility.
    • It prevents mixing Client Component assumptions with Server Component privileges.
    • It gives reviewers a vocabulary for rendering, caching, and trust boundaries.
    • It supports the key decision: default secrets to server-only.
    • It keeps React library knowledge from being mistaken for Next.js framework architecture.

    Real-World Analogy

    The specials board is public; the vault combination is not.

    How It Works Internally

    Runtime behavior

    At runtime, Environment Variables follows React and Next.js conventions around build-time and runtime env injection. Server code can access secrets and data stores; Client Components hydrate in the browser. Types and comments do not execute.

    Server vs browser implications

    If Environment Variables runs in a Server Component, Server Action, Route Handler, or proxy, it executes on the server. If it requires hooks, browser APIs, or event handlers, it belongs behind a Client Component boundary. Never expose database credentials or server secrets across that boundary.

    Critical distinction: React is a UI library. Next.js is a React framework that adds routing, rendering strategies, server capabilities, caching, and deployment-oriented features. Server Components run on the server; Client Components hydrate in the browser. TypeScript types do not validate runtime input. Secrets must never reach Client Components.
    1. 1. Name the invariant: API keys and public site URL.
    2. 2. Identify the Next.js mechanism: build-time and runtime env injection.
    3. 3. Separate server-only work from browser interactivity.
    4. 4. Define success, loading, error, and not-found paths.
    5. 5. Validate untrusted input before domain logic.
    6. 6. Add observability (logs, metrics, or traces) at the boundary.

    Architecture

    text
    Browser request
    Next.js (App Router)
    ├── Server Components / Environment Variables
    ├── Client Components (when needed)
    ├── Server Actions / Route Handlers
    └── Data / Cache layer
    Backend / Database
    HTML + RSC payload → Browser hydration

    Code Examples

    Basic Example: Smallest useful example

    This isolates the essential behavior of Environment Variables.

    tsx
    // Environment Variables — smallest useful App Router example
    export default function Page() {
    return (
    <main>
    <h1>Environment Variables</h1>
    </main>
    );
    }

    Intermediate Example: Realistic application usage

    This applies the idea to API keys and public site URL.

    tsx
    // Environment Variables — TechLearningPro server sketch
    export async function loadenvironmentvariables() {
    // Server-only: never import this module into a Client Component.
    return { ok: true as const, topic: "Environment Variables" };
    }

    Advanced Example: Production-oriented design

    This version makes the trade-off—default secrets to server-only—explicit.

    tsx
    // Environment Variables — production-oriented composition
    export function createenvironmentvariablesHandler(deps: { logger: { info: (value: unknown) => void } }) {
    return async function handler() {
    const started = Date.now();
    try {
    return { status: 200, body: { topic: "Environment Variables" } };
    } finally {
    deps.logger.info({ ms: Date.now() - started, topic: "environment-variables" });
    }
    };
    }

    Enterprise Example

    TechLearningPro uses Environment Variables while implementing API keys and public site URL. Route UI stays intentional, server modules own privileged work, and Client Components stay small. Reviewers can tell React UI concerns from Next.js framework concerns and from TypeScript types.

    text
    Browser
    Next.js (App Router)
    ├── Server Components
    ├── Client Components
    ├── Server Actions / Route Handlers
    ├── Proxy / request interception
    └── Data / cache layer
    Database / external APIs

    Deep Dive

    build-time and runtime env injection matters because it determines where code runs and what may be cached or streamed.

    The principal design risk is putting DATABASE_URL in NEXT_PUBLIC_. A strong design keeps secrets server-side, boundaries explicit, and diagnostics readable.

    Environment Variables ends at a trust boundary. Params, FormData, cookies, headers, and third-party responses start untrusted.

    The governing trade-off is default secrets to server-only. Prefer the least complexity that solves a measured product problem.

    Caching and proxy behavior can change across Next.js versions—verify against the docs for your release line.

    Common Mistakes

    For each mistake, name the false assumption and replace it with an explicit runtime contract:

    1. 1. Treating Environment Variables as plain React instead of a Next.js framework concern.
    2. 2. Assuming Next.js is secure by default.
    3. 3. Ignoring the central pitfall: putting DATABASE_URL in NEXT_PUBLIC_.
    4. 4. Importing server-only modules into Client Components.
    5. 5. Presenting Route Handlers as a full replacement for every backend.
    6. 6. Trusting TypeScript types as runtime validation.
    7. 7. Using outdated caching explanations as if they were universal.
    8. 8. Marking large trees with use client instead of pushing interactivity down.
    9. 9. Logging secrets, tokens, or raw request bodies.
    10. 10. Repeating an earlier lesson instead of composing the next layer.

    Best Practices

    • Default to Server Components; add Client Components only for interactivity.
    • Keep database clients and secrets in server-only modules.
    • Validate every external payload at the boundary.
    • Use structured errors with request or correlation IDs.
    • Load configuration from the environment; never NEXT_PUBLIC_ for secrets.
    • Separate Next.js route files from domain services where the app grows.
    • Prefer Link and framework navigation for internal routes.
    • Add loading and error UI at the slow or failing segment.
    • Treat Server Actions and Route Handlers as public attack surface.
    • Use TypeScript for contracts; use runtime validators for input.
    • Measure LCP, INP, CLS, and server latency in production.
    • Keep dependencies minimal and audited.
    • Document version-specific caching or proxy assumptions.
    • Revalidate or invalidate caches when mutations change user-visible data.
    • Document when not to use the technique.
    • Revisit the decision: default secrets to server-only.

    Performance

    Next.js performance work starts with server/client boundaries, bundle size, caching, and data waterfalls. Measure Core Web Vitals and server latency before adding infrastructure.

    • Environment Variables is only as fast as the slowest render, fetch, or client JS step on the path.
    • Reduce client JavaScript before adding more infrastructure.
    • Avoid data waterfalls; parallelize independent server fetches.
    • Cache only shareable responses; never cache private HTML publicly.

    Security

    Next.js is not secure by default. Security depends on application architecture, dependencies, configuration, validation, authentication, authorization, and deployment.

    • Authenticate and authorize on the server for every mutation and private read.
    • Never execute unsanitized paths, commands, or query fragments.
    • Store secrets in the environment or a secret manager—never in Client Components.
    • Keep dependency and supply-chain reviews part of delivery.
    • Use Environment Variables to improve product safety, not as a substitute for policy.

    Real-World Architecture

    Place Environment Variables in the narrowest layer that owns its invariant. Route files compose UI; server modules own privileged I/O; Client Components own interactivity; the composition root wires Next.js framework concerns.

    Interview Questions & Answers

    Beginner

    1What problem does Environment Variables solve?+
    It supports API keys and public site URL using build-time and runtime env injection. The value is explicit Next.js architecture, not a new React syntax feature.
    2Where does this run?+
    Clarify server versus browser. Server Components, Server Actions, Route Handlers, and proxy run on the server. Client Components hydrate in the browser.
    3Is Environment Variables the same as React?+
    No. React is a UI library. Next.js is a React framework that adds routing, rendering strategies, server capabilities, and deployment-oriented features. Environment Variables should be explained in Next.js terms while still using React for UI.
    4Where does this code run—server or browser?+
    Decide deliberately. Server Components, Server Actions, Route Handlers, and proxy run on the server. Client Components hydrate in the browser. Secrets and database clients must stay server-side.
    5How does this differ from a dedicated Node.js API?+
    Route Handlers and Server Actions can implement HTTP and mutations inside a Next.js app, but they do not automatically replace every Express service or dedicated backend. Choose based on ownership, scale, and team boundaries.

    Intermediate

    1How would you test this in a Next.js app?+
    Unit-test pure logic, integration-test handlers/actions, and cover critical journeys with Playwright. Assert both success and failure paths.
    2When would you avoid Environment Variables?+
    Avoid it when a simpler Next.js or React primitive already solves the problem, when it would blur server/client boundaries, or when the team would adopt ceremony without a product need.
    3How should errors be handled around Environment Variables?+
    Map operational failures to recoverable UI (error.tsx, safe action results) and treat programmer errors as defects. Never leak stack traces or secrets to the browser.
    4Does TypeScript make Environment Variables safe at runtime?+
    No. TypeScript types are erased. Route params, FormData, cookies, and API payloads remain untrusted until validated by runtime schemas.

    Senior

    1When would you reject this design in review?+
    When the pitfall appears: putting DATABASE_URL in NEXT_PUBLIC_. Prefer a simpler Next.js primitive if the extra machinery does not protect a real invariant.
    2How would you measure TechLearningPro if this topic is on the critical path?+
    Measure Core Web Vitals, server latency percentiles, cache hit behavior, and client JS weight separately. Fix data waterfalls and unnecessary client bundles before adding infrastructure.
    3What production failure mode is most common here?+
    The usual failure is blurring trust boundaries—shipping secrets to the client, caching private HTML, or trusting UI-only auth. Keep authz on the server and invalidate caches after mutations.
    4How do you keep this from becoming a God module?+
    Keep route files compositional, put domain rules in server modules, isolate data access, and push Client Components to interactive leaves.

    Architect

    1How should this live on a platform?+
    Own it behind clear server/client boundaries, validate at trust boundaries, observe it, and accept the trade-off: default secrets to server-only.
    2How should Environment Variables sit in a multi-app TechLearningPro platform?+
    Own the invariant behind clear packages or services, validate at every trust boundary, and choose colocated Next.js handlers versus a dedicated API based on team ownership—not fashion.
    3What is the security stance for this area?+
    Next.js is not secure by default. Security depends on validation, authentication, authorization, cookie policy, dependency hygiene, and deployment. Environment Variables can hide or expose risk, but it never replaces policy.
    4How would you evolve this design across Next.js versions?+
    Pin a supported release line, verify caching and proxy terminology against current docs, version public contracts, and measure before adding micro-frontends or extra brokers. Complexity must pay for a named product problem.

    Practical Exercise

    Problem: Classify five env vars as public or server-only.

    Difficulty: Beginner

    Requirements

    • Keep secrets and database access on the server.
    • Validate untrusted input at runtime.
    • Show a loading, error, or not-found path where relevant.
    • Do not treat React, TypeScript, or a dedicated backend as Next.js itself.

    Expected behavior: A small TechLearningPro module that uses Environment Variables to support API keys and public site URL and documents the server/client boundary.

    Hints

    • Start from build-time and runtime env injection.
    • Watch for putting DATABASE_URL in NEXT_PUBLIC_.
    • Ask whether the work belongs on the server or in the browser.

    The full solution is intentionally withheld. Implement the contract, then review failure modes aloud.

    Key Takeaways

    • Environment Variables models API keys and public site URL through build-time and runtime env injection.
    • React is a UI library; Next.js is a React framework.
    • Server Components run on the server; Client Components hydrate in the browser.
    • The main hazard is putting DATABASE_URL in NEXT_PUBLIC_.
    • The key trade-off is default secrets to server-only.
    • Route Handlers are not a mandatory replacement for every backend.
    • Types do not validate runtime input.
    • Do not ship secrets with NEXT_PUBLIC_ or Client Components.
    • Security is an application and operations property.
    • Compose the next lesson instead of reteaching this contract.

    Summary

    Environment Variables gives TechLearningPro a precise way to implement API keys and public site URL through build-time and runtime env injection. Used with honest server/client reasoning, boundary validation, and clear ownership, it improves full-stack change safety without pretending Next.js is React alone or a security product.

    Next Lesson Preview

    Next, study App Directory. The next lesson extends this Next.js foundation with the next production concern.

    Ready to mark this lesson complete?Track your journey across the entire course.