Next.js


Overview

This guide is for the App Router (Next.js 13.4 and later; onRequestError requires Next.js 15). A Next.js app runs code in three places, and each one is covered separately:

Where What to use
Browser (client components) The @understand/understand-js SDK
Node.js server (server components, route handlers, server actions) instrumentation.ts plus a small fetch helper
Edge runtime (middleware, runtime = 'edge' routes) The same fetch helper

The server side uses a small helper around the HTTP API because it works the same in the Node.js and edge runtimes and has no dependencies.

Install the SDK for the browser part:

npm install @understand/understand-js

Input Keys

Create two input keys in your channel (Settings → Input Tokens), one for the browser and one for the server, and add them to .env.local:

# visible in the browser bundle: that is fine, an input key can only send events
NEXT_PUBLIC_UNDERSTAND_TOKEN=browser-input-key
# server only
UNDERSTAND_TOKEN=server-input-key

Only variables prefixed with NEXT_PUBLIC_ are included in browser code. With separate keys you can replace the public one on its own if someone misuses it. See Input Keys.

Browser Errors

Create a client component that initialises the SDK once:

// app/understand-provider.tsx
'use client';

import { useEffect } from 'react';
import Understand from '@understand/understand-js';

let initialized = false;

export function UnderstandProvider() {
  useEffect(() => {
    if (initialized || !process.env.NEXT_PUBLIC_UNDERSTAND_TOKEN) {
      return;
    }

    initialized = true;

    Understand.init({
      env: process.env.NODE_ENV,
      token: process.env.NEXT_PUBLIC_UNDERSTAND_TOKEN
    }).catchErrors();
  }, []);

  return null;
}

Render it in your root layout:

// app/layout.tsx
import { UnderstandProvider } from './understand-provider';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <UnderstandProvider />
        {children}
      </body>
    </html>
  );
}

catchErrors() reports uncaught errors and unhandled promise rejections in the browser.

Error Boundaries (App Router)

Errors thrown while rendering are caught by Next.js error boundaries and do not reach catchErrors(). Report them from error.tsx (per route segment) and global-error.tsx (root layout):

// app/error.tsx
'use client';

import { useEffect } from 'react';
import Understand from '@understand/understand-js';

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

  return (
    <div>
      <h2>Something went wrong.</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}
// app/global-error.tsx
'use client';

import { useEffect } from 'react';
import Understand from '@understand/understand-js';

export default function GlobalError({ error }: { error: Error & { digest?: string } }) {
  useEffect(() => {
    Understand.logError(error, { digest: error.digest });
  }, [error]);

  return (
    <html>
      <body>
        <h2>Something went wrong.</h2>
      </body>
    </html>
  );
}

In production, errors from server components reach the browser with their message hidden and only a digest. The full server error is reported by instrumentation.ts (next section) and carries the same digest, so you can match the two in Search.

Server Errors with instrumentation.ts

First add a small helper that sends an error to Understand.io with fetch. It runs in both the Node.js and edge runtimes:

// lib/understand.ts
type Fields = Record<string, unknown>;

const ENDPOINT = 'https://api.understand.io/';

// turns "    at fn (file:line:col)" lines into stack frames
function parseStack(stack = '') {
  return stack
    .split('\n')
    .slice(1)
    .map(line => line.match(/at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/))
    .filter((match): match is RegExpMatchArray => match !== null)
    .map(([, fn, file, line, column]) => ({
      function: fn || '<anonymous>',
      file,
      line: Number(line),
      column: Number(column)
    }));
}

export async function reportError(error: unknown, fields: Fields = {}) {
  const token = process.env.UNDERSTAND_TOKEN;

  if (!token) {
    return;
  }

  const err = error instanceof Error ? error : new Error(String(error));
  const stack = parseStack(err.stack);

  try {
    await fetch(ENDPOINT + token, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        message: err.message,
        level: 'error',
        class: err.name,
        file: stack[0]?.file,
        line: stack[0]?.line,
        stack,
        env: process.env.NODE_ENV,
        timestamp: Date.now(),
        tags: ['nextjs'],
        ...fields
      }),
      // never let error reporting hang a request
      signal: AbortSignal.timeout(3000)
    });
  } catch {
    // reporting must never break the app
  }
}

export async function reportMessage(message: string, level = 'info', fields: Fields = {}) {
  const token = process.env.UNDERSTAND_TOKEN;

  if (!token) {
    return;
  }

  try {
    await fetch(ENDPOINT + token, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message, level, env: process.env.NODE_ENV, timestamp: Date.now(), ...fields }),
      signal: AbortSignal.timeout(3000)
    });
  } catch {
    // ignore
  }
}

Then report every uncaught server error with the onRequestError hook (Next.js 15+). Create instrumentation.ts in the project root (or in src/ if you use a src folder):

// instrumentation.ts
import type { Instrumentation } from 'next';
import { reportError } from './lib/understand';

export function register() {
  // runs once when the server starts, in both the nodejs and edge runtimes
}

export const onRequestError: Instrumentation.onRequestError = async (error, request, context) => {
  await reportError(error, {
    digest: (error as { digest?: string }).digest,
    path: request.path,
    method: request.method,
    router: context.routerKind,      // 'App Router' | 'Pages Router'
    route: context.routePath,        // e.g. '/blog/[slug]'
    route_type: context.routeType,   // 'render' | 'route' | 'action' | 'middleware'
    runtime: process.env.NEXT_RUNTIME // 'nodejs' | 'edge'
  });
};

onRequestError is called for errors in server components, route handlers, server actions and middleware, in both runtimes. On Next.js 13.4 and 14, onRequestError is not available: use try/catch with reportError (next section), and enable the instrumentation file with experimental.instrumentationHook: true in next.config.js if you use register().

Server Components, Route Handlers and Server Actions

Uncaught errors are already reported by onRequestError. For errors you handle yourself, call the helper:

// app/api/checkout/route.ts
import { reportError } from '@/lib/understand';

export async function POST(request: Request) {
  try {
    const order = await createOrder(await request.json());
    return Response.json(order);
  } catch (error) {
    await reportError(error, { tags: ['nextjs', 'checkout'] });
    return Response.json({ error: 'Checkout failed' }, { status: 500 });
  }
}
// app/actions.ts
'use server';

import { reportError, reportMessage } from '@/lib/understand';

export async function subscribe(email: string) {
  try {
    await addSubscriber(email);
    await reportMessage('subscriber added', 'info', { list: 'newsletter' });
  } catch (error) {
    await reportError(error, { action: 'subscribe' });
    throw error;
  }
}

The same works in server components. Add any fields you want to search on later, such as user_id, role or page.

Edge Runtime

The reportError helper only uses fetch and AbortSignal, so it works unchanged in middleware and in routes with export const runtime = 'edge'.

In middleware, report without delaying the response by passing the promise to event.waitUntil:

// middleware.ts
import { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';
import { reportMessage } from './lib/understand';

export function middleware(request: NextRequest, event: NextFetchEvent) {
  if (!request.cookies.has('session')) {
    event.waitUntil(reportMessage('request without session', 'warning', { path: request.nextUrl.pathname }));
  }

  return NextResponse.next();
}

In Next.js 16, middleware.ts is renamed to proxy.ts (with an exported proxy function). The helper works the same there.

Pages Router

For the Pages Router, initialise the SDK in pages/_app.tsx (inside a useEffect, as in Browser Errors), report rendering errors from a React error boundary (see React), and use onRequestError in instrumentation.ts for server errors. context.routerKind is then 'Pages Router'.