iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
In a Next.js App Router application, use instrumentation.ts to report server request errors from both Route Handlers and Server Actions, and handle expected action failures as returned values rather than exceptions. Add route-level recovery UI, set up client-side reporting separately, and keep diagnostic details in server-side logs—not in messages shown to users.
What “API Routes” means in the App Router
Next.js calls its App Router HTTP endpoints Route Handlers; they are defined with files such as app/api/example/route.ts. Server Actions are a separate way to run server-side code, commonly in response to a form submission. The instrumentation API distinguishes these request contexts: its route type can be route for Route Handlers or action for Server Actions. This setup is for the App Router, not the older Pages Router model.
The central reporting hook gives you a consistent place to forward captured server request errors and the associated request context to your observability system. It does not by itself replace client-side reporting, safe action-result handling, or recovery UI.
Capture server errors with instrumentation.ts
Create instrumentation.ts at the project root, or under src if the application uses that directory structure. Export onRequestError and forward the error, request, and context to your chosen reporting integration. The context includes the router kind, route path, and route type, which lets downstream reporting distinguish a Route Handler error from a Server Action error. See the Next.js instrumentation reference for the current hook contract.
#1 Best Overall
import type { Instrumentation } from 'next'
export const onRequestError: Instrumentation.onRequestError = async (
error,
request,
context,
) => {
await reportError(error, {
request,
routerKind: context.routerKind,
routePath: context.routePath,
routeType: context.routeType,
})
}
reportError here represents your provider-specific integration; its implementation and API depend on the provider, so this example is not a drop-in SDK configuration. Keep the handler focused on forwarding useful context and avoid putting secrets or sensitive request data into telemetry.
Await asynchronous reporting work. The Next.js instrumentation documentation specifically warns: “If you’re running any async tasks in onRequestError, make sure they’re awaited.” An unawaited network call may not finish reliably as request processing ends.
Rank #2
Return expected Server Action failures; throw unexpected ones
Not every failed action is an incident. Invalid input, an ordinary request failure, or another expected outcome should generally be returned as action state and rendered as a user-facing message. Reserve thrown errors for unexpected failures that need production error capture. This separation prevents routine validation feedback from being treated like an unhandled server incident. Follow the patterns in the Next.js error-handling guide.
- Expected: missing or invalid form fields, a rejected business rule, or an anticipated failure to complete a request. Return a structured result the UI can explain.
- Unexpected: a failure the application cannot handle as a normal outcome. Throw it so the framework’s error handling and request instrumentation can capture it.
Do not make the user infer success from a swallowed exception or a generic “something went wrong” result when the action can safely report a specific expected problem.
Rank #3
Add recovery UI at the right route boundaries
Place error.tsx files at route-segment boundaries where users need a recovery path. Consider global-error.tsx when you also need a fallback for root-level errors. These files provide UI for uncaught rendering failures; they do not send incidents to your reporting service. Treat recovery and capture as separate responsibilities. See the error file convention and production error-handling guidance.
When a production Server Component error reaches the UI, Next.js removes sensitive server error detail and shows a generic message with a digest. Keep the diagnostic information in server-side logs and use that digest to help correlate the user’s report with the corresponding server record. Do not display stack traces, raw exception messages, or secret-bearing details in recovery UI.
Instrument client-side errors separately
Server request instrumentation is not a complete client error strategy. Next.js documents instrumentation-client.ts as an entry point for client-side error tracking; configure a separate reporting path there for the client failures your application needs to capture. React error boundaries also do not generally catch errors from event handlers or asynchronous client code, so those paths need explicit handling and reporting where appropriate. See the client instrumentation reference and the error-handling guide.
Check Server Action request limits and origin controls
Server Action configuration affects both resource use and which requests are accepted. Next.js documents a default Server Action request body maximum of 1 MB; this is a configurable framework default, not a measured capacity guarantee. Increase it only when an application has a specific need and has considered the resource implications. Next.js also documents same-origin checks and configuration for additional allowed origins. Review the current Server Actions configuration reference before changing these controls.
Quick Recap
Production setup checklist
- Confirm the application uses the App Router and identify its root or
srcdirectory. - Add
instrumentation.tswith anonRequestErrorhandler, and forward the error plus relevant request context. - Await asynchronous reporting work in the hook.
- Return expected Server Action failures as action state; throw unexpected failures.
- Add
error.tsxat useful route boundaries and considerglobal-error.tsxfor root-level recovery. - Set up client-side capture through
instrumentation-client.tsand explicitly consider event-handler and asynchronous client errors. - Keep production diagnostics in protected server-side logs, correlate using the digest, and show users safe recovery guidance.
- Review the Server Action body-size limit and origin settings against the application’s actual request needs.
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.

