October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

Capture Backend Errors in Next.js Without Sourcemaps or Session Replay

Use Next.js onRequestError to report captured server request errors to a small, validated POST endpoint—without sourcemaps or session replay.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For server errors that Next.js captures, use the onRequestError hook in instrumentation.ts to normalize a small event and await a POST to an ingestion endpoint. An App Router app/api/errors/route.ts can receive that event, but it must validate and protect the public endpoint and forward data to storage suited to your host. This approach needs neither sourcemaps nor session replay; it also does not capture every process crash, infrastructure failure, browser exception, or external-service incident.

What this setup captures—and what it does not

Next.js provides a framework-level hook, onRequestError(error, request, context), for errors it captures while handling requests. Its context can identify the router—Pages or App—and whether the error arose during rendering, a route handler, an action, or proxy execution. Request information includes path, method, and headers. See the instrumentation API reference.

This is request-error reporting, not a universal process monitor. The hook’s documented trigger does not establish that every unhandled process-level failure, host termination, swallowed application error, or external service incident will enter the same stream. Report caught-and-suppressed errors explicitly if they matter to your operations. Use host-level monitoring for failures outside the request lifecycle.

For Server Component errors, React may process the error before the hook receives it, so the error object may not be the original thrown instance. The API documents an error digest as an identifier in that case. Narrow the value before reading properties, and treat the digest as a useful correlation field rather than a substitute for a complete diagnostic record.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a separate browser reporter is needed

Server request capture does not report browser exceptions. Next.js has a separate instrumentation-client.ts surface that runs after the HTML loads and before hydration; its documentation recommends keeping startup instrumentation lightweight. Browser reporting is a distinct decision, not a prerequisite for this backend endpoint. See the instrumentation-client reference.

How the lightweight reporting flow works

  1. Initialize instrumentation. Put instrumentation.ts or instrumentation.js at the project root, or alongside app and pages when those directories are under src. Export register() for initialization; Next.js completes it before that server instance is ready to handle requests.
  2. Receive a captured request error. Export onRequestError(error, request, context) and select only the context and request fields your event needs.
  3. Normalize and send. Build a small allowlisted event rather than serializing the error, request, or headers wholesale. If the report is asynchronous and must complete as part of the hook, await it.
  4. Validate at ingestion. A receiving endpoint checks the body and applies the authorization and anti-abuse controls appropriate to the deployment before storing or forwarding it.

The hook is documented as stable from Next.js 15.0.0. The official Next.js 15 announcement says the feature is stable and the experimental instrumentationHook config option can be removed. Check your installed Next.js version and its matching documentation before adopting this API in an older project.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Set up instrumentation and an App Router ingest route

The following is an implementation pattern built from the documented hook and Route Handler APIs, not a complete secure logging service supplied by Next.js. Keep the two ends explicit: the server hook reports; the route accepts a bounded, validated event.

1. Register the error hook

Place this file at the project root, or in src beside your router directories. The example intentionally sends only a few normalized fields; adapt the event schema to your actual collector and deployment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
// instrumentation.ts
export async function register() {
  // Initialize only the reporting code needed by this server instance.
}

type ErrorLike = {
  message?: unknown;
  digest?: unknown;
};

export async function onRequestError(error: unknown, request: Request, context: {
  routerKind: string;
  routePath: string;
  routeType: string;
}) {
  const candidate = error as ErrorLike | null;
  const message = typeof candidate?.message === "string"
    ? candidate.message.slice(0, 500)
    : "Request failed";
  const digest = typeof candidate?.digest === "string"
    ? candidate.digest
    : undefined;

  const event = {
    name: "next.request_error",
    message,
    digest,
    router: context.routerKind,
    route: context.routePath,
    routeType: context.routeType,
    method: request.method,
    environment: process.env.NODE_ENV,
  };

  const endpoint = process.env.ERROR_INGEST_URL;
  if (!endpoint) return;

  await fetch(endpoint, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(event),
  });
}

Use the exact property names exposed by the installed version’s type definitions; the API reference is authoritative for the current hook signature. In particular, do not assume the example’s event fields represent a prescribed Next.js schema.

In a deployment where the application owns both ends, the endpoint can be an App Router Route Handler at app/api/errors/route.ts. Route Handlers use the Web Request/Response APIs and support POST. They are not cached by default; caching for GET is opt-in. Choose a distinct API path because a Route Handler cannot occupy the same segment as a page. See the Route Handlers guide.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

2. Validate the incoming event

// app/api/errors/route.ts
const MAX_BODY_BYTES = 16_000;

export async function POST(request: Request) {
  const contentLength = Number(request.headers.get("content-length") ?? 0);
  if (contentLength > MAX_BODY_BYTES) {
    return new Response(null, { status: 413 });
  }

  let input: unknown;
  try {
    input = await request.json();
  } catch {
    return new Response(null, { status: 400 });
  }

  if (!isErrorEvent(input)) {
    return new Response(null, { status: 400 });
  }

  // Authenticate or otherwise authorize the sender, then persist or forward
  // the allowlisted event using storage appropriate to this deployment.
  await storeEvent(input);
  return new Response(null, { status: 202 });
}

function isErrorEvent(value: unknown): value is {
  name: string;
  message: string;
  route: string;
  method: string;
} {
  if (!value || typeof value !== "object") return false;
  const event = value as Record<string, unknown>;
  return event.name === "next.request_error"
    && typeof event.message === "string"
    && event.message.length <= 500
    && typeof event.route === "string"
    && typeof event.method === "string";
}

The body-size check shown is an example implementation limit, not a Next.js default or a universal recommended size. A production handler should enforce a limit while reading the body as well, because a missing or misleading Content-Length is not sufficient protection by itself. Define isErrorEvent and storeEvent for your own schema and persistence system.

Choose a small payload and keep sensitive data out

The hook exposes broad request context, but an error event rarely needs the whole request. A practical allowlist can include:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • An event name or category from a fixed set.
  • A normalized, length-limited message and the digest when available.
  • The route pattern, router type, error context, and HTTP method.
  • Deployment environment and a release identifier if your app already has one.
  • A timestamp or correlation identifier generated on the server.

Treat all values arriving at the endpoint as untrusted, including fields emitted by your own app: they may contain attacker-controlled text. Do not serialize the full request, cookies, authorization headers, arbitrary headers, request body, or raw user query strings by default. Next.js warns against exposing sensitive information in errors returned to clients; its Backend for Frontend guide also describes Route Handlers as public HTTP endpoints. Return a minimal success or rejection response—never echo a stack trace, secret-bearing message, or internal backend details.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Secure and operate the endpoint

Next.js does not automatically provide ingestion authentication, throttling, size limits, or abuse controls. Select protections based on who can reach the route and how events are sent:

  • Authorization: authenticate trusted senders where the deployment permits it. A secret embedded in browser code is not a server credential.
  • Abuse controls: consider rate limits, origin checks where relevant, deduplication, and rejection of unexpected event names or fields. These are deployment-specific controls, not built-in Route Handler features.
  • Bounded work: cap the accepted payload and keep the request path short. Avoid turning the route into an unbounded queue or a slow processing pipeline.
  • Durable destination: persist to a collector or storage service designed for the actual hosting environment; do not assume an in-process buffer or local file will survive deployment behavior.
  • Failure behavior: decide what should happen if the collector is unavailable. The reporting path should not accidentally create a second failure storm or leak sensitive details back to the request caller.

Some hosts execute handlers as lambdas. Next.js notes that such handlers may not share state between invocations, may lack writable filesystem access, and may be terminated on timeout. An in-memory queue or local file therefore is not durable storage in a serverless deployment. The exact persistence and retry strategy depends on the host and collector; Next.js does not prescribe one.

Runtime and tooling choices

Instrumentation can run in Node.js and Edge runtimes. Next.js documents using process.env.NEXT_RUNTIME to load runtime-specific code; avoid importing Node-only modules into a path that may execute in Edge. See the instrumentation reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A custom hook and endpoint are a reasonable fit when the goal is narrow server request reporting and the team is prepared to own payload validation, abuse prevention, and storage. A hosted observability SDK may add aggregation and diagnostic workflows. OpenTelemetry is a broader instrumentation approach than a single minimal error event requires; Next.js shows @vercel/otel as an example, not as a prerequisite. Neither sourcemaps nor session replay are required by this event-posting design, and no performance advantage over a hosted SDK can be assumed without measurements.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.