User7007
User7007

Reputation: 361

How to configure Rollbar to integrate with next.js 14 using app routing?

I'm currently in the process of configuring Rollbar to integrate with Next.js, however the documentation on Rollbar (https://docs.rollbar.com/docs/nextjs) seem to be slightly out of date as it refers to page routing, pages/_document and deprecated legacy api functions scuh as getInitialProps.

Although the documentation states that Rollbar works with both page and app routers, the setup is the same and uses older page routing functionaility.

Despite this, I've not got anything that has worked properly, so how should I configure and setup Rollbar in Next.js 14+ using the app router?

For reference I've done some research:


   <Script
       id='rollbar'
       dangerouslySetInnerHTML={{
           __html: `
               var _rollbarConfig = {
                   accessToken: 'token',
                   captureUncaught: true,
                   captureUnhandledRejections: true,
                   payload: {
                   environment: 'testenv',
                      // context: 'rollbar/test'
                      client: {
                          javascript: {
                              code_version: '1.0',
                              // source_map_enabled: true,
                              // guess_uncaught_frames: true
                          }
                      }
                  }
              };
              // Rollbar Snippet
              // ....
              // ....
              // End Rollbar Snippet
              `,
        }}
      />

This seems to work, the only slight downside is that typescript complains about window.Rollbar?.error() as Rollbar doesn't exist (but that can proabbly be supressed).

Any ideas as to how Rollbar can integrate with Next.js 14?

Upvotes: 0

Views: 172

Answers (1)

User7007
User7007

Reputation: 361

Rather than integrating Rollbar with Next.js using the browser.js steps, you can use @rollbar/react npm package which works with app router (https://www.npmjs.com/package/@rollbar/react).

First configure the client and server rollbar instances:

import Rollbar from 'rollbar';

const baseConfig: Rollbar.Configuration = {
  captureUncaught: true,
  captureUnhandledRejections: true,
  environment: process.env.NODE_ENV,
};

export const clientConfig: Rollbar.Configuration = {
  accessToken: process.env.NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN,
  ...baseConfig,
};

export const serverInstance: Rollbar = new Rollbar({
  accessToken: process.env.ROLLBAR_SERVER_TOKEN,
  ...baseConfig,
});

Then you can use the clientConfig in the RollbarProvider in layout.tsx:

<RollbarProvider config={clientConfig}>
  <html lang='en'>
    <body className={`${geistSans.variable} ${geistMono.variable}`}>
      {children}
    </body>
  </html>
</RollbarProvider>

At this point, rollbar should capture any uncaught or unhandled rejections, however you can add a global-error file and manually call Rollbar to ensure any errors get logged:

'use client';
import { useRollbar } from '@rollbar/react';
import { useEffect } from 'react';

export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
    const { rollbar } = useRollbar();
    useEffect(() => {
        rollbar.error(error);
    }, [error, rollbar]);


    return (
    <html>
      <body>
        <div>
          <h2>Something went wrong!</h2>
          <button onClick={() => reset()}>Try again</button>
        </div>
      </body>
    </html>
  );
}

You can then also add a middleware.ts file to capture additional information from request:

import { NextRequest, NextResponse } from 'next/server';
import { serverInstance as serverLogger } from './config/logger';

export function middleware(request: NextRequest) {
    serverLogger.configure({ payload: { context: request.nextUrl.pathname } });

    return NextResponse.next();
}

Upvotes: 1

Related Questions