Opbeat for Node.js API

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

start()

opbeat.start([options])

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:

require('opbeat').start({
  appId: '<app id>',
  organizationId: '<org id>',
  secretToken: '<token>',
  active: process.env.NODE_ENV === 'production'
})

appId

  • Type: String
  • Env: OPBEAT_APP_ID

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

organizationId

  • Type: String
  • Env: OPBEAT_ORGANIZATION_ID

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

secretToken

  • Type: String
  • Env: OPBEAT_SECRET_TOKEN

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

active

  • Type: Boolean
  • Default: true
  • Env: OPBEAT_ACTIVE

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'
}

instrument

  • Type: Boolean
  • Default: true
  • Env: OPBEAT_INSTRUMENT

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.

ignoreUrls

  • 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:

require('opbeat').start({
  ignoreUrls: [
    '/ping',
    /^\/admin\//i,
    new RegExp('^/api/v1')
  ]
})

ignoreUserAgents

  • 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:

require('opbeat').start({
  ignoreUserAgents: [
    'curl/',
    /pingdom/i,
    new RegExp('Safari/[0-9\.]+')
  ]
})

logBody

  • Type: Boolean
  • Default: false
  • Env: OPBEAT_LOG_BODY
  • 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.

timeout

  • Type: Boolean
  • Default: true
  • Env: OPBEAT_TIMEOUT

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

timeoutErrorThreshold

  • Type: Number
  • Default: 25000
  • Env: OPBEAT_TIMEOUT_ERROR_THRESHOLD

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

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

hostname

  • Type: String
  • Default: OS hostname
  • Env: OPBEAT_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.

logLevel

  • Type: String
  • Default: 'info'
  • Env: OPBEAT_LOG_LEVEL

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.

logger

  • Type: object

Set a custom logger, e.g. bunyan:

require('opbeat').start({
  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.

captureExceptions

  • Type: Boolean
  • Default: true
  • Env: OPBEAT_CAPTURE_EXCEPTIONS

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

stackTraceLimit

  • Type: Number
  • Default: Infinity
  • Env: OPBEAT_STACK_TRACE_LIMIT

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.

filterHttpHeaders

  • Type: Boolean
  • Default: true
  • Env: `OPBEAT_FILTER_HTTP_HEADERS“

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

addFilter()

opbeat.addFilter(callback)

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.

captureError()

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.

Metadata

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.

middleware.connect()

opbeat.middleware.connect()

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:
app.use(...)
app.use(...)

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

// add Opbeat in the bottom of the middleware stack
app.use(opbeat.middleware.connect())

app.listen(3000)

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.

setTransactionName()

opbeat.setTransactionName(name)

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.

handleUncaughtExceptions()

opbeat.handleUncaughtExceptions([callback])

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:
  process.exit(1)
})

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.

trackRelease()

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.

Options:

  • 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.

Events

The following events are emitted by the Opbeat agent.

logged

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

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

Compatibility

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/?
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