Next.js

Next.js is a full-stack framework for JavaScript and TypeScript web applications.
This guide covers setting up client-side and server-side Crash Reporting for an existing Next.js application using the Raygun4JS and Raygun4Node providers.


Installation

Next.js has transitioned from Page Routing to App Routing since version 13. Page Routing is still supported alongside App Routing for legacy applications, but it is recommended that new applications use App Routing.

  • If your application uses Page Routing, we'll need to use the Custom Document system from Next.js.

  • If your application uses App Routing, we'll need to modify the Root Layout.

  • If your application is currently migrating from Page Routing to App Routing, you will require Raygun in two locations. See Next's App Router Incremental Adoption Guide for details. In this case, please follow Step 2a and Step 2b for both routing types.


Step 2a - Applications with Page Routing

If you do not already have a custom document located at pages/_document.js / .ts, save the following as pages/_document.js / .ts:

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <script
          type="text/javascript"
          dangerouslySetInnerHTML={{
            __html: `
              !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){
              (a[e].o=a[e].o||[]).push(arguments)},f=b.createElement(c),g=b.getElementsByTagName(c)[0],
              f.async=1,f.src=d,g.parentNode.insertBefore(f,g),h=a.onerror,a.onerror=function(b,c,d,f,g){
              h&&h(b,c,d,f,g),g||(g=new Error(b)),a[e].q=a[e].q||[],a[e].q.push({
              e:g})}}(window,document,"script","//cdn.raygun.io/raygun4js/raygun.min.js","rg4js");

              rg4js('apiKey', 'paste_your_api_key_here');
              rg4js('enableCrashReporting', true);`,
          }}
        />
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

If you do already have a custom document located at pages/_document.js / .ts, add the above Raygun <script /> immediately below the opening <Html> tag in the same manner.

Step 2b - Applications with App Routing

Insert the following into your root layout located at app/layout.tsx immediately below the opening <html> tag:

  <html>
    <head>
      <script
        type="text/javascript"
        dangerouslySetInnerHTML={{
          __html: `
            !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){
            (a[e].o=a[e].o||[]).push(arguments)},f=b.createElement(c),g=b.getElementsByTagName(c)[0],
            f.async=1,f.src=d,g.parentNode.insertBefore(f,g),h=a.onerror,a.onerror=function(b,c,d,f,g){
            h&&h(b,c,d,f,g),g||(g=new Error(b)),a[e].q=a[e].q||[],a[e].q.push({
            e:g})}}(window,document,"script","//cdn.raygun.io/raygun4js/raygun.min.js","rg4js");

            rg4js('apiKey', 'paste_your_api_key_here');
            rg4js('enableCrashReporting', true);`,
        }}
      />
      //...
    </head>
    //...

This will add the Raygun fetch script to the head, applying to all routes.

Note: If you encounter a situation where no events are appearing within Raygun, you may need to hard code the protocol so that the CDN matches your hosting environment. This could look like one of the following -

  • https://cdn.raygun.io/raygun4js/raygun.min.js
  • http://cdn.raygun.io/raygun4js/raygun.min.js

This will be in replacement of //cdn.raygun.io/raygun4js/raygun.min.js.


If you haven't already, install the raygun package:

npm install raygun

Create a raygun.js file that initializes and exports the client. If you're using TypeScript, name the file raygun.ts instead.

import * as Raygun from "raygun";

export const raygun = new Raygun.Client().init({
  batch: true,
  apiKey: "paste_your_api_key_here",
});

Next.js has no conventions for where this file should be placed, so we recommend the project root. Add your api key, or load it from an enviroment variable using process.env.

It's important to create this wrapper module for raygun, as it allows Next.js to only bundle this code when used on the server.

Currently, the raygun package is only designed for use with Node.js. This means it can only be used in certain parts of Next.js (getStaticProps/getServerSideProps).

You can also report errors from code that's only used by these functions, but if raygun is used in functions shared between the server and client, it can cause bundling issues.

For reporting errors via the client browser, we recommend the use of Raygun4JS. You can find a guide for integrating Raygun4JS and Next.js here.


Deploy Raygun into your production environment for best results, or raise a test exception. Once we detect your first error event, the Raygun app will automatically update.


note: It's necessary to use dangerouslySetInnerHTML to create a <script> tag with Next.js. The primary risk from dangerouslySetInnerHTML occurs when including untrusted data in HTML. All of the provided examples are either static strings, or interpolate data directly from the process's environment variables. As such, there is no risk of these issues when using the examples as provided.


If you're using Next.js v9.4 or later, you can also store your Raygun API key in the next.config.js file and load it as an environment variable. This can provide greater flexibility over which API key is used in different environments.

First, add your Raygun API key to your next.config.js file:

module.exports = {
  reactStrictMode: true,
  env: {
    RAYGUN_API_KEY: 'paste_your_api_key_here'
  }
}

Now you can modify your Raygun installation scipt (located in _document.js / .ts and/or layout.tsx) to reference this new environment variable:

      //...
      rg4js('apiKey', '${process.env.RAYGUN_API_KEY}');
      //...

The Raygun API key will then be loaded from the next.config.js file and included in the script tag that's sent to the browser.


The providers are open source and available at the Raygun4JS repository and the Raygun4Node repository.