javascript reference: Documentation for the Honeybadger JavaScript client library (SDK) and platform. # Honeybadger for Node.js and JavaScript > Complete guide to Honeybadger's JavaScript error tracking and application monitoring platform for browser and Node.js applications. Hi there! You’ve found Honeybadger’s docs on **Universal JavaScript exception tracking**. In these guides we’re going to discuss [`honeybadger.js`](https://github.com/honeybadger-io/honeybadger-js) and how to use it to track exceptions in your **Client-side JavaScript and Node.js applications**. ## How you should read the docs [Section titled “How you should read the docs”](#how-you-should-read-the-docs) * For **client-side** JavaScript, start with the [Browser Integration Guide](/lib/javascript/integration/browser/). * For **server-side** JavaScript, start with the [Node.js Integration Guide](/lib/javascript/integration/node/). * The **How-To Guides** (in the left-hand navigation menu) are general guides on how to do things with the library, and should apply to all types of applications. ## Getting support [Section titled “Getting support”](#getting-support) If you’re having trouble working with the library (such as you aren’t receiving error reports when you should be): 1. Upgrade to the latest version if possible (you can find a list of bugfixes and other changes in the [CHANGELOG](https://github.com/honeybadger-io/honeybadger-js/blob/master/CHANGELOG.md)) 2. Check out our [Frequently Asked Questions](/lib/javascript/support/faq/) 3. Run through the [Troubleshooting guide](/lib/javascript/support/troubleshooting/) 4. If you believe you’ve found a bug, [submit an issue on GitHub](https://github.com/honeybadger-io/honeybadger-js/issues/) For all other problems, contact support for help: # Capturing events with breadcrumbs > Add breadcrumbs to JavaScript error reports to track events and user actions leading up to errors. **Breadcrumbs** are events that happen right before an error occurs. Honeybadger captures [many types of breadcrumbs](#automatic-breadcrumbs) automatically, such as click events, console logs, and Ajax requests. You can enhance your ability to rapidly understand and fix your errors by capturing additional breadcrumbs throughout your application. ## Capturing breadcrumbs [Section titled “Capturing breadcrumbs”](#capturing-breadcrumbs) To capture a breadcrumb anywhere in your application: ```js Honeybadger.addBreadcrumb("Sent Email", { metadata: { user_id: user.id, body: body }, }); ``` The first argument (`message`) is the only required data. In the UI, `message` is front and center in your breadcrumbs list, so we prefer a more terse description accompanied by rich metadata. Here are the supported options when adding breadcrumbs: | Option name | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `metadata` | A (*optional*) `Object` that contains any contextual data to help debugging. Must be a single-level object with simple primitives (strings, numbers, booleans) as values. | | `category` | An (*optional*) `string` key used to group specific types of events. We primarily use this key to display a corresponding icon, however, you can use it for your own categorization if you like. | ### Categories [Section titled “Categories”](#categories) A Breadcrumb category is a top level property. It’s main purpose is to allow for display differences (icons & styling) in the UI. You may give a breadcrumb any category you wish. Unknown categories will default to the “custom” styling. Here are the current categories and a brief description of how you might categorize certain activity: | Category | Description | | -------- | ------------------------------------------- | | custom | Any other kind of breadcrumb | | error | A thrown error | | query | Access or Updates to any data or file store | | job | Queueing or Working via a job system | | request | Outbound / inbound requests | | render | Any output or serialization via templates | | log | Any messages logged | | notice | A Honeybadger Notice | ## Automatic breadcrumbs [Section titled “Automatic breadcrumbs”](#automatic-breadcrumbs) Honeybadger captures the following breadcrumbs automatically by instrumenting browser features: * Clicks * Console logs * Errors * History/location changes * Network requests (XHR and fetch) ## Enabling/disabling breadcrumbs [Section titled “Enabling/disabling breadcrumbs”](#enablingdisabling-breadcrumbs) Breadcrumbs are enabled by default. To disable breadcrumbs in your project: ```js Honeybadger.configure({ // ... breadcrumbsEnabled: false, }); ``` You can also enable/disable specific types of breadcrumbs: ```js Honeybadger.configure({ breadcrumbsEnabled: { dom: true, network: true, navigation: true, console: true, }, }); ``` *Note: This configuration applies only on the first call to `Honeybadger.configure`.* # Capturing cross-domain script errors > Capture errors from cross-domain scripts in JavaScript applications with proper CORS configuration. Honeybadger ignores cross-domain script errors by default because they contain no useful information. You can fix this by loading your scripts with [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). To enable CORS on your cross-domain scripts, add the CORS header to your web-server: ```plaintext Access-Control-Allow-Origin: * ``` Then add the [`crossorigin`](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) attribute to your script tag: ```plaintext ``` Here’s a video walkthrough of a basic, global installation: [![Using Honeybadger with JavaScript](https://embed-ssl.wistia.com/deliveries/0881945df2b2413bf15aba6fc853a7b477218048.jpg?image_play_button=true\&image_play_button_color=7b796ae0\&image_crop_resized=150x84)](https://honeybadger.wistia.com/medias/8wkvbipxxj) ### Non-blocking loading [Section titled “Non-blocking loading”](#non-blocking-loading) The default CDN installation above loads `honeybadger.min.js` synchronously so that Honeybadger’s `window.onerror` handler is in place before any other scripts run. This ensures automatic error catching works for all errors, but it means the script is render-blocking. If page load performance is a concern, you can load the script with the `defer` attribute: ```html ``` The `defer` attribute makes the CDN script download without blocking render and execute after the HTML is parsed. Since `defer` only applies to external scripts, the inline configure call uses a `DOMContentLoaded` listener to ensure it runs after the deferred script has executed. **Trade-offs to be aware of:** * **If you only use manual `Honeybadger.notify()` calls** (i.e., `enableUncaught` and `enableUnhandledRejection` are both `false`), then `defer` can be used safely as long as your `notify()` calls also run after the notifier has loaded — for example, in deferred or bundled application scripts. * **If you rely on automatic error catching** (the default), any uncaught errors or unhandled promise rejections that occur *before* the deferred script executes will not be captured. In practice, this is a small window — deferred scripts run after the DOM is parsed but before the `DOMContentLoaded` event. As an alternative, [bundling Honeybadger with npm](#installing-via-npmyarn) eliminates the extra network request entirely and gives you full control over load timing. ### Installing via NPM/YARN [Section titled “Installing via NPM/YARN”](#installing-via-npmyarn) ```plaintext # npm npm install @honeybadger-io/js --save # yarn yarn add @honeybadger-io/js ``` You can include *honeybadger.js* from the `node_modules` directory. #### Bundling with ESM (esbuild), CommonJS (Browserify/Webpack), etc. [Section titled “Bundling with ESM (esbuild), CommonJS (Browserify/Webpack), etc.”](#bundling-with-esm-esbuild-commonjs-browserifywebpack-etc) ```sh // ES module import Honeybadger from '@honeybadger-io/js'; // CommonJS var Honeybadger = require("path/to/honeybadger"); Honeybadger.configure({ apiKey: 'PROJECT_API_KEY', environment: 'production', revision: 'git SHA/project version' }); ``` * See an [example browserify + honeybadger.js project](https://github.com/honeybadger-io/honeybadger-js/tree/master/examples/browserify). * See an [example webpack + honeybadger.js project](https://github.com/honeybadger-io/honeybadger-js/tree/master/examples/webpack). #### RequireJS (AMD) [Section titled “RequireJS (AMD)”](#requirejs-amd) ```sh requirejs(["path/to/honeybadger"], function(Honeybadger) { Honeybadger.configure({ apiKey: 'PROJECT_API_KEY', environment: 'production', revision: 'git SHA/project version' }); }); ``` * See an [example requirejs + honeybadger.js project](https://github.com/honeybadger-io/honeybadger-js/tree/master/examples/requirejs). ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) By default Honeybadger will report all uncaught exceptions automatically using our `window.onerror` handler. You can also manually notify Honeybadger of errors and other events in your application code: ```javascript try { // ...error producing code... } catch (error) { Honeybadger.notify(error); } ``` ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track what users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Honeybadger.context`: ```javascript Honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) Honeybadger can also keep track of application deployments, and link errors to the version which the error occurred in. Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the *honeybadger.js* library. Read more about deploy tracking in the [API docs](/api/deployments/). ### Tracking deploys from Netlify [Section titled “Tracking deploys from Netlify”](#tracking-deploys-from-netlify) If you are deploying your site to Netlify, you can notify Honeybadger of deployments via Netlify’s webhooks. Go to the **Deploy notifications** section of the **Build & deploy** tab for your site settings, and choose to add an Outgoing webhook notification. Choose `Deploy succeeded` as the event to listen for, and use this format for your URL: `https://api.honeybadger.io/v1/deploys/netlify?api_key=YOUR_HONEYBADGER_API_KEY_HERE` The environment that will be reported to Honeybadger defaults to the Netlify environment that was deployed, but you can override that with `&environment=CUSTOM_ENV` in the webhook URL, if you like. ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. ## Collect user feedback [Section titled “Collect user feedback”](#collect-user-feedback) When an error occurs, a form can be shown to gather feedback from your users. Read more about this feature [here](/lib/javascript/errors/collecting-user-feedback/). # Chrome Extension integration guide > Honeybadger monitors your Chrome extensions for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **JavaScript error and exception tracking for your chrome extensions**. Once installed, Honeybadger will automatically report errors from your chrome extension. ## Installation [Section titled “Installation”](#installation) Code in Chrome extensions can run in different execution contexts, such as background scripts, content scripts, and popup or options pages. To monitor errors in all these contexts, you need to include the Honeybadger.js library in each of them. Download the minified version of honeybadger.js to your source code from Honeybadger’s CDN (i.e. ) and save under in your extension’s source code (i.e. `/vendor`). ### Options and popup pages [Section titled “Options and popup pages”](#options-and-popup-pages) For the html (`options` or `popup`) pages, place the following code between the `` tags of your page: ```html ``` ### Background scripts [Section titled “Background scripts”](#background-scripts) For background scripts, add the following code at the top of your background script: ```javascript importScripts(chrome.runtime.getURL("vendor/honeybadger.ext.min.js")); Honeybadger.configure({ apiKey: "PROJECT_API_KEY", environment: "production", revision: "git SHA/project version", }); ``` ### Content scripts [Section titled “Content scripts”](#content-scripts) Finally, for content scripts, the manifest file should also be updated to include the Honeybadger library: ```json { "content_scripts": [ { "matches": [""], "js": ["vendor/honeybadger.ext.min.js", "content-script.js"] } ] } ``` Then, inside the `content-script.js` file, configure Honeybadger: ```javascript Honeybadger.configure({ apiKey: "PROJECT_API_KEY", environment: "production", revision: "git SHA/project version", }); ``` See an [example chrome extension + honeybadger.js project](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/js/examples/chrome-extension). ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) By default Honeybadger will report all uncaught exceptions automatically using our `window.onerror` handler. You can also manually notify Honeybadger of errors and other events in your application code: ```javascript try { // ...error producing code... } catch (error) { Honeybadger.notify(error); } ``` ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track what users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Honeybadger.context`: ```javascript Honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) Honeybadger can also keep track of application deployments, and link errors to the version which the error occurred in. Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the *honeybadger.js* library. Read more about deploy tracking in the [API docs](/api/deployments/). ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. ## Limitations [Section titled “Limitations”](#limitations) Google’s recent extension review policies forced us to remove the feature to [Collect User Feedback](/lib/javascript/errors/collecting-user-feedback/) in Chrome Extensions. If you are already using Honeybadger in your chrome extensions, please note that Google may reject your extension when you update it. In that case, please download a new build build from our [CDN](https://js.honeybadger.io/v6.16/honeybadger.ext.min.js) and replace the existing build in your extension. If you are using the Collect User Feedback feature in your extension and would like to have it in the future, please let us know! # Ember integration guide > Honeybadger monitors your Ember applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **Ember error and exception tracking**. Once installed, Honeybadger will automatically report errors from your Ember application. ## Installation [Section titled “Installation”](#installation) First, install *honeybadger.js*: ```plaintext # npm npm add @honeybadger-io/js --save # yarn yarn add @honeybadger-io/js ``` Then, configure Ember’s [`onerror`](https://guides.emberjs.com/release/configuring-ember/debugging/#toc_miscellaneous) handler to report errors to Honeybadger: ```js // Import honeybadger.js import * as Honeybadger from "@honeybadger-io/js"; // Configure honeybadger.js Honeybadger.configure({ apiKey: "PROJECT_API_KEY", environment: "production", revision: "git SHA/project version", }); // Configure Ember's onerror handler Ember.onerror = function (error) { Honeybadger.notify(error); }; ``` ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) In addition to Ember’s `onerror` handler, Honeybadger will report all uncaught exceptions automatically using our `window.onerror` handler. To disable uncaught error reporting: ```js Honeybadger.configure({ enableUncaught: false }); ``` You can also manually notify Honeybadger of errors and other events in your application code: ```javascript try { // ...error producing code... } catch (error) { Honeybadger.notify(error); } ``` See the [Reporting Errors How-to Guide](/lib/javascript/errors/reporting-errors/) for more info. ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track what users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Honeybadger.context`: ```javascript Honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) As with vanilla JavaScript applications, you can notify Honeybadger when you’ve deployed a new build. Honeybadger will associate an error report with a specific revision number (matching the ‘revision’ field in your *honeybadger.js* configuration). Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the *honeybadger.js* library. Read more about deploy tracking in the [API docs](/api/deployments). ### Tracking deploys from Netlify [Section titled “Tracking deploys from Netlify”](#tracking-deploys-from-netlify) If you are deploying your site to Netlify, you can notify Honeybadger of deployments via Netlify’s webhooks. Go to the **Deploy notifications** section of the **Build & deploy** tab for your site settings, and choose to add an Outgoing webhook notification. Choose `Deploy succeeded` as the event to listen for, and use this format for your URL: `https://api.honeybadger.io/v1/deploys/netlify?api_key=YOUR_HONEYBADGER_API_KEY_HERE` The environment that will be reported to Honeybadger defaults to the Netlify environment that was deployed, but you can override that with `&environment=CUSTOM_ENV` in the webhook URL, if you like. ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. ## Collect user feedback [Section titled “Collect user feedback”](#collect-user-feedback) When an error occurs, a form can be shown to gather feedback from your users. Read more about this feature [here](/lib/javascript/errors/collecting-user-feedback/). # Next.js integration guide > Honeybadger monitors your Next.js applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 7 minutes Hi there! You’ve found Honeybadger’s guide to **Next.js error and exception tracking**. Once installed, Honeybadger will automatically report errors from your Next.js application. The `@honeybadger-io/nextjs` package utilizes the packages `@honeybadger-io/js`, `@honeybadger-io/react` and `@honeybadger-io/webpack` under the hood to provide a simplified integration package for Next.js applications. You can always refer to these packages’ documentation for more information and advanced configuration. ## Features [Section titled “Features”](#features) * App Router support (added with Next.js 13) * Automatic reporting of uncaught exceptions (see [Limitations](#limitations)) * Breadcrumbs * Source map upload to Honeybadger * CLI command to generate Honeybadger configuration files for Next.js runtimes ## Installation [Section titled “Installation”](#installation) Add `@honeybadger-io/nextjs` and `@honeybadger-io/react` as dependencies. ```plaintext # npm npm add @honeybadger-io/react @honeybadger-io/nextjs --save # yarn yarn add @honeybadger-io/react @honeybadger-io/nextjs ``` ## Configuration [Section titled “Configuration”](#configuration) Run the following command, which generates configuration files in your project root for each Next.js runtime: ```plaintext npx honeybadger-copy-config-files ``` The following files will added to your project: * `honeybadger.server.config.js` - Configuration file for Next.js server runtime * `honeybadger.client.config.js` - Configuration file for Next.js client runtime * `honeybadger.edge.config.js` - Configuration file for Next.js Edge runtime * `pages/_error.[js|tsx]` - Next.js Pages Router custom error component - if *pages* folder exists * `app/error.[js|tsx]` - Next.js App Router custom error component - if *app* folder exists * `app/global-error.[js|tsx]` - Next.js App Router global error component - if *app* folder exists **Note**: The `honeybadger.edge.config.js` file is necessary if you deploy your Next.js application to Vercel and use [Vercel Edge Functions](https://vercel.com/features/edge-functions). If not, you can safely remove this file. **Note**: The script will create backups of any existing files. In your `next.config.js`: ```javascript const { setupHoneybadger } = require("@honeybadger-io/nextjs"); const moduleExports = { // ... Your existing module.exports object goes here }; // Showing default values const honeybadgerNextJsConfig = { // Disable source map upload (optional) disableSourceMapUpload: false, // Hide debug messages (optional) silent: true, // More information available at @honeybadger-io/webpack: https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/webpack webpackPluginOptions: { // Required if you want to upload source maps to Honeybadger apiKey: process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY, // Required if you want to upload source maps to Honeybadger assetsUrl: process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL, revision: process.env.NEXT_PUBLIC_HONEYBADGER_REVISION, endpoint: "https://api.honeybadger.io/v1/source_maps", ignoreErrors: false, retries: 3, workerCount: 5, deploy: { environment: process.env.NEXT_PUBLIC_VERCEL_ENV || process.env.VERCEL_ENV || process.env.NODE_ENV, repository: "https://url.to.git.repository", localUsername: "username", }, }, }; module.exports = setupHoneybadger(moduleExports, honeybadgerNextJsConfig); ``` **Note**: If you want to upload source maps to Honeybadger, ensure that `disableSourceMapUpload` is set to `false` and that `apiKey` and `assetsUrl` properties are set in `webpackPluginOptions`. **Note**: The value of `assetsUrl` should be the URL to your domain suffixed with `_next`. For example if you app is deployed on Vercel and has the domain `my-app.vercel.app`, the value of `assetsUrl` should be `https://my-app.vercel.app/_next`. Optionally, you can use Honeybadger’s Error Boundary component to collect additional React contextual information for errors that occur in your React components. Simply wrap the `Component` prop in your `_app.js` file: ```jsx import { Honeybadger, HoneybadgerErrorBoundary } from "@honeybadger-io/react"; function MyApp({ Component, pageProps }) { return ( ); } export default MyApp; ``` You can read more about Error Boundaries in the [React documentation](https://reactjs.org/docs/error-boundaries.html). ## Insights instrumentation [Section titled “Insights instrumentation”](#insights-instrumentation) Enable Insights HTTP instrumentation in your Honeybadger config files to record a `request.handled` event for each inbound request. Export the config object so API and edge handlers can reuse it: honeybadger.server.config.js ```javascript import Honeybadger from "@honeybadger-io/js"; export const config = { apiKey: process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY, environment: process.env.NEXT_PUBLIC_VERCEL_ENV || process.env.VERCEL_ENV || process.env.NODE_ENV, revision: process.env.NEXT_PUBLIC_HONEYBADGER_REVISION, insights: { enabled: true, http: true }, }; Honeybadger.configure(config); ``` Do the same in `honeybadger.edge.config.js` when you use the Edge runtime. Wrap App Router route handlers, Pages Router API routes, middleware, and edge handlers with `withHoneybadger` from `@honeybadger-io/nextjs`. When Insights HTTP is enabled, each request emits `request.handled` with method, path, status, duration, `request_id`, and `correlation_id`. Pass config explicitly for API and edge handlers Webpack config-file auto-injection only reaches pages such as `_app`, `_document`, `_error`, and the App Router `main-app` entry. It does **not** reach API routes (`pages/api/*`, `app/api/*`) or edge middleware. Pass your exported config as the second argument to `withHoneybadger` in those files. The argument is ignored if Honeybadger is already configured, so it is safe to pass everywhere. App Router route handler: ```typescript import { NextResponse } from "next/server"; import { withHoneybadger } from "@honeybadger-io/nextjs"; import { config } from "../../../honeybadger.server.config"; export const GET = withHoneybadger(async () => { return NextResponse.json({ message: "hello" }); }, config); ``` Pages Router API route: ```javascript import { withHoneybadger } from "@honeybadger-io/nextjs"; import { config } from "../../honeybadger.server.config"; export default withHoneybadger((req, res) => { res.status(200).json({ message: "hello" }); }, config); ``` Edge route (import from `honeybadger.edge.config.js`): ```typescript import { NextResponse } from "next/server"; import { withHoneybadger } from "@honeybadger-io/nextjs"; import { config } from "../../../honeybadger.edge.config"; export const runtime = "edge"; export const GET = withHoneybadger(async () => { return NextResponse.json({ message: "hello from the edge" }); }, config); ``` Middleware (also runs on the edge runtime — pass edge config explicitly): ```typescript import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { withHoneybadger } from "@honeybadger-io/nextjs"; import { config } from "./honeybadger.edge.config"; export const middleware = withHoneybadger((request: NextRequest) => { return NextResponse.next(); }, config); ``` On the Node.js runtime, `request_id` and `correlation_id` are seeded onto the event context, so programmatic `Honeybadger.event(...)` calls during the request inherit them. On the **edge** runtime, those IDs are included on the `request.handled` event itself, but programmatic events do not inherit them (the edge build uses a shared global store that cannot safely isolate concurrent requests). For the full Insights configuration surface (including console logs, filtering, and sampling), see [Automatic instrumentation](/lib/javascript/insights/automatic-instrumentation/). ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) The above configuration will automatically report errors to Honeybadger in most cases (see [Limitations](#limitations)), but you can also report errors manually: ```javascript import { Honeybadger } from "@honeybadger-io/react"; Honeybadger.notify(error); ``` ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track which users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Honeybadger.setContext`: ```javascript import { Honeybadger } from "@honeybadger-io/react"; Honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Sending additional context [Section titled “Sending additional context”](#sending-additional-context) Sometimes additional application state may be helpful for diagnosing errors. You can arbitrarily specify additional key/value pairs when you invoke `setContext`. ```javascript import { Honeybadger } from "@honeybadger-io/react"; Honeybadger.setContext({ active_organization: 55, custom_configuration: false, }); ``` ## Clearing context [Section titled “Clearing context”](#clearing-context) If your user logs out or if your context changes during the React component lifetime, you can set new values as appropriate by invoking `setContext` again. Additionally, if needed, you can clear the context by invoking `clear`: ```javascript import { Honeybadger } from "@honeybadger-io/react"; // Set the context to {} Honeybadger.clear(); ``` ## Advanced usage [Section titled “Advanced usage”](#advanced-usage) `@honeybadger-io/nextjs` is built on [@honeybadger-io/js](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/js) and [@honeybadger-io/react](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/react). See the [Honeybadger JavaScript integration documentation](/lib/javascript/) for additional customization options, as well as the dedicated [React integration guide](/lib/javascript/integration/react/). ## Source map upload and tracking deploys [Section titled “Source map upload and tracking deploys”](#source-map-upload-and-tracking-deploys) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. Fill in the values under `webpackPluginOptions` in your `next.config.js` file to upload source maps to Honeybadger. You can notify Honeybadger when you’ve deployed a new build. Honeybadger will associate an error report with a specific revision number (matching the `revision` field in the configuration passed to `Honeybadger.configure`, found in one of your honeybadger.\[server|client|edge].config.js files). Set deploy information in your Honeybadger’s Next.js configuration under the `webpackPluginOptions.deploy` key. For more information, see [@honeybadger-io/webpack](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/webpack) documentation. ## Collect User Feedback [Section titled “Collect User Feedback”](#collect-user-feedback) When an error occurs, a form can be shown to gather feedback from your users. Honeybadger can automatically show the form by setting the `showUserFeedbackFormOnError` prop to `true`: ```javascript ``` Read more about this feature [here](/lib/javascript/errors/collecting-user-feedback/). ## Limitations [Section titled “Limitations”](#limitations) The following limitations are known to exist and will be tackled in future releases: * [Issue link](https://github.com/honeybadger-io/honeybadger-js/issues/1055): A custom error component is used to report uncaught exceptions to Honeybadger. This is necessary because Next.js does not provide a way to hook into the error handler. This is not a catch-all errors solution. If you are using the *Pages Router*, there are some caveats to this approach, as reported [here](https://nextjs.org/docs/advanced-features/custom-error-page#caveats). This is a limitation of Next.js, not Honeybadger’s Next.js integration. Errors thrown in middlewares or API routes will not be reported to Honeybadger, since when they reach the error component, the response status code is 404 and no error information is available. Additionally, there is an open [issue](https://github.com/vercel/next.js/issues/45535) about 404 being reported with Next.js apps deployed on Vercel, when they should be reported as 500. If you are using the *App Router*, these limitations do not apply, because errors thrown in middlewares or API routes do not reach the custom error component but are caught by the global `window.onerror` handler. However, some other server errors (i.e. from data fetching methods) will be reported with minimal information, since Next.js will send a [generic error message](https://nextjs.org/docs/app/building-your-application/routing/error-handling#handling-server-errors) to this component for better security. ## Sample applications [Section titled “Sample applications”](#sample-applications) Two sample applications are available in the [*examples*](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/nextjs/examples) folder. Follow the README instructions to run them. # Node.js integration guide > Honeybadger monitors your Node.js applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 3 minutes Hi there! You’ve found Honeybadger’s guide to **Node.js error and exception tracking**. Once installed, Honeybadger will automatically report errors from your Node.js application. ## Installation [Section titled “Installation”](#installation) First, install the npm package: ```sh npm install @honeybadger-io/js --save ``` Then, require the honeybadger module and configure your API key: ```javascript const Honeybadger = require("@honeybadger-io/js"); Honeybadger.configure({ apiKey: "[ YOUR API KEY HERE ]", }); ``` By default Honeybadger will be notified automatically of all unhandled errors which crash your node processes. Many applications catch errors, however, so you may want to set up some additional framework integrations. ## Framework integrations [Section titled “Framework integrations”](#framework-integrations) ### Express and Express-style frameworks [Section titled “Express and Express-style frameworks”](#express-and-express-style-frameworks) Errors which happen in [Express](http://expressjs.com/) or [Connect](https://github.com/senchalabs/connect#readme) apps can be automatically reported to Honeybadger by installing our middleware. The `requestHandler` middleware must be added before your other app middleware, while the `errorHandler` must be added after all app middleware and routes, but before any custom error handling middleware: ```javascript app.use(Honeybadger.requestHandler); // Use *before* all other app middleware. // Any other middleware and routes app.use(myMiddleware); app.get("/", (req, res) => {...}); app.use(Honeybadger.errorHandler); // Use *after* all other app middleware // Your custom error handling middleware app.use(myErrorMiddleware); ``` You can follow a similar pattern for most frameworks which use Express-style middleware: #### Restify [Section titled “Restify”](#restify) ```js const server = restify.createServer(); server.use(Honeybadger.requestHandler); // Other middleware and routes... server.on("restifyError", Honeybadger.errorHandler); ``` #### Sails.js [Section titled “Sails.js”](#sailsjs) For Sails.js, use `Honeybadger.errorHandler` to report errors from within your [custom `serverError` response](https://sailsjs.com/documentation/concepts/extending-sails/custom-responses). ```js const Honeybadger = require("@honeybadger-io/js"); module.exports = function serverError(optionalData) { if (_.isError(optionalData)) { Honeybadger.errorHandler(optionalData, this.req); return res.status(500).send(optionalData.stack); } }; ``` You should also add the `Honeybadger.requestHandler` at the start of your middleware chain so asynchronous context can be correctly tracked between requests: ```js // in config/http.js module.exports.http = { middleware: { order: [ "honeybadgerContext", // other middleware... ], honeybadgerContext: Honeybadger.requestHandler, }, }; ``` ### Non-Express-style frameworks [Section titled “Non-Express-style frameworks”](#non-express-style-frameworks) For frameworks that don’t use Express-style middleware, Honeybadger will still capture unhandled exceptions automatically, but you may need to add a few lines of code to capture other kinds of errors and use the context feature properly. Fastify has a dedicated plugin (below). For other frameworks, see [Tracking Context](#tracking-context). #### Fastify [Section titled “Fastify”](#fastify) Use the dedicated Fastify plugin. It is not exported from the main `@honeybadger-io/js` entry — import it from the deep path below. Install the optional peer package `fastify-plugin` (>= 4); `fastify` (>= 4) is also an optional peer. ```js const Honeybadger = require("@honeybadger-io/js"); const { fastifyPlugin } = require("@honeybadger-io/js/dist/server/fastify"); fastify.register(fastifyPlugin(Honeybadger)); fastify.setErrorHandler((err, req, reply) => Honeybadger.withRequest(req, () => { Honeybadger.notify(err); reply.send({ message: "error" }); }), ); ``` Do **not** register `Honeybadger.requestHandler` as a Fastify `preHandler` — that Express middleware expects a Node `ServerResponse` EventEmitter and is not compatible with Fastify’s reply object. The plugin isolates each request with `withRequest` and, when Insights HTTP instrumentation is enabled, emits `request.handled` events. See [Automatic instrumentation](/lib/javascript/insights/automatic-instrumentation/) for the full Insights setup. ### AWS Lambda [Section titled “AWS Lambda”](#aws-lambda) To automatically report errors which happen in your [AWS Lambda](https://aws.amazon.com/lambda/) functions, wrap your Lambda handlers in `Honeybadger.lambdaHandler()`: ```javascript async function myHandler(event, context) { // ... } exports.handler = Honeybadger.lambdaHandler(myHandler); ``` Check out our [example AWS Lambda project](https://github.com/honeybadger-io/honeybadger-js/tree/master/examples/aws-lambda) for a list of handlers with different settings. ##### Timeout warning [Section titled “Timeout warning”](#timeout-warning) If your Lambda function hits its [time limit](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html#w329aad109b7b9), it will get killed by AWS Lambda without completing. Honeybadger can notify you when your function is about time out. By default, this will be when there are only 50 milliseconds left to reach the limit. You can override this with the `timeoutWarningThresholdMs` setting: ```javascript Honeybadger.configure({ timeoutWarningThresholdMs: 1000, }); ``` You can disable the timeout warning with the `reportTimeoutWarning` setting: ```javascript Honeybadger.configure({ reportTimeoutWarning: false, }); ``` To manually report errors in a serverless environment, use `Honeybadger.notifyAsync`. Read more below. ## Manually reporting errors [Section titled “Manually reporting errors”](#manually-reporting-errors) Honeybadger reports unhandled exceptions by default. You can also manually notify Honeybadger of errors and other events in your application code: ```javascript try { // ...error producing code... } catch (error) { Honeybadger.notify(error); } ``` `Honeybadger.notify` implements a *fire-and-forget* approach, which means that you can call the function and continue execution in your application code without waiting for the error to be reported. This is OK for most applications, but in some environments this can cause problems when the execution environment could be terminated before the report is sent to Honeybadger. For this reason, you may use `Honeybadger.notifyAsync` which is a promise-based implementation of `notify` and will resolve only after the report is sent: ```javascript async function doSomething() { try { // ...error producing code... } catch (error) { await Honeybadger.notifyAsync(error); } } ``` See the [full documentation](/lib/javascript/) for more options. ## Tracking context [Section titled “Tracking context”](#tracking-context) You can add contextual information to your error reports to make debugging easier: ```javascript Honeybadger.setContext({ query: searchQuery, }); ``` When an error is captured (manually or automatically), the context will be sent along in the error report and displayed in the Context section of the Honeybadger UI. ### AdonisJS [Section titled “AdonisJS”](#adonisjs) For AdonisJS, you’ll need to do three (easy) steps: * Create a middleware that wraps your request handlers with `withRequest()`). You can generate a middleware with `adonis make:middleware HoneybadgerContext` (v4) or `node ace make:middleware HoneybadgerContext` (v5): app/Middleware/HoneybadgerContext.js ```js // Adonis v5: app/Middleware/HoneybadgerContext.ts class HoneybadgerContext { async handle({ request, response }, next) { await Honeybadger.withRequest(request, next); } } ``` * Register the middleware: ```js // Adonis v4: in start/kernel.js const globalMiddleware = ["App/Middleware/HoneybadgerContext"]; // Adonis v5: in start/kernel.ts Server.middleware.register([() => import("App/Middleware/HoneybadgerContext")]); ``` * In your exception handler’s `report()` method, make sure to use `withRequest()`. (On Adonis v4, you may need to generate an exception handler with `adonis make:ehandler`): app/Exceptions/Handler.js ```js // Adonis v5: app/Exceptions/Handler.ts class ExceptionHandler extends BaseExceptionHandler { // ... async report(error, { request }) { Honeybadger.withRequest(request, () => Honeybadger.notify(error)); } } ``` ### Hapi [Section titled “Hapi”](#hapi) In Hapi, you’ll need to wrap your request handlers in `withRequest`, as well as add an `onPreResponse` extension to report errors. ```javascript server.route({ method: 'POST', path: '/search', handler: async (request, h) => Honeybadger.withRequest(request, () => { Honeybadger.setContext({ query: request.payload.searchQuery }); return ...; }) }); server.ext('onPreResponse', (request, h) => Honeybadger.withRequest(request, () => { if (!request.response.isBoom) { return h.continue; } Honeybadger.notify(request.response); return h.continue; })); ``` ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track what users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Honeybadger.setContext`: ```javascript Honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` We’ll surface this info in a special “Affected Users” section in the Honeybadger UI. ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) Honeybadger can also keep track of application deployments, and link errors to the version which the error occurred in. Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the honeybadger.js library. Read more about deploy tracking in the [API docs](/api/deployments/). ## Uncaught exceptions [Section titled “Uncaught exceptions”](#uncaught-exceptions) Honeybadger’s default uncaught exception handler logs the error and exits the process after notifying Honeybadger of the uncaught exception. You can change the default handler by replacing the `afterUncaught` config callback with a new handler function. Honeybadger will still be notified before your handler is invoked. Note that it’s important to exit the process cleanly if you replace the handler; see [Warning: using ‘uncaughtException’ correctly](https://nodejs.org/api/process.html#process_warning_using_uncaughtexception_correctly) for additional information. ### Examples [Section titled “Examples”](#examples) ```javascript Honeybadger.configure({ afterUncaught: (err) => { doSomethingWith(err); process.exit(1); }, }); ``` ### Disable Honeybadger’s uncaught error handler [Section titled “Disable Honeybadger’s uncaught error handler”](#disable-honeybadgers-uncaught-error-handler) To disable Honeybadger’s handler entirely (restoring Node’s default behavior for uncaught exceptions), use the `enableUncaught` option when calling `Honeybadger.configure`: ```javascript Honeybadger.configure({ apiKey: '[ YOUR API KEY HERE ]' enableUncaught: false }); ``` ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. Honeybadger also supports Node’s [experimental `--source-map-support` flag](https://nodejs.org/dist/latest-v14.x/docs/api/cli.html#cli_enable_source_maps) as of **version 14+**. If you run `node` with `--source-map-support` (and are generating source maps in your build), your stack traces should be automatically translated *before* they are sent to Honeybadger. ## Sample application [Section titled “Sample application”](#sample-application) If you’d like to see the library in action before you integrate it with your apps, check out our [sample Node.js/Express application](https://github.com/honeybadger-io/crywolf-node). You can deploy the sample app to your Heroku account by clicking this button: [![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy?template=https://github.com/honeybadger-io/crywolf-node) Don’t forget to destroy the Heroku app after you’re done so that you aren’t charged for usage. The code for the sample app is [available on Github](https://github.com/honeybadger-io/crywolf-node), in case you’d like to read through it, or run it locally. # React integration guide > Honeybadger monitors your React applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **React error and exception tracking**. Once installed, Honeybadger will automatically report errors from your React application. ## Installation [Section titled “Installation”](#installation) Add *@honeybadger-io/react* as a dependency. ```plaintext # npm npm add @honeybadger-io/js @honeybadger-io/react --save # yarn yarn add @honeybadger-io/js @honeybadger-io/react ``` In your main.js: ```javascript import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import { Honeybadger, HoneybadgerErrorBoundary } from "@honeybadger-io/react"; const config = { apiKey: "PROJECT_API_KEY", environment: "production", revision: "git SHA/project version", }; const honeybadger = Honeybadger.configure(config); ReactDOM.render( , document.getElementById("root"), ); ``` ### `HoneyBadgerErrorBoundary` props [Section titled “HoneyBadgerErrorBoundary props”](#honeybadgererrorboundary-props) * `honeybadger` The Honeybadger config object. * `children` Your root `` component. * `ErrorComponent` (optional — default: “DefaultErrorComponent”) The component that will be rendered in `ErrorBoundary` children’s place when an error is thrown during React rendering. The default value for this prop is the `DefaultErrorComponent`. #### DefaultErrorComponent [Section titled “DefaultErrorComponent”](#defaulterrorcomponent) ```jsx class DefaultErrorComponent extends Component { render() { return (
An Error Occurred
{this.error}
{this.info}
); } } ``` ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) Using the example configuration above, you’ll install *@honeybadger-io/react* as React’s error handler. Additionally, by default, an error handler for all JavaScript errors will be attached to the `window.onerror` handler for JavaScript errors that may originate from React components or other JavaScript on the page. Because React doesn’t intercept all errors that may occur within a React component, errors that bubble up to the `window.onerror` handler may be missing some React component contextual information, but the stack trace will be available. If, for some reason, you do not wish to install Honeybadger’s error handler on the global `window.onerror` handler, you may add `{ enableUncaught: false }` to the configuration you’re passing to `Honeybadger.configure`. You may also manually report errors by directly invoking the [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/js) API. ```javascript honeybadger.notify(error); ``` See the [full documentation](/lib/javascript/) for more options. ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track which users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `honeybadger.setContext`: ```javascript honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Sending additional context [Section titled “Sending additional context”](#sending-additional-context) Sometimes additional application state may be helpful for diagnosing errors. You can arbitrarily specify additional key/value pairs when you invoke `setContext`. ```javascript honeybadger.setContext({ active_organization: 55, custom_configuration: false, }); ``` ## Clearing context [Section titled “Clearing context”](#clearing-context) If your user logs out or if your context changes during the React component lifetime, you can set new values as appropriate by invoking `setContext` again. Additionally, if needed, you can clear the context by invoking `clear`: ```javascript // Set the context to {} honeybadger.clear(); ``` ## Advanced usage [Section titled “Advanced usage”](#advanced-usage) *@honeybadger-io/react* is built on [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js). See the [Honeybadger JavaScript integration documentation](/lib/javascript/) for additional customization options. ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) As with vanilla JavaScript applications, you can notify Honeybadger when you’ve deployed a new build. Honeybadger will associate an error report with a specific revision number (matching the ‘revision’ field in the configuration passed to `Honeybadger.configure`). Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the *@honeybadger-io/react* library. Read more about deploy tracking in the [API docs](/api/deployments/). ### Tracking deploys from Netlify [Section titled “Tracking deploys from Netlify”](#tracking-deploys-from-netlify) If you are deploying your site to Netlify, you can notify Honeybadger of deployments via Netlify’s webhooks. Go to the **Deploy notifications** section of the **Build & deploy** tab for your site settings, and choose to add an Outgoing webhook notification. Choose `Deploy succeeded` as the event to listen for, and use this format for your URL: `https://api.honeybadger.io/v1/deploys/netlify?api_key=YOUR_HONEYBADGER_API_KEY_HERE` The environment that will be reported to Honeybadger defaults to the Netlify environment that was deployed, but you can override that with `&environment=CUSTOM_ENV` in the webhook URL, if you like. ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. ## Collect user feedback [Section titled “Collect user feedback”](#collect-user-feedback) When an error occurs, a form can be shown to gather feedback from your users. Honeybadger can automatically show the form by setting the `showUserFeedbackFormOnError` prop to `true`: ```javascript ``` Read more about this feature [here](/lib/javascript/errors/collecting-user-feedback/). ## Sample application [Section titled “Sample application”](#sample-application) A minimal implementation is included in the [*example*](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/react/example) folder in the *@honeybadger-io/react* repository. To run it from the command line, enter the following commands in your shell: ```bash cd example yarn install REACT_APP_HONEYBADGER_API_KEY=yourkey yarn start ``` Observe the command-line output to determine the appropriate URL to connect to in your browser (usually `http://localhost:3000/`). # Honeybadger for React Native > Honeybadger monitors your React Native applications for errors and exceptions so that you can fix them wicked fast. Hi there! You’ve found Honeybadger’s guide to **React Native exception and error tracking**. Once installed, Honeybadger will automatically report errors from your React Native application. ## Installation [Section titled “Installation”](#installation) From the root directory of your React Native project, add *@honeybadger-io/react-native* as a dependency: ```shell npm install "@honeybadger-io/react-native" cd ios && pod install ``` The iOS step is required to properly add the library to the Xcode project through CocoaPods. Android doesn’t require a separate step. Add the following to your **App.js** file to initialize the Honeybadger library. ```js import Honeybadger from "@honeybadger-io/react-native"; export default function App() { Honeybadger.configure({ apiKey: "[ YOUR API KEY HERE ]", }); // ... } ``` You can log into your [Honeybadger](https://app.honeybadger.io/) account to obtain your API key. See the [Configuration Reference](/lib/javascript/reference/configuration/) for a full list of config options. ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) Uncaught iOS, Android, and JavaScript errors will be automatically reported to Honeybadger by default. You may also manually report errors by directly invoking the [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/js) API. ```javascript Honeybadger.notify(error); ``` See the [full documentation](/lib/javascript/errors/reporting-errors/) for more options. ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track which users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Honeybadger.setContext`: ```javascript Honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Sending additional context [Section titled “Sending additional context”](#sending-additional-context) Sometimes additional application state may be helpful for diagnosing errors. You can arbitrarily specify additional key/value pairs when you invoke `setContext`. ```javascript Honeybadger.setContext({ active_organization: 55, custom_configuration: false, }); ``` ## Clearing context [Section titled “Clearing context”](#clearing-context) If your user logs out or if your context changes during the React component lifetime, you can set new values as appropriate by invoking `setContext` again. Additionally, if needed, you can clear the context by invoking `clear`: ```javascript // Set the context to {} Honeybadger.clear(); ``` ## Advanced usage [Section titled “Advanced usage”](#advanced-usage) *@honeybadger-io/react-native* is built on [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js). See the [Honeybadger JavaScript integration documentation](/lib/javascript/) for additional customization options. ## Source map support [Section titled “Source map support”](#source-map-support) To generate and upload source maps to Honeybadger, use the following command: ```shell npx honeybadger-upload-sourcemaps --apiKey --revision ``` The `--apiKey` param is your Honeybadger API key for the project. The `--revision` param should match the revision param of the `Honeybadger.init` call inside your application. This is done so that reported errors are correctly matched up against the generated source maps. As of version 0.70, React Native uses Hermes as the default JavaScript engine. The source maps tool assumes that your project uses Hermes. If you are building against an earlier version of React Native, or are explicitly not using Hermes, add the `--no-hermes` flag to the source maps tool, like so: ```shell npx honeybadger-upload-sourcemaps --no-hermes --apiKey --revision ``` If your React Native project uses Expo, include the `--expo` param. ```shell npx honeybadger-upload-sourcemaps --apiKey --revision --expo ``` If you just want to generate the source maps without uploading them to Honeybadger, you can use the `--skip-upload` flag. ```shell npx honeybadger-upload-sourcemaps --skip-upload --apiKey --revision ``` ## Sample applications [Section titled “Sample applications”](#sample-applications) The [*examples*](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/react-native/examples) folder contains two minimal React Native projects, demonstrating the use of the Honeybadger library. See the [README](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/react-native#example-projects) for details. # Honeybadger for React Native version <=5 > Honeybadger monitors your React Native applications for errors and exceptions so that you can fix them wicked fast. ## Installation [Section titled “Installation”](#installation) From the root directory of your React Native project: ```shell npm install "@honeybadger-io/react-native" cd ios && pod install ``` The above will download the Honeybadger React Native library and add it as a dependency of your project. The iOS step is required to properly add the library to the Xcode project through CocoaPods. Android doesn’t require a separate step. ## Initialization [Section titled “Initialization”](#initialization) Add the following to your **App.js** file to initialize the Honeybadger library. ```js import Honeybadger from "@honeybadger-io/react-native"; export default function App() { Honeybadger.configure("PROJECT_API_KEY"); // ... } ``` You can log into your [Honeybadger](https://honeybadger.io) account to obtain your API key. ## Configuration [Section titled “Configuration”](#configuration) The configure method takes additional configuration options. | Name | Type | Required | Default | Example | | ------------ | ------- | -------- | ------- | -------------------- | | apiKey | String | YES | `""` | `"hb-api-key-1234"` | | reportErrors | Boolean | NO | true | | | revision | String | NO | `""` | `"8afb34a"` | | projectRoot | String | NO | `""` | `"/path/to/project"` | ```js Honeybadger.configure("hb-api-key-1234", "8afb34a", "/path/to/project"); ``` The **reportErrors** parameter determines if errors are to be sent to Honeybadger. This is set to **true** by default. In certain environments, say, during development, it could be useful to set **reportErrors** to **false** to prevent errors from being posted to your Honeybadger account. ## Usage examples [Section titled “Usage examples”](#usage-examples) iOS, Android, and JavaScript errors will be automatically handled by the Honeybadger React Native library, by default. But you can also use the following API to customize error handling in your application. ### Honeybadger.notify(error, additionalData) [Section titled “Honeybadger.notify(error, additionalData)”](#honeybadgernotifyerror-additionaldata) You can use the **notify** method to send any kind of error, exception, object, String, etc. If sending an error or exception, the Honeybadger React Native library will attempt to extract a stack trace and any relevant information that might be useful. You can also optionally provide **additionalData** to the **notify** method, as either a string or an object, to include any relevant information. ### Honeybadger.setContext(context) [Section titled “Honeybadger.setContext(context)”](#honeybadgersetcontextcontext) If you have data that you would like to include whenever an error or an exception occurs, you can provide that data using the **setContext** method. Provide an object as an argument. You can call **setContext** as many times as needed. New context data will be merged with any previously-set context data. ```js Honeybadger.setContext({ user_id: "123abc", more: "some additional data", }); ``` ### Honeybadger.resetContext() [Section titled “Honeybadger.resetContext()”](#honeybadgerresetcontext) If you’ve used **Honeybadger.setContext()** to store context data, you can use **Honeybadger.resetContext()** to clear that data. ### Honeybadger.setLogLevel(logLevel) [Section titled “Honeybadger.setLogLevel(logLevel)”](#honeybadgersetloglevelloglevel) Sets the logging level for the Honeybadger library. ```js Honeybadger.setLogLevel("debug"); ``` The following values are accepted: | Value | Meaning | | --------- | ---------------------------------------- | | “debug” | Everything will be logged to console. | | “warning” | Only warnings will be logged to console. | | “error” | Only errors will be logged to console. | The default logging level is “warning”. # Stimulus integration guide > Honeybadger monitors your Stimulus applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **Stimulus error and exception tracking**. Once installed, Honeybadger will automatically report errors from your Stimulus application. ## Installation [Section titled “Installation”](#installation) First, install *honeybadger.js*: ```plaintext # npm npm add @honeybadger-io/js --save # yarn yarn add @honeybadger-io/js ``` Then, configure Stimulus to report errors to Honeybadger: ```js // In a Rails app this code typically resides in app/javascript/packs/application.js // In a non-Rails app, usually src/application.js // Import honeybadger.js import { Application } from "stimulus"; import * as Honeybadger from "@honeybadger-io/js"; // Configure honeybadger.js Honeybadger.configure({ apiKey: "PROJECT_API_KEY", environment: "production", revision: "git SHA/project version", }); // Start Stimulus application const application = Application.start(); // Set up error handler application.handleError = (error, message, detail) => { console.warn(message, detail); Honeybadger.notify(error); }; // Perform your other Stimulus setup here ``` ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) Honeybadger also reports all uncaught exceptions outside of Stimulus controllers using our `window.onerror` handler. To disable uncaught error reporting: ```js Honeybadger.configure({ enableUncaught: false }); ``` You can also manually notify Honeybadger of errors and other events in your application code: ```javascript try { // ...error producing code... } catch (error) { Honeybadger.notify(error); } ``` See the [Reporting Errors How-to Guide](/lib/javascript/errors/reporting-errors/) for more info. ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track what users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Honeybadger.context`: ```javascript Honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) As with vanilla JavaScript applications, you can notify Honeybadger when you’ve deployed a new build. Honeybadger will associate an error report with a specific revision number (matching the ‘revision’ field in your *honeybadger.js* configuration). Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the *honeybadger.js* library. Read more about deploy tracking in the [API docs](/api/deployments). ### Tracking deploys from Netlify [Section titled “Tracking deploys from Netlify”](#tracking-deploys-from-netlify) If you are deploying your site to Netlify, you can notify Honeybadger of deployments via Netlify’s webhooks. Go to the **Deploy notifications** section of the **Build & deploy** tab for your site settings, and choose to add an Outgoing webhook notification. Choose `Deploy succeeded` as the event to listen for, and use this format for your URL: `https://api.honeybadger.io/v1/deploys/netlify?api_key=YOUR_HONEYBADGER_API_KEY_HERE` The environment that will be reported to Honeybadger defaults to the Netlify environment that was deployed, but you can override that with `&environment=CUSTOM_ENV` in the webhook URL, if you like. ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. ## Collect user feedback [Section titled “Collect user feedback”](#collect-user-feedback) When an error occurs, a form can be shown to gather feedback from your users. Read more about this feature [here](/lib/javascript/errors/collecting-user-feedback/). # Vue.js 2.x integration guide > Honeybadger monitors your Vue.js applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **Vue.js 2.x error and exception tracking**. Once installed, Honeybadger will automatically report errors from your Vue.js application. ## Installation [Section titled “Installation”](#installation) Add *@honeybadger-io/js* and *@honeybadger-io/vue* as dependencies and configure. ```plaintext # npm npm add @honeybadger-io/js @honeybadger-io/vue --save # yarn yarn add @honeybadger-io/js @honeybadger-io/vue ``` In your main.js: ```javascript import Vue from "vue"; import HoneybadgerVue from "@honeybadger-io/vue"; const config = { apiKey: "PROJECT_API_KEY", environment: "production", revision: "git SHA/project version", }; Vue.use(HoneybadgerVue, config); ``` ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) Using the example configuration above, you’ll install *@honeybadger-ui/vue* as Vue’s error handler. Depending on the Vue version you’re using, the errors that Vue propagates through its own error handler may vary. Generally, rendering errors are passed in *Vue 2.0.0* and above, errors in component lifecycle hooks are handled in *Vue 2.2.0* and above, and errors in Vue custom event handlers will be passed through to `errorHandler` in *Vue 2.4.0* and above. Additionally, by default, an error handler for all JavaScript errors will be attached to the `window.onerror` handler for JavaScript errors that may originate from Vue components or other JavaScript on the page. Because Vue doesn’t intercept all errors that may occur within a Vue component, errors that bubble up to the `window.onerror` handler may be missing some Vue component contextual information, but the stack trace will be available. If, for some reason, you do not wish to install Honeybadger’s error handler on the global `window.onerror` handler, you may add `{ enableUncaught: false }` to the configuration when you’re registering `HoneybadgerVue`. You may also manually report errors by directly invoking the [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js) API. ```javascript Vue.$honeybadger.notify(error); ``` See the [full documentation](/lib/javascript/) for more options. ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track which users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `Vue.$honeybadger.setContext`: ```javascript Vue.$honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Sending additional context [Section titled “Sending additional context”](#sending-additional-context) Sometimes additional application state may be helpful for diagnosing errors. You can arbitrarily specify additional key/value pairs when you invoke `setContext`. ```javascript Vue.$honeybadger.setContext({ active_organization: 55, custom_configuration: false, }); ``` ## Clearing context [Section titled “Clearing context”](#clearing-context) If your user logs out or if your context changes during the Vue component lifetime, you can set new values as appropriate by invoking `setContext` again. Additionally, if needed, you can clear the context by invoking `clear`: ```javascript // Set the context to {} Vue.$honeybadger.clear(); ``` ## Advanced usage [Section titled “Advanced usage”](#advanced-usage) *@honeybadger-io/vue* is built on [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js). Most configuration options can be passed in to the `config` object you pass when registering the `HoneybadgerVue` component with your Vue app instance. As of this release, there are no Vue-specific configuration options, but that may change as we learn more about Vue users’ unique needs. In general, configuration and context options supported by the JavaScript version of the library should work as is, aside from needing to reference `Vue.$honeybadger` instead of a global `Honeybadger` variable. See the [Honeybadger JavaScript integration documentation](/lib/javascript/) for additional customization options. ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) As with vanilla JavaScript applications, you can notify Honeybadger when you’ve deployed a new build. Honeybadger will associate an error report with a specific revision number (matching the `revision` field in the configuration when registering the `HoneybadgerVue` component). Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the *@honeybadger-io/vue* library. Read more about deploy tracking in the [API docs](/api/deployments/). ### Tracking deploys from Netlify [Section titled “Tracking deploys from Netlify”](#tracking-deploys-from-netlify) If you are deploying your site to Netlify, you can notify Honeybadger of deployments via Netlify’s webhooks. Go to the **Deploy notifications** section of the **Build & deploy** tab for your site settings, and choose to add an Outgoing webhook notification. Choose `Deploy succeeded` as the event to listen for, and use this format for your URL: `https://api.honeybadger.io/v1/deploys/netlify?api_key=YOUR_HONEYBADGER_API_KEY_HERE` The environment that will be reported to Honeybadger defaults to the Netlify environment that was deployed, but you can override that with `&environment=CUSTOM_ENV` in the webhook URL, if you like. ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. ## Collect user feedback [Section titled “Collect user feedback”](#collect-user-feedback) When an error occurs, a form can be shown to gather feedback from your users. Read more about this feature [here](/lib/javascript/errors/collecting-user-feedback/). ## Sample applications [Section titled “Sample applications”](#sample-applications) Two sample applications are included in the `examples/` folder in the honeybadger-vue repository, one for vue 2.x and one for vue 3.x. You can follow the README.md inside each app to run them. # Vue.js 3.x integration guide > Honeybadger monitors your Vue.js applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 5 minutes Hi there! You’ve found Honeybadger’s guide to **Vue.js 3.x error and exception tracking**. Once installed, Honeybadger will automatically report errors from your Vue.js application. ## Installation [Section titled “Installation”](#installation) Add *@honeybadger-io/js* and *@honeybadger-io/vue* as dependencies and configure. ```shell # npm npm add @honeybadger-io/js @honeybadger-io/vue --save # yarn yarn add @honeybadger-io/js @honeybadger-io/vue ``` In your main.js (or main.ts): ```javascript import HoneybadgerVue from "@honeybadger-io/vue"; import { createApp } from "vue"; import App from "./App"; //your root component const app = createApp(App); const config = { apiKey: "PROJECT_API_KEY", environment: "production", revision: "git SHA/project version", }; app.use(HoneybadgerVue, config); app.mount("#app"); ``` ## Using Vite for development [Section titled “Using Vite for development”](#using-vite-for-development) If you are using Vite for local development, you may get CORS errors in your browser console. To work around that, you can apply the following in your vite.config.js (or vite.config.ts): ```javascript export default defineConfig({ // ... server: { cors: false, }, }); ``` ## Reporting errors [Section titled “Reporting errors”](#reporting-errors) Using the example configuration above, you’ll install *@honeybadger-io/vue* as Vue’s error handler. By default, an error handler for all JavaScript errors will be attached to the `window.onerror` handler for JavaScript errors that may originate from Vue components or other JavaScript on the page. Because Vue doesn’t intercept all errors that may occur within a Vue component, errors that bubble up to the `window.onerror` handler may be missing some Vue component contextual information, but the stack trace will be available. If, for some reason, you do not wish to install Honeybadger’s error handler on the global `window.onerror` handler, you may add `{ enableUncaught: false }` to the configuration when you’re registering `HoneybadgerVue`. You may also manually report errors by directly invoking the [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js) API. ### Composition API [Section titled “Composition API”](#composition-api) To access the Honeybadger instance when using the Composition API, use the `useHoneybadger` function: ```javascript ``` ### Options API [Section titled “Options API”](#options-api) To access the Honeybadger instance when using the Options API, use `this.$honeybadger`: ```javascript // inside a component this.$honeybadger.notify(error); ``` See the [full documentation](/lib/javascript/) for more options on how to call `notify()`. ## Identifying users [Section titled “Identifying users”](#identifying-users) Honeybadger can track which users have encountered each error. To identify the current user in error reports, add a user identifier and/or email address with `$honeybadger.setContext`: ```javascript // inside a component this.$honeybadger.setContext({ user_id: 123, user_email: "user@example.com", }); ``` ## Sending additional context [Section titled “Sending additional context”](#sending-additional-context) Sometimes additional application state may be helpful for diagnosing errors. You can arbitrarily specify additional key/value pairs when you invoke `setContext`. ```javascript // inside a component this.$honeybadger.setContext({ active_organization: 55, custom_configuration: false, }); ``` ## Clearing context [Section titled “Clearing context”](#clearing-context) If your user logs out or if your context changes during the Vue component lifetime, you can set new values as appropriate by invoking `setContext` again. Additionally, if needed, you can clear the context by invoking `clear`: ```javascript // inside a component this.$honeybadger.clear(); ``` ## Advanced usage [Section titled “Advanced usage”](#advanced-usage) *@honeybadger-io/vue* is built on [honeybadger.js](https://github.com/honeybadger-io/honeybadger-js). Most configuration options can be passed in to the `config` object you pass when registering the `HoneybadgerVue` component with your Vue app instance. As of this release, there are no Vue-specific configuration options, but that may change as we learn more about Vue users’ unique needs. In general, configuration and context options supported by the JavaScript version of the library should work as is, aside from needing to reference `this.$honeybadger` (or `app.$honeybadger` if you have access to your vue `app` instance) instead of a global `Honeybadger` variable. See the [Honeybadger JavaScript integration documentation](/lib/javascript/) for additional customization options. ## Tracking deploys [Section titled “Tracking deploys”](#tracking-deploys) As with vanilla JavaScript applications, you can notify Honeybadger when you’ve deployed a new build. Honeybadger will associate an error report with a specific revision number (matching the `revision` field in the configuration when registering the Honeybadger component). Here’s a simple `curl` script to record a deployment: ```sh HONEYBADGER_ENV="production" \ HONEYBADGER_REVISION="$(git rev-parse HEAD)" \ HONEYBADGER_REPOSITORY="$(git config --get remote.origin.url)" \ HONEYBADGER_API_KEY="Your project API key" \ && curl -g "https://api.honeybadger.io/v1/deploys?deploy[environment]=$HONEYBADGER_ENV&deploy[local_username]=$USER&deploy[revision]=$HONEYBADGER_REVISION&deploy[repository]=$HONEYBADGER_REPOSITORY&api_key=$HONEYBADGER_API_KEY" ``` Be sure that the same revision is also configured in the *@honeybadger-io/vue* library. Read more about deploy tracking in the [API docs](/api/deployments). ### Tracking deploys from Netlify [Section titled “Tracking deploys from Netlify”](#tracking-deploys-from-netlify) If you are deploying your site to Netlify, you can notify Honeybadger of deployments via Netlify’s webhooks. Go to the **Deploy notifications** section of the **Build & deploy** tab for your site settings, and choose to add an Outgoing webhook notification. Choose `Deploy succeeded` as the event to listen for, and use this format for your URL: `https://api.honeybadger.io/v1/deploys/netlify?api_key=YOUR_HONEYBADGER_API_KEY_HERE` The environment that will be reported to Honeybadger defaults to the Netlify environment that was deployed, but you can override that with `&environment=CUSTOM_ENV` in the webhook URL, if you like. ## Source map support [Section titled “Source map support”](#source-map-support) Honeybadger can automatically un-minify your code if you provide a source map along with your minified JavaScript files. See our [Source Map Guide](/lib/javascript/errors/using-source-maps/) for details. ## Collect user feedback [Section titled “Collect user feedback”](#collect-user-feedback) When an error occurs, a form can be shown to gather feedback from your users. Read more about this feature [here](/lib/javascript/errors/collecting-user-feedback/). ## Sample applications [Section titled “Sample applications”](#sample-applications) Two sample applications are included in the `examples/` folder in the honeybadger-vue repository, one for vue 2.x and one for vue 3.x. You can follow the README.md inside each app to run them. To create your own standalone Vue application, simply follow the [Quick Start](https://vuejs.org/guide/quick-start.html#with-build-tools) guide in Vue.js documentation. Remember to install Honeybadger Vue: ```bash npm add @honeybadger-io/js @honeybadger-io/vue ``` Then, in your `main.js`, you can follow the pattern in the source code in `examples/vue3/src/main.js`: ```javascript import { createApp } from "vue"; import App from "./App"; import router from "./router"; import HoneyBadgerVue from "@honeybadger-io/vue"; const app = createApp(App); app.use(HoneyBadgerVue, { apiKey: "your_api_key" }); app.use(router).mount("#app"); ``` # Configuration > Complete configuration reference for Honeybadger's JavaScript library with all available options and settings. ## Configuration file (server-side only) [Section titled “Configuration file (server-side only)”](#configuration-file-server-side-only) When using the JavaScript client in a Node.js environment, you can configure Honeybadger using a configuration file in your project’s root directory, such as `honeybadger.config.js` or `honeybadger.config.ts`. The configuration file should export an object with the configuration. An example configuration file is shown below: honeybadger.config.js ```javascript module.exports = { apiKey: process.env.HONEYBADGER_API_KEY, environment: process.env.NODE_ENV, revision: process.env.HONEYBADGER_REVISION, // etc. }; ``` ## Configuration options [Section titled “Configuration options”](#configuration-options) All of the available configuration options are shown below: ```javascript Honeybadger.configure({ // Honeybadger API key (required) apiKey: "", // The revision of the current deploy revision: "", // Project root projectRoot: "http://my-app.com", // Environment environment: "production", // Defaults to the server's hostname in Node.js hostname: "badger01", // Environments which will not report data developmentEnvironments: ["dev", "development", "test"], // Override `developmentEnvironments` to explicitly enable/disable error reporting // reportData: true, // Key values to filter from request data. Matches are partial, so "password" // and "password_confirmation" will both be filtered filters: ["creditcard", "password"], // Tags to apply to every reported error. Accepts an array of strings or a // comma-separated string. See "Tagging errors". tags: [], // Component (optional) component: "", // Action (optional) action: "", // Should unhandled errors be reported? // This option uses `window.onerror` in browsers and `uncaughtException` in Node.js enableUncaught: true, // Executed after an uncaught exception is reported in Node.js. // See "Uncaught exceptions" in the Node.js integration guide. // afterUncaught: (error) => {}, // Should unhandled Promise rejections be reported? enableUnhandledRejection: true, // Enable breadcrumbs collection breadcrumbsEnabled: true, // Insights instrumentation (off by default). `enabled` is the master switch; // `console` and `http` are ignored unless `enabled` is true. insights: { enabled: false, // Forward console logs to Honeybadger Insights console: false, // Emit request.handled events for inbound HTTP requests (server integrations) http: false, }, // Event delivery controls for Insights events: { // How often to flush buffered events, in seconds dispatchIntervalSeconds: 10, // Flush when this many events are buffered bulkThreshold: 500, // Percentage of events to send (0–100) sampleRatePercentage: 100, }, // Deprecated: use `insights.enabled` and `insights.console` instead. // Setting `eventsEnabled: true` auto-enables both (not `insights.http`) and // logs a deprecation warning. Explicit `insights` values win over the shim. // eventsEnabled: false, // Collector Host // If you are using our EU stack, this should be set to "https://eu-api.honeybadger.io". endpoint: "https://api.honeybadger.io", // The maximum number of breadcrumbs to include with error reports maxBreadcrumbs: 40, // The maximum depth allowed in deeply-nested objects maxObjectDepth: 8, // The logger to use. Should behave like `console` logger: console, // Output Honeybadger debug messages to the logger debug: false, }); ``` The following additional options are available in **browser environments**: ```javascript Honeybadger.configure({ // Send notifications asynchronously async: true, // Endpoint to submit user feedback for errors. See "Collecting User Feedback". // If you are using our EU stack, this should be set to "https://eu-api.honeybadger.io/v2/feedback". userFeedbackEndpoint: "https://api.honeybadger.io/v2/feedback", // Limit the maximum number of errors the client will send to Honeybadger // after page load. Default is unlimited (undefined) maxErrors: 20, // Ignore errors that originate from browser extensions (chrome-extension://, // moz-extension://, safari-extension://, safari-web-extension://). // Errors filtered by this option do not count against `maxErrors`. ignoreBrowserExtensionErrors: false, // Enable breadcrumbs collection breadcrumbsEnabled: true, // You can also selectively configure these types of breadcrumbs: // breadcrumbsEnabled: { // dom: true, // network: true, // navigation: true, // console: true // } // Element attributes to prefer when naming elements in click breadcrumbs. // See "Naming elements in click breadcrumbs" below. breadcrumbsSelectorAttributes: ["data-hb-name"], }); ``` The following additional options are available in **serverless environments** (currently AWS Lambda): ```javascript Honeybadger.configure({ // Report a warning to Honeybadger when a Lambda function is about to reach // its configured time limit reportTimeoutWarning: true, // How close (in milliseconds) the function must get to the Lambda time // limit before the timeout warning is reported timeoutWarningThresholdMs: 50, }); ``` See [Timeout warning](/lib/javascript/integration/node/#timeout-warning) in the Node.js integration guide for details. ### Naming elements in click breadcrumbs [Section titled “Naming elements in click breadcrumbs”](#naming-elements-in-click-breadcrumbs) When you click an element, Honeybadger records a `ui.click` breadcrumb containing a CSS selector for that element. By default the selector is built from each element’s tag, id, and classes, which can be hard to read in apps that use utility CSS frameworks such as Tailwind: ```plaintext body > div#root > main > div.flex.min-h-screen.flex-col.font-sans.antialiased > ... ``` To make these breadcrumbs legible, add a `data-hb-name` attribute to the elements you care about. When a clicked element — or one of its ancestors — has the attribute, its value replaces that element’s selector segment, and the nearest named ancestor anchors the selector, so everything above it is dropped. Given this markup: ```html

Acme Corp

``` Clicking the heading records the selector `deal-card > h3.text-left.font-semibold` instead of the full chain from ``. Use `breadcrumbsSelectorAttributes` to reuse attributes you already have, such as the test IDs from your test suite. The first attribute in the list that is present on an element wins: ```javascript Honeybadger.configure({ breadcrumbsSelectorAttributes: ["data-hb-name", "data-testid"], }); ``` Set the option to `[]` to disable this behavior and always build selectors from tags, ids, and classes. ## Configuring with environment variables [Section titled “Configuring with environment variables”](#configuring-with-environment-variables) Unlike some of our other client libraries, *honeybadger.js* does **not** automatically read configuration from environment variables; to use environment variables, you must configure Honeybadger like this: ```javascript Honeybadger.configure({ apiKey: process.env.HONEYBADGER_API_KEY, environment: process.env.NODE_ENV, revision: process.env.HONEYBADGER_REVISION, // etc. }); ``` Note that `process.env` may not be available outside of Node.js by default (it depends on your JavaScript build system). For example, [in Webpack you need to use `environmentPlugin`](https://webpack.js.org/plugins/environment-plugin/) to make `process.env` keys available in source files. ## `beforeEvent` handlers [Section titled “beforeEvent handlers”](#beforeevent-handlers) `beforeEvent` handlers run before each Insights event is sent to Honeybadger. Handlers may be synchronous or asynchronous. Return `false` (or a promise that resolves to `false`) to skip the event, or mutate the payload in place to change what is sent. See [Filtering events](/lib/javascript/insights/filtering-events/). ```javascript Honeybadger.beforeEvent((event) => { if (event.event_type === "request.handled" && event.path === "/health") { return false; } }); ``` ## `beforeNotify` handlers [Section titled “beforeNotify handlers”](#beforenotify-handlers) `beforeNotify` handlers run before each notice (error report) is sent to Honeybadger. There are two cases this might be useful: 1. Filtering out unwanted error reports by returning `false` from a handler 2. Sanitizing or enhancing notice data before being sent to Honeybadger ### Usage examples [Section titled “Usage examples”](#usage-examples) Sanitizing notice data: ```javascript Honeybadger.beforeNotify((notice) => { if (/creditCard/.test(notice.url)) { notice.url = "[FILTERED]"; } }); ``` Adding additional context to notice data: ```javascript Honeybadger.beforeNotify((notice) => { notice.context.session_id = MyApp.sessionId; }); ``` Adding additional context to notice data from an async source: ```javascript Honeybadger.beforeNotify(async (notice) => { notice.context.state = await MyApp.getState(); }); ``` Skipping a notice: ```javascript Honeybadger.beforeNotify((notice) => { if (/third-party-domain/.test(notice.stack)) { return false; } }); ``` ## `afterNotify` handlers [Section titled “afterNotify handlers”](#afternotify-handlers) `afterNotify` handlers run *after* each notice (error report) is sent to Honeybadger. Here are two cases where this is useful: 1. Displaying the ID of the Honeybadger notice to users 2. Handling errors if the Honeybadger API rejects the notice ### Usage examples [Section titled “Usage examples”](#usage-examples-1) Log a URL to the error report in Honeybadger: ```javascript Honeybadger.afterNotify((err, notice) => { if (err) { return console.log(`Honeybadger notification failed: ${err}`); } console.log( `Honeybadger notice: https://app.honeybadger.io/notice/${notice.id}`, ); }); ``` An `afterNotify` handler can also be attached to a single error report: ```javascript Honeybadger.notify("testing", { afterNotify: (err, notice) => console.log(err || notice.id), }); ``` ### Notice properties [Section titled “Notice properties”](#notice-properties) The following notice properties are available in `notice` objects: * `notice.stack` - The stack trace (read only) * `notice.backtrace` - The parsed backtrace object * `notice.name` - The exception class name * `notice.message` - The error message * `notice.url` - The current url * `notice.projectRoot` - The root url * `notice.environment` - Name of the environment. example: “production” * `notice.component` - Similar to a rails controller name. example: “users” * `notice.action` - Similar to a rails action name. example: “create” * `notice.fingerprint` - A unique fingerprint, used to customize grouping of errors in Honeybadger * `notice.context` - The context object * `notice.tags` - A string comma-separated list of tags * `notice.params` - An object of request parameters * `notice.session` - An object of request session key/values * `notice.headers` - An object of request headers * `notice.cookies` - An object of cookie key/values. May also be sent as a string in the document.cookie “foo=bar;bar=baz” format. The following additional notice properties are available in `afterNotify` handlers: * `notice.id` - The UUID of the error in Honeybadger # Supported versions > View supported browsers and Node.js versions for Honeybadger's JavaScript error tracking and application monitoring library. ## Browser [Section titled “Browser”](#browser) * [`@honeybadger-io/js`](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/js) works in **all modern browsers** and is tested back to the following versions: | Chrome | Edge | Firefox | Safari | | ------ | ---- | ------- | ------ | | 49.0 | 15.0 | 58.0 | 12.1 | * [`@honeybadger-io/webpack`](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/webpack) supports Webpack **v3+**. * [`@honeybadger-io/rollup-plugin`](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/rollup-plugin) supports Rollup **v3+**. ## Node.js [Section titled “Node.js”](#nodejs) * [`@honeybadger-io/js`](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/js) supports all [currently maintained Node.js releases](https://nodejs.org/en/about/releases/). # Frequently asked questions > Find answers to frequently asked questions about Honeybadger's JavaScript error tracking and application monitoring library. ## How do I ignore certain errors? [Section titled “How do I ignore certain errors?”](#how-do-i-ignore-certain-errors) Return `false` to a `Honeybadger.beforeNotify` handler: ```js Honeybadger.beforeNotify(function (notice) { if (/third-party-domain/.test(notice.stack)) { return false; } }); ``` For more information, see [Reducing Noise](/lib/javascript/errors/reducing-noise/). ## Why aren’t my Source Maps working? [Section titled “Why aren’t my Source Maps working?”](#why-arent-my-source-maps-working) Check out the [Troubleshooting](/lib/javascript/support/troubleshooting/#source-map-is-not-working) section. # Troubleshooting > Troubleshoot common issues with Honeybadger's JavaScript library and resolve integration problems. Common issues/workarounds for [`honeybadger.js`](https://github.com/honeybadger-io/honeybadger-js) are documented here. If you don’t find a solution to your problem here or in our [support documentation](/lib/javascript/#getting-support), email and we’ll assist you! ## Before you start troubleshooting [Section titled “Before you start troubleshooting”](#before-you-start-troubleshooting) 1. Make sure you are on the latest version of [*honeybadger.js*](https://github.com/honeybadger-io/honeybadger-js) 2. Enable the [`debug` config option](/lib/javascript/reference/configuration/) ## All errors are not reported [Section titled “All errors are not reported”](#all-errors-are-not-reported) If *no* errors are reported (even manually via `Honeybadger.notify`): 1. Is the [`apiKey` config option](/lib/javascript/reference/configuration/) configured? 2. Is the error ignored in a [`beforeNotify` callback](/lib/javascript/errors/reducing-noise/)? ## Uncaught errors are not reported [Section titled “Uncaught errors are not reported”](#uncaught-errors-are-not-reported) If you can report errors using `Honeybadger.notify`, but uncaught errors are not automatically reported: 1. Is the [`enableUncaught` config option](/lib/javascript/reference/configuration/#configuration-options) enabled? It must be enabled for uncaught errors to be reported. It is enabled by default. 2. Is Honeybadger’s `window.onerror` callback installed? Check `window.onerror` in the console and make sure it originates in honeybadger.js or honeybadger.min.js (or wherever you are hosting our JavaScript). If it doesn’t, it’s possible some 3rd-party code is overriding our callback. 3. If the error originates in a file hosted on a different domain, is CORs enabled? If you host your assets on a CDN (or if the domain is different from where your HTML is served) you may need to enable CORS on your asset domain for the `window.onerror` errors to be reported. See for more info. If this is the issue, you should see logs similar to this: ```plaintext [Log] [Honeybadger] Ignoring cross-domain script error. ``` 4. Does your application or framework handle errors internally? If you’re using a framework, search the documentation for “error handling”. For example, Ember provides its own `Ember.onerror` callback which you must configure in order for uncaught errors to be reported: ```js Ember.onerror = function (error) { Honeybadger.notify(error); }; ``` ## Errors are reported twice [Section titled “Errors are reported twice”](#errors-are-reported-twice) 1. If it’s a React app, are you running in dev mode? React’s [Strict Mode](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects) may cause double rendering, causing Honeybadger to report multiple errors. This shouldn’t be a problem in your production build. For more info, see [github.com/honeybadger-io/honeybadger-react#247](https://github.com/honeybadger-io/honeybadger-react/issues/247) ## Source map is not working [Section titled “Source map is not working”](#source-map-is-not-working) ### Did the error happen *before* the source map was uploaded? [Section titled “Did the error happen before the source map was uploaded?”](#did-the-error-happen-before-the-source-map-was-uploaded) Honeybadger **does not** apply source maps to errors that have already occurred. If the error in question first occurred before the source map was uploaded, that’s likely the problem—look for a newer version of the error. You may also want to delete the old error in the Honeybadger UI to avoid confusion. ### Did the build process modify the output *after* it generated your source map? [Section titled “Did the build process modify the output after it generated your source map?”](#did-the-build-process-modify-the-output-after-it-generated-your-source-map) If a source map is available but translation is not working, **make sure that your build process did not add extra lines/comments to the top of your minified JavaScript file**, which could throw off the mapping information. For example, line 1 column 123 would become line 2 column 123, which would not translate. Likewise, **ensure that your build process or CDN does not minify the file twice.** Some CDN providers (such as Cloudflare) can auto-minify your JavaScript files after you upload them—such options should be disabled. ### If you are hosting your source map [Section titled “If you are hosting your source map”](#if-you-are-hosting-your-source-map) In some cases a few minified errors may get through before we have the chance to download and process your hosted source map. If your source map is not being applied to your errors after the first few minutes: 1. Is your minified file publicly accessible? Try downloading it with `curl`: ```sh curl https://www.example.com/assets/application.min.js ``` 2. Does the [`minified_url`](https://docs.honeybadger.io/lib/javascript/errors/using-source-maps/#uploading-your-source-map) point to the correct URL? If you are using [@honeybadger-io/webpack](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/webpack) or [@honeybadger-io/rollup-plugin](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/rollup), this parameter is built using the [`assetsUrl`](https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/webpack#plugin-parameters) parameter. 3. Does your minified file have [the `sourceMappingURL` comment](/lib/javascript/errors/using-source-maps/#hosting-your-source-map)? 4. Is your Source Map file publicly accessible? Try downloading it with `curl`: ```sh curl https://www.example.com/assets/application.min.js.map ``` 5. If using [Authentication](/lib/javascript/errors/using-source-maps/#authentication), is the `Honeybadger-Token` header validated correctly? Try downloading with `curl`: ```sh curl -H"Honeybadger-Token: token" https://www.example.com/assets/application.min.js.map ``` ### If you are uploading your source map [Section titled “If you are uploading your source map”](#if-you-are-uploading-your-source-map) 1. Navigate to **Project Settings** -> **Source Maps** -> **Uploaded Source Maps**, then: 2. Does the **Minified URL** for your source map match the minified URL in your JavaScript stack trace? The URLs must match exactly, with the exception of [wildcards](/api/reporting-source-maps/#wildcards) and query strings (which are ignored). 3. Does the **revision** match the `revision` key in the **Application Environment** section of the error page? If it doesn’t, [make sure the `revision` of your uploaded source map is the same as the `revision` configured in `honeybadger.js`](/lib/javascript/errors/using-source-maps/#versioning-your-project). 4. Was the source map uploaded **before** the first error for that revision occurred? Source mappings are cached, meaning that uploading the source map after the error occurred has no effect. The only way to get a new mapping in this case is to deploy a new revision, making sure the source map upload completes before the code is live. 5. If your build process includes compression, make sure your source map files are not compressed (such as with gzip compression) when you upload them. 6. Can you parse your source map as JSON? Source map files must be valid JSON. ## Error in `beforeNotify` handler [Section titled “Error in beforeNotify handler”](#error-in-beforenotify-handler) If you’re using *honeybadger.js* < 1.0.4, upgrade to a more recent version. [1.0.4 fixed a bug in `beforeNotify`](https://github.com/honeybadger-io/honeybadger-js/blob/master/CHANGELOG.md#104---2019-06-12) which prevented some properties from being available on the notice object (which would most likely result in `ReferenceError` in certain use cases). # Upgrading to @honeybadger-io/js v3.0 > Upgrade guide for migrating to Honeybadger JavaScript library v3 with breaking changes and new features. The new [@honeybadger-io/js](https://www.npmjs.com/package/@honeybadger-io/js) package is a universal/isomorphic JavaScript package combining the deprecated [honeybadger-js for browsers](https://www.npmjs.com/package/honeybadger-js) and the [honeybadger for Node.js](https://www.npmjs.com/package/honeybadger) NPM packages. **Moving forward, development for both platforms will happen on @honeybadger-io/js** ([source code on GitHub](https://github.com/honeybadger-io/honeybadger-js)). The new API is mostly the same as the old packages, with a few small changes. ## Upgrading from honeybadger-js v2.x (client-side) [Section titled “Upgrading from honeybadger-js v2.x (client-side)”](#upgrading-from-honeybadger-js-v2x-client-side) If you currently use the [honeybadger-js](https://www.npmjs.com/package/honeybadger-js) package, this section is for you. The changes between *honeybadger-js* and *@honeybadger-io/js* are minimal. First, replace the old package with the new one: ```sh npm uninstall honeybadger-js npm install @honeybadger-io/js ``` Next, replace any `require`/`import` statements that reference “honeybadger-js”: ```js const Honeybadger = require("@honeybadger-io/js"); // Or: // import Honeybadger from '@honeybadger-io/js'; Honeybadger.configure({ apiKey: "project api key", environment: "production", revision: "git SHA/project version", }); ``` Finally, review this list of changes: * Previously deprecated snake case config options such as `api_key`, `project_root`, etc. are no longer supported. Use `apiKey`, `projectRoot` instead. * Stack traces are now parsed client-side; `notice.stack` is now read-only in [`beforeNotify` handlers](/lib/javascript/reference/configuration/#beforenotify-handlers), and a new `notice.backtrace` object has been added. * The `max_depth` config option is now `maxObjectDepth` * The `host` and `port` config options are now `endpoint` * `onerror` is now `enableUncaught` * The `onunhandledrejection` config option is now `enableUnhandledRejection` * The `ignorePatterns` config option has been removed. Use a [`beforeNotify` handler](/lib/javascript/reference/configuration/#beforenotify-handlers) instead: ```js const ignorePatterns = [/NoisyError/i, /unwanted error message/i]; Honeybadger.beforeNotify(function (notice) { if (ignorePatterns.some((p) => p.test(notice.message))) { return false; } }); ``` * `Honeybadger.wrap` [has been removed](https://github.com/honeybadger-io/honeybadger-js/pull/506). If you used this functionality, you can recreate it like so: ```js Honeybadger.wrap = function (func) { try { func.apply(this, arguments); } catch (error) { Honeybadger.notify(error); throw error; } }; ``` See [configuration](/lib/javascript/reference/configuration/) for an up-to-date list of available config options. Feel free to [email support](mailto:support@honeybadger.io?subject=honeybadger-js%20v3%20upgrade) if you run into issues not mentioned here. ### CDN users [Section titled “CDN users”](#cdn-users) If you use the CDN instead of the NPM package, replace your current script tag with the **v3.0** script tag: ```html ``` ## Upgrading from honeybadger 1.x (Node.js) [Section titled “Upgrading from honeybadger 1.x (Node.js)”](#upgrading-from-honeybadger-1x-nodejs) If you currently use the [honeybadger](https://www.npmjs.com/package/honeybadger) package, this section is for you. First, replace the old package with the new one: ```sh npm uninstall honeybadger npm install @honeybadger-io/js ``` Next, replace any `require` statements that reference “honeybadger-js”: ```js const Honeybadger = require("@honeybadger-io/js"); Honeybadger.configure({ apiKey: "project api key", environment: "production", revision: "git SHA/project version", }); ``` Finally, review this list of changes: * Environment variables are no longer configured by default; you must explicitly call `Honeybadger.configure`, i.e.: ```js Honeybadger.configure({ apiKey: process.env.HONEYBADGER_API_KEY, environment: process.env.HONEYBADGER_ENVIRONMENT, }); ``` * [`Honeybadger.logger`](https://github.com/honeybadger-io/honeybadger-node#configuring-the-default-logger) is now the [`logger` config option](/lib/javascript/reference/configuration/#configuration-options). * [`Honeybadger.onUncaughtException`](https://github.com/honeybadger-io/honeybadger-node#honeybadgeronuncaughtexception-configure-the-uncaught-exception-handler) is now the [`afterUncaught` config option](/lib/javascript/reference/configuration/#configuration-options). * [Events](https://github.com/honeybadger-io/honeybadger-node#events) are no longer emitted. Use [`beforeNotify` and `afterNotify` handlers instead](/lib/javascript/reference/configuration/#beforenotify-handlers). See [configuration](/lib/javascript/reference/configuration/) for an up-to-date list of available config options. Feel free to [email support](mailto:support@honeybadger.io?subject=honeybadger-js%20v3%20upgrade) if you run into issues not mentioned here.