Node.js agent API

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

Starting the agent

Important: The Opbeat agent needs to be started as the first thing in your application - before any other module is required. This means that you should probably require and start it in your applications main file (usually index.js, server.js or app.js).

There is two ways to start the Opbeat agent:

  • Require the opbeat module and call the start function on the returned agent:
    var opbeat = require('opbeat').start({...})
    
  • Require the opbeat/start script:
    var opbeat = require('opbeat/start')
    

If you are using Babel, you need to use the opbeat/start approach.

Configuring the agent

There is three ways to configure the Opbeat agent:

  1. If calling the start function, you can supply a configurations object as the first argument. The option parameters given here will take precedence over config options provided by other means
  2. If a given config option is not provided in the call to the start function (or if requiring the opbeat/start script), Opbeat will look for the config option in the optional Opbeat configuration file
  3. If a config option is not provided in any of the above means, Opbeat will look for its associated environment variable. You can see the expected names of these environment variables in the documentation for the start options below

Opbeat configuration file

The Opbeat agent will look for a file named opbeat.js in the current working directory. You can specify a custom path for this file using the OPBEAT_CONFIG_FILE environment variable (this path must include the filename).

The configuration file is expected to export an object following the same conventions as the options object given as the first argument to the start function, e.g:

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

Agent API

The Opbeat agent is a singleton. You get the agent instance by either requireing opbeat or opbeat/start.

The agent is also returned by the start() function, which allows you to require and start the agent on the same line:

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

If you need to access the Agent in any part of your codebase, you can simply require opbeat to access the already started singleton. You therefore don’t need to manage or pass around the started Agent your self.

opbeat.start()

opbeat.start([options])

Starts the Opbeat agent and returns it self.

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 other means.

organizationId

  • Type: String
  • Env: OPBEAT_ORGANIZATION_ID

Your Opbeat orgainization id. Required unless set via other means.

secretToken

  • Type: String
  • Env: OPBEAT_SECRET_TOKEN

Your secret Opbeat token. Required unless set via other means.

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.

captureTraceStackTraces

  • Type: Boolean
  • Default: true
  • Env: OPBEAT_CAPTURE_TRACE_STACK_TRACES

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

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.

flushInterval

  • Type: Number
  • Default: 60
  • Env: OPBEAT_FLUSH_INTERVAL

The Opbeat agent maintains an in-memory queue to which recorded metrics and sampled transactions are added when they end. By default, this queue is flushed and sent to Opbeat for processing every 60 seconds.

Use this option to change that interval. The value is expected to be in seconds.

Lowering this interval can reduce memory usage on Node.js applications with a high number of transactions.

Note: The queue is flushed only 5 seconds after the first transaction have ended on a newly started Node process. This ensures that you don’t have to wait for the entire flushInterval to pass to see the first data on opbeat.com. From there on the flushInterval option is used.

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

opbeat.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 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']
  }

  // remember to return the modified context
  return context
})

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

Though you can also use filter functions to add new contextual information to the user and extra properties, it’s recommended that you use opbeat.setUserContext() and opbeat.setExtraContext() for that purpose.

opbeat.setUserContext()

opbeat.setUserContext(context)

Call this to enrich collected performance data and errors with information about the user/client. This function can be called at any point during the request/response life cycle (i.e. while a transaction is active).

The provided user context is displayed along side other contextual information in a “User” tab under the Performance section and on errors on opbeat.com.

The given context argument must be an object and can contain the following properties (all optional):

  • id - The users ID
  • username - The users username
  • email - The users e-mail

The given context will be added to the active transaction. If no active transaction can be found, false is returned. Otherwise true.

It’s possible to call this function multiple times within the scope of the same active transaction. Each time the properties of the context arguement is shallow merged with the context previously given.

If an error is captured, the context from the active transaction is used as context for the captured error and any custom context given as the 2nd argument to opbeat.captureError takes precedence and is shallow merged on top.

opbeat.setExtraContext()

opbeat.setExtraContext(context)

Call this to enrich collected performance data and errors with any information that you think will help you debug performance issues and errors. This function can be called at any point during the request/response life cycle (i.e. while a transaction is active).

The provided extra context is displayed along side other contextual information in a “Extra” tab under the Performance section and on errors on opbeat.com.

The given context argument must be an object and can contain any property that can be JSON encoded.

The given context will be added to the active transaction. If no active transaction can be found, false is returned. Otherwise true.

It’s possible to call this function multiple times within the scope of the same active transaction. Each time the properties of the context arguement is shallow merged with the context previously given.

If an error is captured, the context from the active transaction is used as context for the captured error and any custom context given as the 2nd argument to opbeat.captureError takes precedence and is shallow merged on top.

opbeat.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 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: {
    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'
  }
})

To supply per-request metadata to all errors captured in one central location, use opbeat.setUserContext() and opbeat.setExtraContext().

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.

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

opbeat.startTransaction()

var transaction = opbeat.startTransaction([name][, type])

Start a new transaction.

Arguments:

Use this function to create a custom transaction. Note that Opbeat will do this for you automatically when ever your application receives an incomming HTTP request. You only need to use this function to create custom transactions.

Each unique type of transaction have its own pane in the Performance section on opbeat.com. In each pane transactions are grouped by name.

There’s a special type called request which is used by the agent for the transactions automatically created when an incomming HTTP request is detected.

See Transaction API docs for details on how to use custom transactions.

opbeat.endTransaction()

opbeat.endTransaction()

Ends the active transaction. If no transaction is currently active, nothing happens.

Note that Opbeat will do this for you automatically for all regular HTTP transactions. You only need to use this function to end custom transactions created by opbeat.startTransaction() or if you wish the end a regular transaction prematurely.

Alternatively you can call end() directly on an active transaction object.

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 a supported router/framework the agent will automatically set the transaction name for you.

If you do not use Express, hapi or koa-router or if 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.

opbeat.buildTrace()

var trace = opbeat.buildTrace()

Prepare and return a new custom trace associated with the current active transaction.

See Trace API docs for details on how to use custom traces.

Gotcha: If there’s no active transaction available, null will be returned.

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

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

Event: ‘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

Event: ‘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

Transaction API

A transaction groups multiple traces in a logical group.

To get a Transaction object, you need to call opbeat.startTransaction().

To see an example of using custom transactions, see the Custom Transactions in Node.js article.

transaction.name

  • Type: String
  • Default: unnamed

The name of the transaction.

Can be used to set or overwrite the name of the transaction (visible in the performance monitoring breakdown). If you don’t have access to the current transaction, you can also set the name using opbeat.setTransactionName().

Transaction with the same name and type are grouped together in the Performance section on opbeat.com.

transaction.type

  • Type: String
  • Default: custom

The type of the transaction.

Each unique type of transaction have its own pane in the Performance section on opbeat.com.

There’s a special type called request which is used by the agent for the transactions automatically created when an incomming HTTP request is detected.

transaction.result

  • Type: Number
  • Default: 200

The transaction result.

The result is used when graphing the transactions in the “Requests per minute” graph under the Performance section on opbeat.com.

Think of the transaction result as equivalent to the status code of an HTTP response. All transactions in the 200-299 range will be grouped and graphed together in the “Request per minute” graph. Similarly all transaction with a result in the 300-399 range, the 400-499 range and the 500-599 range will each be grouped and graphed together.

Any transaction with a result not within the 200-599 range will not be included in the graph.

transaction.end()

transaction.end()

Ends the transaction and truncates all un-ended child traces. If the transaction has already ended, nothing happens.

Alternatively you can call opbeat.endTransaction() to end the active transaction.

Trace API

A trace measures the duration of a single event.

To get a Trace object, you need to call opbeat.buildTrace().

To see an example of using custom traces, see the Custom Traces in Node.js article.

trace.transaction

  • Type: Transaction

A reference to the parent transaction object.

All traces belongs to a transaction.

trace.name

  • Type: String
  • Default: unnamed

The name of the trace. This can also be set via trace.start().

The name is shown above the trace-graph on opbeat.com.

trace.type

  • Type: String
  • Default: custom

The type of trace. This can also be set via trace.start().

The type is a hierarchical string used to group similar traces together. For instance, all traces of MySQL queries are given the type db.mysql.query.

Currently only the first part of the string (the prefix) have special meaning - db in this example. In the future this might change. The prefix is used to choose the color of the trace-graph on opbeat.com.

The following prefixes are currently recognized:

Prefix Color Legend
app Blue App
db Orange Db
cache Turquoise Cache
template Green Template
ext Purple External

The color gray is given to traces with any prefix not listed here.

trace.start()

trace.start([name][, type])

Start a trace.

Arguments:

  • name - The name of the trace (string). You can alternatively set this via trace.name. Defaults to unnamed
  • type - The type of trace (string). You can alternatively set this via trace.type. Defaults to custom.code

When a trace is started it will measure the time until trace.end() or trace.truncate() is called.

trace.end()

trace.end()

End the trace. If the trace has already ended, nothing happens.

A trace that isn’t ended before the parent transaction ends will be truncated.

trace.truncate()

trace.truncate()

Truncates and ends the trace. If the trace is already ended or truncated, nothing happens.

A truncated trace is a special type of ended trace. It’s used to indicate that the measured event took longer than the duration recorded by the trace.

Truncated traces will be shown with an arrow on the trace-graph pointing right, indicating that the trace continued past the measured point.

For details see the announcement.

Compatibility

See the Compatibility article for details.