Opbeat for Node.js API

To get started, take a look at our framework specific documentation for either Express, Hapi or custom frameworks.



Starts the Opbeat agent.

Important: Put the call to this function at the very top of your main app file - before requiring any other modules.

The available configuration options are listed below. Most configuration option can be set either in the optional options object or by using environment variables. Their equivalent environment variable name is listed together with each option.

Properties on the options object will always take precedence over environment variables.

The only required parameters are appId, organizationId and secretToken.

Example usage configuring the agent to only be active in production:

  appId: '<app id>',
  organizationId: '<org id>',
  secretToken: '<token>',
  active: process.env.NODE_ENV === 'production'


  • Type: String

Your Opbeat app id. Required unless set via the OPBEAT_APP_ID environment variable.


  • Type: String

Your Opbeat orgainization id. Required unless set via the OPBEAT_ORGANIZATION_ID environment variable.


  • Type: String

Your secret Opbeat token. Required unless set via the OPBEAT_SECRET_TOKEN environment variable.


  • Type: Boolean
  • Default: true

A boolean specifying if the agent should be active or not. If active, the agent will instrument incoming HTTP requests and track errors. Normally you would not want to run the agent in your development or testing environments. If you are using the NODE_ENV envrionment variable, you can use this to determine the state:

var options = {
  active: process.env.NODE_ENV === 'production'


  • Type: Boolean
  • Default: true

A boolean specifying if the Opbeat agent should collect performance metrics for the app.

Note that both active and instrument needs to be true for instrumentation to be running.


  • Type: Array
  • Default: undefined

Used to restrict requests to certain URL’s from being instrumented.

This property should be set to an array containing one or more strings or RegExp objects. When an incoming HTTP request is detected, its URL will be tested against each element in this list. If an element in the array is a String, an exact match will be performed. If an element in the array is a RegExp object, its test function will be called with the URL being tested.

Example usage:

  ignoreUrls: [
    new RegExp('^/api/v1')


  • Type: Array
  • Default: undefined

Used to restrict requests from certain User-Agents from being instrumented.

This property should be set to an array containing one or more strings or RegExp objects. When an incoming HTTP request is detected, the User-Agent from the request headers will be tested against each element in this list. If an element in the array is a String, it’s matched against the begining of the User-Agent. If an element in the array is a RegExp object, its test function will be called with the User-Agent string being tested.

Example usage:

  ignoreUserAgents: [
    new RegExp('Safari/[0-9\.]+')


  • Type: Boolean
  • Default: false
  • Since: v3.21.0

Since version 3.21.0 of the Opbeat Node.js agent, the HTTP body associated with logged errors and sampled HTTP requests will no longer be sent to Opbeat. If you wish to log the HTTP request body, set this config option to true.


  • Type: Boolean
  • Default: true

A boolean specifying if the Opbeat agent should instrument timed out HTTP requests.


  • Type: Number
  • Default: 25000

Specify the threshold (in milliseconds) for when a timeout is considered an error.

If the timeout property is false, this property is ignored.


  • Type: String
  • Default: OS hostname

The OS hostname is automatically logged along with all errors (you can see it under the “Environment” tab on each error). If you want to overwrite this, use this option.


  • Type: String
  • Default: 'info'

Set the verbosity level the Opbeat agent. Note that this does not have any influence on what types of errors that are sent to Opbeat. This only controls how chatty the Opbeat agent are in your logs.

Possible levels are: trace, debug, info, warn, error and fatal.


  • Type: object

Set a custom logger, e.g. bunyan:

  logger: require('bunyan')({ level: 'info' })

If no custom logger is provided, Opbeat will use its built-in logger which will log to STDOUT and STDERR depending on the log level.

The logger should expose the following functions: trace, debug, info, warn, error and fatal.

Note that if a custom logger is provided, the logLevel option will be ignored.


  • Type: Boolean
  • Default: true

Whether or not the Opbeat agent should monitor for uncaught exceptions and sent them to Opbeat automatically.


  • Type: Boolean
  • Default: true

Set it option to false to disable capture of stack traces for Opbeat traces during instrumentation.


  • Type: Number
  • Default: Infinity

Setting it to 0 will disable stacktrace collection. Any finite integer value will be used as the maximum number of frames to collect. Setting it to Infinity means that all frames will be collected.


  • Type: Boolean
  • Default: true

A boolean specifying if the Opbeat agent should anonymize certain sensitive HTTP headers by default before they are sent to Opbeat. When anonymized, the header value will be set to [REDACTED]

Currently the following HTTP headers are anonymized by default:

  • Authorization - The full value of this header is redacted
  • Cookie - The cookies inside the Cookie header are analysed and their values redacted if they appear sensitive (like a session cookie). See the is-secret module for details about which patterns are considered sensitive.



Use addFilter() to supply a filter function.

Each filter function will be called just before an error or transaction context is being sent to Opbeat. This will allow you to manipulate the context being sent, for instance to always supply certain information in the extra field or remove sensitive information like passwords etc.

Each filter function will be called in the order they were added, and will receive a context object as the only argument, containing the context about to be sent to Opbeat.

The context object can contain 3 optional properties:

  • http - Will automatically be populated with information about the current HTTP request if one is detected
  • user - Will automatically be populated with information about the currently logged in user if one is detected
  • extra - Will contain extra context details that doesn’t fit into the previous two properties. You can use this to supply your own custom properties as well

See the Opbeat intake API documentation for details of the format of these properties.

The filter function is synchronous and should return the manipulated context object. If a filter function doesn’t return any value or returns a falsy value, the remaining filter functions will not be called and the transaction context or error will not be sent to Opbeat.

Example usage:

opbeat.addFilter(function (context) {
  if (context.http && context.http.headers) {
    // remove sensitive data
    delete context.http.headers['x-secret-data']

  if (!context.extra) context.extra = {}
  context.extra.caffeinated = true // supply custom context as well

  // remember to return the modified context
  return context

A set of built-in filters are added by default. See filterHttpHeaders for details.


opbeat.captureError(error[, options][, callback])

Send an error to Opbeat:

opbeat.captureError(new Error('boom!'))

The error argument can be either an Error object, a message string or a special parameterized object.

The optional options object can be used to log additional metadata with the error. For details see the metadata section.

The optional callback will be called once the error have been sent to Opbeat. If something went wrong, the callback will be called with an error as the first argument. The second argument is the URL of where you can find the logged error on opbeat.com.

Message strings

Instead of an Error object, you can log a plain text message:

opbeat.captureError('Something happened!')

This will also be logged as an error in Opbeat, but will not be associated with an exception.


To ease debugging it’s possible to send some extra data with each error you send to Opbeat. The Opbeat API supports a lot of different metadata fields, most of which are automatically managed by the opbeat node agent. But if you wish you can supply some extra details using client_supplied_id, extra, user or query. If you want to know more about all the fields, you should take a look at the full Opbeat API docs.

To supply any of these extra fields, use the optional options argument when calling opbeat.captureError().

Here are some examples:

// Sending some extra details about the user
opbeat.captureError(error, {
  user: {
    is_authenticated: true,
    id: 'unique_id',
    username: 'foo',
    email: 'foo@example.com'

// Sending some abitrary extra details using the `extra` field
opbeat.captureError(error, {
  extra: {
    some_important_metric: 'foobar'

HTTP requests

Besides the options described in the the metadata section, you can use the options argument to associate the error with an HTTP request:

opbeat.captureError(err, {
  request: req // an instance of http.IncomingMessage

This will log the URL that was requested, the HTTP headers, cookies and other useful details to help you debug the error.

In most cases this isn’t needed though, as the Opbeat agent is pretty smart at figuring out if your Node.js app is an HTTP server and if an error occurred during an incoming request. In which case it will automate this processes for you.



Alias: opbeat.middleware.express()

The Opbeat middleware can be used as-is with either Connect or Express in the same way. Take note that in your middlewares, Opbeat must appear after your router to pick up any errors that may result from handling a request.

var opbeat = require('opbeat').start()
var connect = require('connect')

var app = connect()

// your regular middleware:

// your main HTTP router
app.use(function (req, res, next) {
  throw new Error('Broke!')

// add Opbeat in the bottom of the middleware stack


Note: opbeat.middleware.express or opbeat.middleware.connect must be added to the middleware stack before any other error handling middlewares or there’s a chance that the error will never get to Opbeat.



Set or overwrite the name of the current transaction (visible in the performance monitoring breakdown). The name argument must be a string.

If you use Express 4 or Hapi 9 or greater the agent will automatically set the transaction name for you.

If you do not use Express or Hapi or the agent for some reason cannot detect the name of the HTTP route, the transaction name will default to METHOD unknown route (e.g. POST unknown route).

Read more about naming routes manually in the Get started with a custom Node.js stack article.



By default the Opbeat agent will terminate the Node.js process when an uncaught exception is detected. Use this function if you need to run any custom code before the process is terminated.

opbeat.handleUncaughtExceptions(function (err, url) {
  // Do your own stuff... and then exit:

The callback is called after the event has been sent to the Opbeat server with the following arguments:

  • err - the captured exception
  • url - the URL of where you can find the sent error on Opbeat

This function will also enable the uncaught exception handler if it was disabled using the captureExceptions configuration option.

If you don’t specify a callback, the node process is terminated automatically when an uncaught exception have been captured and sent to Opbeat.

It is recommended that you don’t leave the process running after receiving an uncaught exception, so if you are using the optional callback, remember to terminate the node process.


opbeat.trackRelease(options[, callback])

Tracks a release on Opbeat.

Though Opbeat provides other means of handling release tracking, you can also use this function to do the same.


  • cwd - An optional path on the filesystem where the git repo can be found (defaults to the current working directory)
  • rev - An optional full git revision (will try to guess the rev based on the cwd)
  • status - completed (default) or machine-completed. If machine-completed is specified, the machine attribute must be present
  • branch - Optional git branch (will try to guess the rev based on the cwd)
  • machine - Optional hostname of the server that was updated. Required if status=machine-completed

The optional callback will be called when the release has been tracked. Note that the callback will not be called upon errors. Listen instead for the error events.


The following events are emitted by the Opbeat agent.


function (url, uuid) {}

Emitted when an error have been successfully sent to Opbeat.

  • url - The url where the error can be found on opbeat.com
  • uuid - A unique id associated with the error


function (error, uuid) {}

Emitted if the agent encounters an internal error.

  • error - The error object
  • uuid - A unique id associated with the error. Note that not all errors have a uuid


The module is tested against Node.js v0.10 and above. Previous versions of Node.js is not supported.

Module Version Note
http >=0.10.x Will trace outgoing http requests
https >=0.10.x Will trace outgoing https requests
express 4.x Will trace incoming http requests and group them according to the route names, e.g. /users/{id}
hapi 9.x - 16.x Will trace incoming http requests and group them according to the route names, e.g. /users/?
koa-router ^5.2.0 Will trace incoming http requests and group them according to the route names, e.g. /users/:id
pg 4.x - 6.x Will trace all queries
mongodb-core 1.2.7 - 2.x Will trace all queries. A lot of higher level MongoDB modules use mongodb-core, so those should be supported as well
mongodb 2.x Supported via mongodb-core
mongoose 4.x Supported via mongodb-core
mongojs 1.x Supported via mongodb-core
mysql ^2.0.0 Will trace all queries
redis ^2.0.0 Will trace all queries
ioredis ^2.0.0 Will trace all queries
bluebird 2.x - 3.x Missing traces might occur if using other versions