Integrating with Next.js

Next.js enables a React application to be rendered on either the client-side or server-side, improving first-page load performance and capability. Integrating TrackJS will require an isomorphic adapter to inject either the browser agent or the node agent at runtime.

Attach TrackJS into Next.js through a custom <app> and custom error handler as described in the Next.js documentation.

Custom _app.js

The pages/_app.js override of the Application enables us to attach the standard React componentDidCatch handler. The rest of the code is boilerplate from the Next.js documentation.

import React from "react";
import App, { Container } from "next/app";
// trackjsAdapter is the Isomorphic Adapter this may be run on the browser or server.
import { TrackJS } from "./utils/trackjsAdapter.js";

  token: "YOUR_TOKEN"

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    return { pageProps };

  // Standard React extension point for capturing errors.
  componentDidCatch (error, errorInfo) {
    this.setState({ error });

  render() {
    const { Component, pageProps } = this.props;
    return (
        <Component {...pageProps} />

export default MyApp;
Next.js custom App with TrackJS

Custom _error.js

The pages/_error.js override allows us to attach a custom error handler for other classes of errors not caught by the _app.js handler. If this component initializes, an error has been caught by the Next.js framework, so we can capture it during getInitialProps. The rest of the code is boilerplate from the Next.js documentation, and can be customized to show the user friendly error messages.

import React from "react";
import { TrackJS } from "trackjs-node";

class Error extends React.Component {
  static getInitialProps({ res, err }) {
    const statusCode = res ? res.statusCode : err ? err.statusCode : null;
    return { statusCode };

  render() {
    return (
          ? `An error ${this.props.statusCode} occurred on server`
          : "An error occurred on client"}

export default Error;
Next.js custom Error Handler with TrackJS

Server API

Next.js is commonly augmented with Express for a data API. See the Express integration for details.