Skip to article content
LESSON 26 / 28

Deployment and production diagnosis

Operate a real Next.js server with deliberate environment, cache, streaming and diagnostic contracts.

What you will be able to do

  • Separate build-time configuration from request-time values.
  • Choose a deployment model that supports required server features.
  • Explain multi-instance cache and action consistency.
  • Trace production failure using safe logs, metrics and runtime evidence.

A successful build is one stage of delivery

A Next.js application contains build artifacts and, when server features are used, request-time work. A static export can serve compatible prerendered output without a Next server, but it cannot provide arbitrary Server Actions or request-time sessions. Choose the deployment model from required behavior rather than assuming every host supports the same APIs.

Build an immutable artifact, run it with the intended runtime and verify a direct route visit plus a mutation. Use the package's supported Node version and run lint/type checks explicitly according to its scripts. Development behavior can differ from production prerendering, caching and error delivery, so next dev success alone does not close the deployment question.

An environment variable can become public code

By default, server environment values belong to server execution. NEXT_PUBLIC-prefixed values are intended for browser exposure and can be inlined at build time. Changing a container environment after a build does not necessarily change an already compiled public value. Never put a secret under a public prefix, even if the UI does not display it intentionally.

Validate required configuration at the correct boundary and fail with the variable name, not its confidential value. A TypeScript declaration saying process.env.DATABASE_URL is a string does not make it present at runtime. The helper below is a server-only example. For a promotable artifact, distinguish values that must be fixed during build from values the server can safely read per environment.

Server execution

lib/env.ts
import "server-only";
export function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value || value.trim() === "") throw new Error("Missing server configuration: " + name);
  return value;
}
export function getDatabaseUrl() {
  return requireEnv("DATABASE_URL");
}

Terminal command

terminal
npm run build
npm run start

PAUSE AND PREDICT

A container receives a new NEXT_PUBLIC_API_URL after its bundle was built. Why may the browser still use the old URL?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Two servers must agree on shared facts

Horizontal scaling introduces independent process memory. A cache stored in one process is not automatically visible to another. Shared cache storage must be paired with tag invalidation coordination; otherwise one instance can continue serving a value another invalidated. Plain JSON serialization can also lose special structures in framework cache entries, so implement the documented adapter contract rather than a generic Map-shaped guess.

Use consistent build artifacts across replicas and plan for deployment skew during rolling updates. Server Action identifiers and encrypted closures can be tied to build configuration. The official self-hosting guide covers shared encryption keys, deployment identifiers and cache handlers. Do not log those keys, and do not assume sticky sessions solve old asset references or invalidation across every instance.

Infrastructure participates in the feature

A reverse proxy can buffer a streaming response and erase the visible benefit of Suspense or SSE. Serverless platforms may impose execution and connection limits. Test through the actual deployment path, including compression and proxy behavior, rather than stopping at a local curl request. Cancellation should release per-request work when a client disappears.

Work that must survive a process restart needs durable ownership. A request handler that starts a promise and immediately returns has not created a reliable job system. For email-like notifications, processing uploaded files or long-running tasks, use a queue or an appropriate platform lifecycle primitive and record retry/idempotency behavior. The choice follows durability and latency requirements.

PAUSE AND PREDICT

One of three instances invalidates a local tag. The others keep serving old data. What is missing?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Follow one request across the system

Record safe structured events for request identity, operation, duration, cache behavior and outcome. Correlate application traces with upstream and database timings. A slow page could be waiting on a query, recomputing uncached work, transferring a large payload or blocking the browser. The same symptom needs different fixes depending on the evidence.

Create an incident exercise: a route works in development but fails in production. Check the build version, environment, direct-route response, asset URLs, runtime compatibility and server logs in that order of relevance to the symptom. Report the observed cause and verification scope. Never turn a successful local test into a claim that a remote deployment is healthy.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGEA successful development server proves the production build works.
A more accurate model

Build, production-start and deployed behavior have separate failure modes and need scoped evidence.

How to check it

Compare real /cache and /stream behavior in the documented production process.

CLAIM TO CHALLENGEA fire-and-forget promise is a durable background job.
A more accurate model

Required work needs durable ownership, retry policy and an appropriate execution lifecycle.

How to check it

The deployment lesson distinguishes request lifetime from queue-backed processing.

Mistakes to catch in your own code

  • Putting secrets in NEXT_PUBLIC variables.
  • Using a static export for required request-time sessions or actions.
  • Assuming each replica's local cache is shared.
  • Treating fire-and-forget promises as durable background jobs.

Write it by hand

JavaScript logic playground

Validate a safe deployment configuration

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Input is a configuration object with PORT, DATABASE_URL and optional NEXT_PUBLIC_SECRET.
  2. PORT must be a decimal integer string from 1 to 65535. DATABASE_URL must be a nonempty string. Reject a nonempty NEXT_PUBLIC_SECRET.
  3. Return {ok:false,errors} with sorted variable names, or {ok:true,port,databaseConfigured:true}. Never echo secret values.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 4 test cases
  1. Accept valid server configuration

    Input

    {
      "PORT": "3000",
      "DATABASE_URL": "postgres://local/demo"
    }

    Expected

    {
      "ok": true,
      "port": 3000,
      "databaseConfigured": true
    }
  2. Reject exposed secret without echoing it

    Input

    {
      "PORT": "3000",
      "DATABASE_URL": "postgres://local/demo",
      "NEXT_PUBLIC_SECRET": "example-placeholder"
    }

    Expected

    {
      "ok": false,
      "errors": [
        "NEXT_PUBLIC_SECRET"
      ]
    }
  3. Collect missing and invalid variables

    Input

    {
      "PORT": "70000",
      "DATABASE_URL": ""
    }

    Expected

    {
      "ok": false,
      "errors": [
        "DATABASE_URL",
        "PORT"
      ]
    }
  4. Reject partial numeric port

    Input

    {
      "PORT": "3000junk",
      "DATABASE_URL": "postgres://local/demo"
    }

    Expected

    {
      "ok": false,
      "errors": [
        "PORT"
      ]
    }
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const errors = [];
  const port = typeof input.PORT === "string" && /^[1-9]\d*$/.test(input.PORT) ? Number(input.PORT) : 0;
  if (!Number.isInteger(port) || port < 1 || port > 65535) errors.push("PORT");
  if (typeof input.DATABASE_URL !== "string" || !input.DATABASE_URL.trim()) errors.push("DATABASE_URL");
  if (typeof input.NEXT_PUBLIC_SECRET === "string" && input.NEXT_PUBLIC_SECRET.trim()) errors.push("NEXT_PUBLIC_SECRET");
  return errors.length ? { ok: false, errors: errors.sort() } : { ok: true, port, databaseConfigured: true };
}

A validator should report configuration names rather than leaking their values.

This is a deliberately small contract, not a general environment loader or database URL verifier.

Run equivalent checks in the real server process at an appropriate startup boundary.

Verify it in a real Next.js application

Next.js application lab

Verify the local production runtime and design its hosting extension

Open the local application route /cache after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Follow the README with Node.js 22.14 or newer, npm ci, npm run build and npm start. Inspect the pinned package versions and next.config.ts: this lab explicitly enables cacheComponents and partialPrefetching.
  2. As an administrator, change a product price at /cache. Trace the committed file-store mutation followed by updateTag("catalog"), then inspect /api/catalog and the catalogue page. The API no-store response header does not remove the separately tagged server function cache.
  3. Check a direct /catalog/keyboard visit, /stream completion/cancellation and a dashboard action against the production process. Keep development observations separate because HMR and development caching can differ.
  4. Inspect lib/store.ts and the persistent signing-key file. The current adapter uses a single-process write queue and atomic file replacement on writable local storage; it is not a shared transactional or ephemeral-serverless persistence solution.
  5. Implementation extension: add request tracing, structured redacted logs and a controlled failure metric. The project has no deployed telemetry collector or preconfigured production dashboard.
  6. Implementation extension: replace the file store, plan shared cache/tag coordination and signing/action-key distribution, and test deployment skew plus streaming proxy behavior on your chosen host before claiming multi-instance support.

Check the behavior

  • The local production process serves nested routes, required assets and the documented server features under its actual pinned configuration.
  • A committed price is observed through the action response and a new catalogue read; the evidence identifies which server cache and browser response were checked.
  • Stream observations cover the actual local transport; proxy buffering and hosted-runtime limits require a separate deployment check.
  • The multi-instance, persistence and observability extensions are explicit design/implementation work. Missing hosting access or an unrun build is recorded as blocked or unexecuted.
Review the application reasoning

The example is a runnable local Node application. Its source, tests and build commands make the operation reviewable; they do not establish behavior on a deployment that has not been performed. Static article hosting remains separate from this Next.js server.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01Why did changing NEXT_PUBLIC_API_URL at runtime not change the browser?

    That value can be inlined into the browser bundle at build time. The browser is executing the already built artifact, not reading the container environment directly.

    I would rebuild when the value is intentionally build-specific or design an explicit runtime public configuration endpoint when appropriate. Secret values remain server-only.

    Follow-up questions

    • What configuration can be promoted unchanged across environments?
    • Does a TypeScript env declaration validate presence?
  2. 02What changes when the app runs on three instances?

    Process-local data and caches are independent. I need a shared strategy for durable state, cache storage and tag invalidation, along with consistent build/action configuration.

    I also plan rolling deployments so old clients can obtain compatible assets and action behavior. A load balancer does not create these consistency guarantees automatically.

    Follow-up questions

    • Does sticky routing fix every cache problem?
    • How are invalidation tags learned by other instances?
  3. 03Why might a streamed page arrive all at once in production?

    A proxy or hosting adapter may buffer the response, or the application may await all work before producing a stream. I inspect the actual response timing through the deployment path.

    I check infrastructure streaming support and buffering settings as well as Suspense placement. Local streaming evidence is necessary but not sufficient for the deployed behavior.

    Follow-up questions

    • What platform timeout limits matter for SSE?
    • How do you observe cancellation cleanup?
  4. 04Can the entire course lab be deployed as a static export?

    Only if its required behavior fits static-export support. Real actions, request-specific session reads and custom request-time server endpoints require a capable server or platform adapter.

    The learning article itself can remain static while linking to a separate executable Next.js project. That separation preserves the host site's architecture without pretending the article executes server features.

    Follow-up questions

    • Which example routes could be fully prerendered?
    • Where would a backend API live for a static frontend?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

SSE works locally but arrives in one batch through production infrastructure. What should be checked?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.