Integrating with NextJS
NextJS runs on both the client and server, and errors can occur in either context. To get full coverage of errors, the TrackJS agent must be installed in both the browser and server side of NextJS. We provide a node package specifically built for NextJS to make this easier.
Supported Versions: The trackjs-nextjs
package supports NextJS versions 14 and 15. Use our legacy Next.js integrations for older versions of NextJS.
Install the package
First, install the TrackJS-NextJS integration package:
Client-Side Error Handling with App Router
To capture client-side errors in App Router based pages, use the TrackJSAgent
component inserted into the head of your root at app/layout.tsx
. Provide the agent with your TrackJS token and any other custom settings you may have.
Root Layout
Global Error Handler
Some NextJS render errors are only exposed through NextJS error handling. To catch these errors, create a global-error.tsx
in the root of app
. This can be customized to show your own user error UI in addition to tracking the error.
NOTE global-error.tsx
is only enabled in production builds of NextJS. To verify it’s functionality, build and run the code in production mode.
Error Boundaries (Optional)
Some NextJS applications use additional error boundaries. Errors handled by an error boundary do not bubble to the global error handler. To log these errors, add TrackJS.track(error)
to your existing error boundary. A simple example is below:
Client-Side Error Handling with Pages Router (Optional)
When using the Pages Router, additional configuration is needed to enable client-side error tracking.
Pages Router Only If you don’t use the Pages Router, skip this step.
App Component
Install the TrackJS
agent at the start of your pages/_app.tsx
App component. Create this file if it does not yet exist. Be sure to include your TrackJS token and any other custom settings you may have.
Server-Side Error Handling
There are some cases where the server-side components of NextJS will throw an error. To capture these, you need to ensure that the TrackJS agent is installed in the server context as well.
Instrumentation
Install TrackJS using the instrumentation.tsx
file in the root of your project. Instrumentation captures errors in the NodeJS server side of NextJS for both App Router and Pages Router based pages.
Enable Instrumentation (NextJS 14 Only)
NextJS 14 Requires An Additional Step:
By default, this version does not execute instrumentation.tsx
.
Enable execution by creating a next.config.js
file in the root of your project:
The NextJS ecosystem is evolving rapidly, so if you have any trouble with the integration, let us know!