Report Next.js server errors from instrumentation.ts
Place instrumentation.ts at the project root, report each server error with its digest, and match that id on error.tsx to the log line you need.
Artykuł opublikowany po angielsku.
Źródła: Next.js instrumentation.ts: Catch Server Errors Before Your Users Report Them
A Next.js app can sit in production for weeks while nobody watches it. Then a customer forwards a screenshot of a blank failure screen. No route name, no account, no stack. You open the server log, scroll past thousands of lines, and still cannot point at 9:14, the minute they say the page died.
instrumentation.ts is the file Next.js gives you for that gap. It runs as the server process boots, and it can forward every error the framework caught. The rest of this walkthrough is placement, the register and onRequestError exports, an OpenTelemetry hookup, and a way to match the text on screen to one log line.
Loud locally, quiet after deploy
On your laptop a throw is hard to miss. The overlay covers the page, the terminal turns red, and the fix often lands inside a minute.
After you ship, the same throw goes quiet.
- A Server Component blows up while a dashboard renders. The visitor only sees the fallback rendered by
error.tsx. - Checkout can die inside a Server Action. They see a bland message and a stalled order.
- A Route Handler dies on one malformed body. The client receives a 500 and nothing else.
In each case the stack never leaves the server. The framework removes it from the response on purpose, so a secret sitting in the error text cannot reach whoever triggered the request.
That default is the right security choice. It also leaves you blind unless something on the server writes the failure down. If a production break can happen with nobody notified, the customer becomes the alerting system.
The App Router, Server Actions, and Server Components are where that silence shows up first. If they still feel new, learn them before you expect a useful report. The hook can only name the surface that threw. It will not teach you what that surface is.
A note for the guest, a detector for the desk
Picture a hotel corridor. The guest notices smoke once the room is already thick with it. A detector down the hall catches the first thin trail and rings the front desk.
error.tsx is the note on the door: sorry, this room is being fixed. The guest is who that note is for.
The detector is instrumentation.ts. You are who that file is for.
Keep both. The boundary file chooses the copy and the retry button. The instrumentation file decides whether you hear about the incident at all.
The file sits beside app, not inside it
Almost everyone drops this file in the wrong folder on the first try. It does not belong under app/.
It belongs at the project root, as a sibling of app/, public/, next.config.ts, and package.json:
my-app/
├── app/
├── public/
├── instrumentation.ts
├── next.config.ts
└── package.json
If the project keeps its source under src/, place the file at src/instrumentation.ts, beside src/app.
Three constraints come with that path:
- There is no feature flag to flip. Next.js 15 is when this API left experimental status. Guides written for earlier releases still tell you to set
experimental.instrumentationHook. Leave that setting out. - Custom page suffixes. When
pageExtensionsadds a suffix to page files, the instrumentation filename has to carry the same suffix. - One file, whole server. It watches the app, not a single route.
register, once per process, before traffic
register is the first export. Next.js calls it a single time as a fresh server instance comes up, and it holds incoming requests until the function settles.
The smallest version that proves the hook is alive logs a boot line with an ISO timestamp:
// instrumentation.ts
export async function register() {
console.log('[boot] server instance started', new Date().toISOString());
}
The log text is [boot] server instance started, followed by new Date().toISOString(). Read the function as a rule: finish this work, then accept traffic.
That makes it the right home for boot tasks:
- Boot your tracing SDK, or the monitoring client, before any traffic, so request number one is already inside a trace.
- Load a module whose import has side effects, for example one that wraps global
fetchand records outbound calls. - Assert env vars you cannot run without. A missing key should abort boot, not turn into a mystery failure at 2 a.m.
Order is the point. Setup finishes, then traffic arrives. Code inside register cannot race the first request, because the server waits for the function to resolve.
It also runs once per instance, not once per deploy. On a serverless host a cold start can happen many times in a day, so a slow register taxes every one of those boots. Keep the function short.
onRequestError, the callback that pays for the file
onRequestError is the export you will actually rely on. Next.js invokes it for each recorded server failure. You receive the thrown value, the request, and the route context around that failure.
A compact reporter posts JSON to a URL you own, taken from ERROR_REPORT_URL:
// instrumentation.ts
import type { Instrumentation } from 'next';
export const onRequestError: Instrumentation.onRequestError = async (
err,
request,
context
) => {
const message = err instanceof Error ? err.message : String(err);
const digest =
typeof err === 'object' && err !== null && 'digest' in err
? String(err.digest)
: undefined;
await fetch(process.env.ERROR_REPORT_URL!, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message,
digest,
path: request.path,
method: request.method,
routePath: context.routePath,
routeType: context.routeType,
}),
});
};
The callback is typed as Instrumentation.onRequestError, with the Instrumentation type imported from next. The body is a POST whose Content-Type is application/json.
What each argument is for:
errarrives asunknown. Narrow it before you readmessageordigest. The sample useserr.messageonly when the value is anError, and otherwise stringifies it.digestis copied only when the value is a non-null object that actually has that field.request.pathandrequest.methodname the URL that failed. A billing tab can show up as/dashboard?tab=billing.context.routePathis the pattern, such as/dashboard/[team]. That pattern is the folder you should open in the repo.context.routeTypesays which kind of server code threw. The four values arerender,route,action, andproxy.- The
fetchto your report URL is awaited. Skip that await and the process can move on before the POST leaves the machine.
Look at what the JSON leaves out: request.headers. Cookies and bearer tokens live there. Forwarding the raw header map to a logging vendor hands those secrets to a third party. Strip anything sensitive first, or omit headers entirely.
Send the fields that locate the bug. Leave out the fields an attacker would want.
Put the same id on the screen and in the log
When a Server Component throws, the browser does not get the stack. It gets a generic line plus an id Next.js calls the digest. That same id is passed into error.tsx.
Show it on the fallback UI:
// app/error.tsx
'use client';
export default function Error({
error,
retry,
}: {
error: unknown;
retry: () => void;
}) {
const digest =
error instanceof Error && 'digest' in error
? String(error.digest)
: undefined;
return (
<div>
<h2>Something went wrong.</h2>
{digest && <p>Error ID: {digest}</p>}
<button onClick={() => retry()}>Try again</button>
</div>
);
}
The file is a client boundary, marked with 'use client'. Props are error (typed unknown) and retry (a function with no arguments). The component reads digest only when error is an Error that carries the property, prints it under the label Error ID, and wires the button's click to retry(). The heading the visitor sees is the plain line "Something went wrong."
A support screenshot now holds the same digest your onRequestError payload stored. Search the logs for that string and the matching report is the failure itself, not a neighbor.
Version note: from Next.js 16.3, the try-again button's stable prop is retry. Earlier releases passed reset. reset is still available, and its job is to clear the error-boundary state without refetching.
The visitor gets a calm screen. You get an id you can search.
Node and Edge do not share one import graph
Next.js runs register in every runtime the app actually uses. Plenty of monitoring SDKs work only on Node. A top-level import of one of them can take down an Edge route while the module is still loading.
Branch on process.env.NEXT_RUNTIME and dynamic-import a file per runtime:
// instrumentation.ts
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
await import('./instrumentation.node');
}
if (process.env.NEXT_RUNTIME === 'edge') {
await import('./instrumentation.edge');
}
}
When the value is nodejs, the file loads ./instrumentation.node. When it is edge, it loads ./instrumentation.edge. The shared instrumentation.ts stays small. Each runtime file owns its own imports.
The framework docs want side-effect imports inside register, not at the top of the module. Keeping boot effects in one function means you don't get surprised while the module graph is still evaluating.
Model calls belong in the same picture. They are slow, they cost money on every token, and they fail in ways a normal CRUD handler does not. If you are adding AI features, those calls are exactly the spans and error reports you should have on the first deploy, not after the first bad week.
Traces for the requests that did not throw
An error report says what died. A trace says what dragged.
Next.js already emits OpenTelemetry spans for its own work. Register a tracer and rendering, route handlers, and outbound fetch each show up as their own spans. The shortest setup is @vercel/otel, and that package runs on Node and on Edge.
Install the set named in the Next.js docs:
# terminal
npm install @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
The install line pulls in @vercel/otel, @opentelemetry/sdk-logs, @opentelemetry/api-logs, and @opentelemetry/instrumentation.
Then start it from register:
// instrumentation.ts
import { registerOTel } from '@vercel/otel';
export function register() {
registerOTel({ serviceName: 'shop-web' });
}
registerOTel takes a serviceName. In the sample that name is shop-web. It is the label your backend shows when several services ship telemetry to one collector. Choose a name you will still recognize with three apps on the same screen.
A slow function of your own, such as a wide order query, needs a span you create:
// lib/orders.ts
import { trace } from '@opentelemetry/api';
import { db } from '@/lib/db';
const tracer = trace.getTracer('shop-web');
export async function getOrders(userId: string) {
return tracer.startActiveSpan('getOrders', async (span) => {
try {
span.setAttribute('orders.user_id', userId);
return await db.order.findMany({ where: { userId } });
} finally {
span.end();
}
});
}
lib/orders.ts builds a tracer named shop-web with trace.getTracer from @opentelemetry/api, then wraps getOrders in startActiveSpan using the span name getOrders. Inside the try it sets the attribute orders.user_id from userId and returns db.order.findMany filtered on that same id, with db imported from @/lib/db. The finally block calls span.end().
That finally is the line people skip. A span you never end does not show up in the trace UI.
Browser throws take a second file
Server-captured failures are the only ones onRequestError observes. If a click handler throws on the client, this callback never sees it.
Next.js has another root file for that side, instrumentation-client.ts. It runs before the app becomes interactive, and you don't export anything from it. The file itself is the hook:
// instrumentation-client.ts
window.addEventListener('error', (event) => {
navigator.sendBeacon(
'/api/client-errors',
JSON.stringify({ message: event.message, page: location.pathname })
);
});
It listens for window's error event. navigator.sendBeacon posts to /api/client-errors with a JSON body of event.message and location.pathname. Beacon is the right transport here because the browser still delivers the payload when the tab is closing.
People notice a missing client reporter faster than a missing server one. A lot of the errors they actually hit live in the browser.
Throw on purpose before you trust it
A detector you have never heard beep is just a plastic disc on the ceiling. Force a failure before you trust the pipe.
Add a page whose only job is to throw:
// app/debug/boom/page.tsx
import { connection } from 'next/server';
export default async function BoomPage() {
await connection();
throw new Error('Test error from /debug/boom');
}
BoomPage lives at app/debug/boom/page.tsx. It imports connection from next/server, awaits that call, then throws an Error whose message is Test error from /debug/boom.
connection() opts the page into request-time rendering. Skip the call and Next.js tries to prerender /debug/boom while next build runs, and the build fails on the throw.
Then boot the way production does. Build with npm run build, start the server with npm run start, and visit /debug/boom.
- The page should render your
error.tsxfallback and show an Error ID. - The report endpoint should receive the thrown message, the path, a
routeTypeofrender, and that same digest.
When those two sides agree, the pipe works. Remove the debug route before you ship, or lock it down so only you can hit it.
Mistakes that drop the report
- Nesting the file under
app/. Next.js will not load it from there. Use the project root, orsrc/when that is your layout. - Forgetting
awaitinsideonRequestError. The POST can be abandoned. Await every async call in that function. - Writing the full header set into logs. Cookies and tokens land in a vendor you don't fully control. Send only the fields you will search.
- Importing a Node-only SDK at module scope. Edge routes break. Import it inside
register, after aNEXT_RUNTIMEcheck. - Heavy work inside
register. Every new instance waits on it. Boot should stay fast. - Leaving the digest off the fallback UI. A support email then has nothing you can match to a log line, and you are guessing.
Short answers
Do you need a paid monitoring product for this? You don't. Point onRequestError at any URL you control, including a Route Handler that inserts a row in your own database. Paid products add dashboards and paging on top of that.
Does onRequestError stand in for error.tsx? No. error.tsx is the screen the visitor gets. onRequestError is the record you keep. Ship both.
Does the Pages Router participate? Yes. context.routerKind distinguishes an App Router failure from a Pages Router failure.
Can an assistant wire the file up? Yes, if the prompt names the runtime, the host, and the fields you are willing to store. Leave those three out and you will get a logger that either crashes Edge or uploads session cookies.
What to leave in the repo
instrumentation.ts goes at the project root, outside app/. Call register for boot work like OpenTelemetry, and don't let that function get slow. Use onRequestError to report each server error with its path, its route pattern, and its digest. Await the async work. Don't send raw headers. Print the digest from error.tsx. Split runtime-specific imports with NEXT_RUNTIME. Add instrumentation-client.ts so browser throws have a path too.
Once the app can report its own breakage, shipping one that cannot starts to look like an odd habit.