completefrontend

Write the codeMedium

Write onRequestError in instrumentation.ts, so every server error reaches the error tracker without leaking the visitor's data

Next.js calls onRequestError(error, request, context) for each error the server catches. request has the path (with its query), the method, and every request headers; context has routePath, routeType ("render", "route", "action", or "proxy"), and, for errors while rendering, renderSource.

Send one report per error: a POST to ERROR_TRACKER_URL from @/lib/error-tracker, with a content-type: application/json header and a JSON body, and wait for the tracker to answer before returning. The report has these fields and no others:

message: the error's message, or String(error) when what was thrown isn't an Error. digest: the error's digest, when it has one (a Server Component's errors do, a Route Handler's don't). method, and path without its query string. route, type, and source: the context's routePath, routeType, and renderSource, which a Route Handler's error doesn't have. requestId: the x-request-id header, when the request has one. Nothing else from the headers: they carry the visitor's cookies.

Write this: instrumentation.ts
import type { Instrumentation } from "next";
import { ERROR_TRACKER_URL } from "@/lib/error-tracker";
 
export const onRequestError: Instrumentation.onRequestError = async (error, request, context) => {
  fetch(ERROR_TRACKER_URL, {
    method: "POST",
    body: JSON.stringify({ error, request, context }),
  });
};
lib/error-tracker.ts (read-only)
/** Where the shop's error tracker takes reports: one JSON object per POST. */
export const ERROR_TRACKER_URL = "https://errors.leafandkettle.example/reports";
The tests your code must pass
  • reports a Server Component's error with its digest, route, type, and source
  • reports a Route Handler's error, which has no digest and no source
  • reports a value thrown that isn't an Error
  • drops the query string, and every header but the request id
  • sends JSON, and waits for the tracker to answer

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…