Nuxt


Overview

This guide is for Nuxt 3 and 4. A Nuxt app runs code in two places:

Where What to use
Browser The @understand/understand-js SDK in a client plugin
Server (Nitro: SSR, server/api routes, server middleware) A Nitro plugin with a small fetch helper

The server part uses the HTTP API directly, so it works with every Nitro deployment preset: Node.js, Vercel, Netlify and Cloudflare (edge).

npm install @understand/understand-js

Input Keys and Runtime Config

Create two input keys in your channel (Settings → Input Tokens), one for the browser and one for the server, and declare them in nuxt.config.ts:

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    // server only
    understandToken: '',
    public: {
      // sent to the browser: that is fine, an input key can only send events
      understandToken: ''
    }
  }
});

Set the values with environment variables, which Nuxt maps to the runtime config automatically:

NUXT_UNDERSTAND_TOKEN=server-input-key
NUXT_PUBLIC_UNDERSTAND_TOKEN=browser-input-key

Browser Errors

Create a client-only plugin (the .client suffix makes Nuxt load it in the browser only):

// plugins/understand.client.ts
import Understand from '@understand/understand-js';

export default defineNuxtPlugin(nuxtApp => {
  const config = useRuntimeConfig();

  if (!config.public.understandToken) {
    return;
  }

  Understand.init({
    env: import.meta.dev ? 'development' : 'production',
    token: config.public.understandToken
  }).catchErrors();

  // errors thrown in components (render, setup, lifecycle hooks, watchers)
  nuxtApp.hook('vue:error', (error, instance, info) => {
    Understand.logError(error, { vue_info: info, route: nuxtApp.$router?.currentRoute.value.fullPath });
  });

  // fatal errors while the app starts
  nuxtApp.hook('app:error', error => {
    Understand.logError(error, { source: 'app:error' });
  });
});

catchErrors() adds uncaught errors and unhandled promise rejections in the browser, for example from event handlers and timers.

Server Errors (Nitro)

Add a helper in server/utils, where Nitro auto-imports it in all server code:

// server/utils/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)
    }));
}

async function send(event: Fields) {
  const token = useRuntimeConfig().understandToken;

  if (!token) {
    return;
  }

  try {
    await fetch(ENDPOINT + token, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ env: import.meta.dev ? 'development' : 'production', timestamp: Date.now(), ...event }),
      // never let error reporting hang a request
      signal: AbortSignal.timeout(3000)
    });
  } catch {
    // reporting must never break the app
  }
}

export function reportToUnderstand(error: unknown, fields: Fields = {}) {
  const err = error instanceof Error ? error : new Error(String(error));
  const stack = parseStack(err.stack);

  return send({
    message: err.message,
    level: 'error',
    class: err.name,
    file: stack[0]?.file,
    line: stack[0]?.line,
    stack,
    tags: ['nuxt'],
    ...fields
  });
}

export function logToUnderstand(message: string, level = 'info', fields: Fields = {}) {
  return send({ message, level, tags: ['nuxt'], ...fields });
}

Then report every unhandled server error, including errors during server-side rendering, with a Nitro plugin:

// server/plugins/understand.ts
export default defineNitroPlugin(nitroApp => {
  nitroApp.hooks.hook('error', async (error, { event }) => {
    const statusCode = (error as { statusCode?: number }).statusCode ?? 500;

    // createError({ statusCode: 404 }) and other 4xx responses are expected
    if (statusCode < 500) {
      return;
    }

    await reportToUnderstand(error, {
      status: statusCode,
      method: event?.method,
      path: event?.path
    });
  });
});

Handled Errors in API Routes

For errors you handle yourself, call the helper:

// server/api/checkout.post.ts
export default defineEventHandler(async event => {
  try {
    const order = await createOrder(await readBody(event));
    await logToUnderstand('order created', 'info', { order_id: order.id });
    return order;
  } catch (error) {
    await reportToUnderstand(error, { path: event.path, tags: ['nuxt', 'checkout'] });
    throw createError({ statusCode: 500, statusMessage: 'Checkout failed' });
  }
});

Add any fields you want to search on later, such as user_id or role. Pass per-request values like this on each call; don't store them in a module-level variable, because a server handles many requests at once.

Nuxt 2

For Nuxt 2 (Vue 2), register a client plugin in nuxt.config.js (plugins: [{ src: '~/plugins/understand.js', mode: 'client' }]) that calls Understand.init(...).catchErrors() and sets Vue.config.errorHandler as shown in Vue.js.