Integrating with NextJS (Old)

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> 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 App from "next/app";
// the Isomorphic Adapter is a custom shim you need to add to run TrackJS on both browser and server.
// see below.
import { TrackJS } from "./util/trackjs-isomorphic.js";

if (!TrackJS.isInstalled()) {
  TrackJS.install({
    token: "YOUR_TOKEN"
  });
}

class MyApp extends App {

  componentDidCatch(error, errorInfo) {
    TrackJS.track(error);
    this.setState({ error });
    // Anything else you want to do with the error.
  }

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

export default MyApp;
Next.js custom App with TrackJS

TrackJS Isomorphic Adapter

To use the agent effectively in both NodeJS and on the browser, you need to add a small isomorphic adapter to your application. This allows you to get the correct agent object in your code.

module.exports = process.browser ?
  require("trackjs") :
  require("trackjs-node");
TrackJS Isomorphic Adapter

Server API

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