Koa integration guide

Add BugSnag to your Koa projects to automatically capture and report errors in production.

This documentation is for version 6 of the BugSnag JavaScript notifier. We recommend upgrading to the latest release using our Upgrade guide. Documentation for the current release can be found here.

Installation

npm

Install BugSnag and the BugSnag / Koa integration from the npm registry using npm or yarn:

npm install --save @bugsnag/js @bugsnag/plugin-koa
# or
yarn add @bugsnag/js @bugsnag/plugin-koa

Basic configuration

Depending on which module system you are using, you’ll need to include BugSnag in one of the following ways:

// commonjs/node-style require
const bugsnag = require('@bugsnag/js')
const bugsnagKoa = require('@bugsnag/plugin-koa')

// ES module-style import
import bugsnag from '@bugsnag/js'
import bugsnagKoa from '@bugsnag/plugin-koa'

The simplest way to configure the client is to provide your API key as a string:

const bugsnagClient = bugsnag('YOUR_API_KEY')

To specify any additional configuration options, supply an object instead:

const bugsnagClient = bugsnag({
  apiKey: 'YOUR_API_KEY',
  otherOptions: value
})

For information on values that can be set in the configuration object, see configuration options.

Add the Koa plugin to BugSnag:

bugsnagClient.use(bugsnagKoa)

And in the part of your application where the Koa server is configured, obtain and use the Koa middleware:

const app = new Koa()
const middleware = bugsnagClient.getPlugin('koa')

// This must be the first piece of middleware in the stack.
// It can only capture errors in downstream middleware
app.use(middleware.requestHandler)

/* all other middleware and application routes go here */

// This handles any errors that Koa catches
app.on('error', middleware.errorHandler)

TypeScript support

Type definitions provided and will be picked up automatically by the TypeScript compiler when you import any of the top-level @bugsnag/* packages.

Reporting unhandled errors

After completing installation and basic configuration, unhandled exceptions and unhandled promise rejections will be automatically reported.

Unhandled errors in Koa routes will be reported with information about the request.

Reporting handled errors

Sometimes it is useful to manually notify BugSnag of a problem. To do this, call bugsnagClient.notify() with an Error object. For example:

try {
  something.risky()
} catch (e) {
  bugsnagClient.notify(e)
}

See reporting handled errors for more information.

As well as capturing and reporting unhandled errors, the requestHandler middleware attaches a request-scoped BugSnag client to ctx.bugsnag. This means that if you encounter an error in route or piece of middleware, you can call ctx.bugsnag.notify(err) which will include information about the request in the error report. For example:

app.use(async (ctx, next) => {
  const product = await db.products.find(ctx.request.query.productId)
  if (product.discontinued) {

    // This report will include detail about the request, plus anything we attach here
    ctx.bugsnag.notify(new Error('Attempted to purchase discontinued product'), {
      metaData: { product: product }
    })

    ctx.body = renderPurchaseError(product)
  } else {
    ctx.body = renderInvoice(product)
  }
})

Sending diagnostic data

Automatically captured diagnostics

BugSnag will automatically capture the following data for every exception:

  • Request info (if relevant and available)
  • Device time
  • Hostname
  • Release stage (production, beta, staging, etc)

Custom diagnostics

Error reports have a metaData property where arbitrary data can be attached.

Top-level properties of metaData will render as tabs in the BugSnag dashboard. Custom metaData can be supplied globally:

bugsnagClient.metaData = {
  company: {
    name: "Acme Co.",
    country: "uk"
  }
}

For additional options on attaching custom metaData, see customizing error reports.

Leaving breadcrumbs

Breadcrumbs are not yet supported on Node.

Identifying users

In order to correlate errors with customer reports, or to see a list of users who experienced each error, it is helpful to capture and display user information on your BugSnag dashboard.

You can provide or modify the user information of an error report by supplying the user option to a notify call, or using a beforeSend callback to modify report.user. For information on doing so, see customizing error reports.

Setting a user on the client

In the browser, or in other environments where your process will only be serving a single user (such as a CLI app in Node.js), you can attach user info directly on the bugsnagClient instance. This will then be sent along with all subsequent errors.

// Attach to the client object
bugsnagClient.user = {
  id: '3',
  name: 'Bugs Nag',
  email: 'bugs.nag@bugsnag.com'
}

Tracking releases

Configure your app version to see the release that each error was introduced in.

bugsnag({ appVersion: '4.10.0' })

Then set up a build tool integration to enable linking to code in your source control provider from the releases dashboard, timeline annotations, and stack traces.

Session tracking

BugSnag tracks the number of “sessions” that happen within your application. This allows you to compare stability scores between releases and helps you to understand the quality of your releases.

Sessions are captured and reported by default. This behavior can be disabled using the autoCaptureSessions configuration option.

By default, sessions are only reported in Node.js if you are using one of the server integrations:

  • @bugsnag/plugin-express
  • @bugsnag/plugin-restify
  • @bugsnag/plugin-koa

When using one of these integrations, BugSnag will record a session every time a request is served. A summary of sessions recorded will periodically sent to BugSnag.

If you are working with different kind of application or not using one of the server integrations above, you should call bugsnagClient.startSession() to indicate each time a session has started.

Next steps

  • View @bugsnag/js, the library powering BugSnag for Node.js, on GitHub
  • Get support for your questions and feature requests