Next.js Instrumentation: Code That Runs on Server Startup
Next.js's `instrumentation.ts` file runs code once when your server process starts, before any requests. It's ideal for setting up global logging, monitoring like OpenTelemetry, or database connections.
WHY IT EXISTS Modern applications need to perform setup tasks before they're ready to serve traffic. Things like connecting to a database or initializing a monitoring service shouldn't happen on the first user request, as that would add latency. Next.js needed a standard, predictable place for this one-time server initialization logic.
THE MENTAL MODEL Think of instrumentation.ts as the main function for your Next.js server process. It's a single entry point that executes once when the server boots up, and then it's done. It's not part of the request-response lifecycle; it happens before that lifecycle even begins.
HOW IT WORKS You create a file named instrumentation.ts (or .js) in the root of your project or inside the src/ directory. Inside this file, you must export a function named register. Next.js will automatically detect this file, import it, and call the register function when the server process starts. This applies to next dev, next build, and next start. Note that you may need to opt-in via next.config.js.
WHEN TO USE IT Use it for tasks that need to run once for the lifetime of the server. The canonical use case mentioned in the Next.js documentation is setting up OpenTelemetry for distributed tracing and metrics. Other good uses include initializing a database connection pool or connecting to external services that require a persistent, long-lived client.
WHEN NOT TO USE IT Do not use this for any client-side logic; it never runs in the browser. Do not use it for logic that needs to run on every incoming request, like checking authentication headers—that's what Middleware is for. Avoid putting heavy, synchronous, blocking tasks here, as they will delay your server's startup time.
ONE CANONICAL EXAMPLE To set up a simple logger that announces server startup, you would create instrumentation.ts with the code: export function register() { console.log('Server instrumentation hook registered. The server is starting...'); }. A more realistic example involves initializing the OpenTelemetry SDK to automatically trace requests across your Next.js application.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.