Skip to main content

Instrumentation file

In next.js the instrumentation.ts file located at the root of the src directory can be used to run code on server startup. You can add monitoring or logging tools.

Limitations

Runtime management required

The instrumentation.ts file will be executed by both the nodejs and edge. You need to run logic conditionally to avoid issues in a specific runtime. Additionally, imports should be done using the import() function rather than to import at the top of the file for the same reason.

Context issues

The code called in the instrumentation.ts file will run on its own context (modules will be initialized there independently from the regular flow). It makes the instrumentation not ideal for app initialization code that relies on initializing modules or services for later used in the app navigation.

From the next.js documentation, global variables should be available in all context if you set them there.

Usage

To use the instrumentation.ts file, create a new file at the root of the src directory (same level of middleware.ts). You need to export a function named register as a name export.

See minimal example:

export const register = () => {
if (process.env.NEXT_RUNTIME === 'nodejs') {
// Run in the nodejs runtime
await import('module/with/side/effects');
}
if (process.env.NEXT_RUNTIME === 'edge') {
// Run in the edge runtime
}
};
warning

The edge runtime is based on web API's, so libraries like @accedo/accedo-one that do environment detection can wrongly detect edge as the browser.