Real-time error tracking
Vercel lets you deploy when you are ready. Rollbar tells you if what you deployed actually worked. No digging through logs. No waiting for user complaints. If a release introduces a problem, Rollbar flags it at the code source and ties it directly to the deploy. You stay fast without being reckless.
Start by connecting to your existing project and then run vercel link in the CLI to link to the project locally.
Run vercel env pull to make the latest environment variables available to your project locally.
Rollbar supports both the pages and app routing versions of Next.js. While there are some difference in the usage between the two, the setup remains the same.
Try our new Next.js CLI install wizard. Install Rollbar in your code base with a simple rollbar-wizard command in your CLI.
cd my-nextjs-appnpx @rollbar/wizard# npm> npm install rollbar @rollbar/react
# yarn> yarn add rollbar @rollbar/react
# pnpm> pnpm add rollbar @rollbar/reactYou can add your Rollbar access tokens as environment variables. To get started add the following environment variables to the correct .env for your environment:
These tokens can be found on your project access tokens page. Take care to not put an access token with the Post Server Item scope in an environment variable that is prefixed with NEXT_PUBLIC as those will be compiled into the code that is delivered to your client side JS.
NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN={{YOUR_SECRET}}', // Replace with your Rollbar Client access tokenROLLBAR_SERVER_TOKEN=YOUR_ROLLBAR_SERVER_ACCESS_TOKEN', // Go to Project->Project Access Tokens and create a token with a post_server scopeWe suggest you create a single instance for use server side, to be certain there are not more than one, and a config to use in your client side components. React Server Components limit you to passing simple objects as props from Server Components to Client Components, so using a simple serializable object will work regardless if you are using the app/ or pages/ routers.
/// ./src/rollbar.jsimport Rollbar from 'rollbar';
const baseConfig = { captureUncaught: true, captureUnhandledRejections: true, environment: process.env.NODE_ENV,};
export const clientConfig = { accessToken: process.env.NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN, ...baseConfig,};
export const serverInstance = new Rollbar({ accessToken: process.env.ROLLBAR_SERVER_TOKEN, ...baseConfig,});To be able to use the hooks consistently through your application. It is easiest if you configure your Rollbar Provider within your root layout.
/// ./src/app/layout.jsimport { Provider as RollbarProvider } from '@rollbar/react';import { clientConfig } from '@/rollbar';
...
export default function RootLayout(children) { return ( <RollbarProvider config={clientConfig}> <html lang="en"> <body>{children}</body> </html> </RollbarProvider> ); }Note: The Rollbar Provider uses a React Context. This context, like hooks are only available for use in your client components.
Next.js provides an error handler this handler will automatically wrap your router, at the desired level, within an Error Boundary. It is recommended to use your Rollbar instance within this error handler to report errors to Rollbar.
Creating an error.js/tsx file in the root of your app/ folder will catch any errors created within the rest of your pages. You can also specific an error handler specific to a given page within its own folder. For errors in your global layout and template see the next section.
'use client'; // Error components must be Client Components
import { useEffect } from 'react';import { ResetPage } from '@/components/ResetPage';import { useRollbar } from '@rollbar/react';
export default function Error({ error, reset }) { const rollbar = useRollbar(); useEffect(() => { rollbar.error(error); }, [error, rollbar]);
return <ResetPage reset={reset} />;}Errors generated within your root layout and template are note handled by the top level error.js/tsx file. Instead you need to create a global-error.js/tsx. This handler will catch errors, including from your root layout and relay then to Rollbar.
/// ./src/app/global-error.js'use client';
import { useEffect } from 'react';import Rollbar from 'rollbar';import { clientConfig } from '@/rollbar';import { ResetPage } from '@/components/ResetPage';
export default function GlobalError({ error, reset }) { useEffect(() => { // Root layout and template are not available in the error page // so we don't have the RollbarProvider available to use the // useRollbar hook so we need to create a new Rollbar instance here const rollbar = new Rollbar(clientConfig);
rollbar.error(error); }, [error]);
return ( <html> <body> <ResetPage reset={reset} />; </body> </html> );}The <ErrorBoundary> component provided by the @rollbar/react library may still be used if you would prefer that over the built in Next.js error handler.
'use client';
import { ErrorBoundary } from '@rollbar/react';
import { ResetPage } from '@/components/ResetPage';
export default function RollbarErrorBoundary() { return ( <ErrorBoundary fallbackUI={() => ( <ResetPage reset={() => { location.reload(); }} /> )} > <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={() => { throw new Error('Something broke'); }} > Click for Error with Rollbar Error Boundary </button> </ErrorBoundary> );}The first step in using Rollbar within the pages directory is wrapping your application with a Rollbar <Provider/> and <ErrorBoundary/>.
/// ./src/pages/_app.jsimport '@/styles/globals.css';import type { AppProps } from 'next/app';import { Provider, ErrorBoundary } from '@rollbar/react';
import { clientConfig } from '@/rollbar';
export default function App({ Component, pageProps }: AppProps) { return ( <Provider config={clientConfig}> <ErrorBoundary level="critical" errorMessage="example error boundary message" fallbackUI={() => ( <p style={{ color: 'red' }}>Oops, there was an error.</p> )} extra={{ more: 'data' }} callback={() => console.log('an exception was sent to rollbar')} > <Component {...pageProps} /> </ErrorBoundary> </Provider> );}This setup will ensure that all* (see Notes below) errors within your application are captured, and reported, and ensures that Rollbar is always available to use within lower components you may want to handle errors within also.
<br />Sometimes you want to capture errors within a more limited part of your application and show a specific error for that area of your UI. This can be accomplished by wrapping that component in an <ErrorBoundary />
/// ./SomeComponent.jsimport { ErrorBoundary } from '@rollbar/react';
import { ResetPage } from '@/components/ResetPage';
export default function SomeComponent() { return ( <ErrorBoundary fallbackUI={() => <ResetPage reset={() => {}} />}> <button onClick={() => { throw new Error('Something broke'); }} > Click for Error with Rollbar Error Boundary </button> </ErrorBoundary> );}captureUncaught or captureUnhandledRejections in your Rollbar config you may receive doubled occurrences.Start by connecting to your existing project and then run vercel link in the CLI to link to the project locally.
Run vercel env pull to make the latest environment variables available to your project locally.
Use the React SDK for sending events to Rollbar from your React application.
To install with npm:
npm install @rollbar/react rollbarTo install with yarn:
yarn add @rollbar/react rollbarCreate a separate file (src/Rollbar.js) to configure and export your Rollbar instance. In
import Rollbar from 'rollbar';
const rollbar = new Rollbar({ accessToken: '{{YOUR_SECRET}}', captureUncaught: true, captureUnhandledRejections: true, payload: { environment: process.env.NODE_ENV === 'production' ? 'production' : 'development' }});
export default rollbar;Create a simple component in src/app.js that you can use to test both handled and unhandled errors:
import React from 'react';import rollbar from './rollbar';
function App() { const triggerHandledError = () => { try { throw new Error("This is a handled error"); } catch (err) { rollbar.error("Handled error in App component", err); } };
const triggerUnhandledError = () => { // Use setTimeout to bypass React’s error boundary setTimeout(() => { throw new Error("This is an unhandled error"); }, 0); };
const triggerUnhandledPromiseRejection = () => { new Promise((resolve, reject) => { reject("This is an unhandled promise rejection"); }); };
return ( <div style={{ padding: '2rem', textAlign: 'center' }}> <h1>React + Rollbar</h1> <button onClick={triggerHandledError}>Trigger Handled Error</button><br /><br /> <button onClick={triggerUnhandledError}>Trigger Unhandled Error</button><br /><br /> <button onClick={triggerUnhandledPromiseRejection}>Trigger Promise Rejection</button> </div> );}
export default App;React’s error boundaries can catch render-time errors and pass them to Rollbar.
src/ErrorBoundary.js
import React from 'react';import rollbar from './rollbar';
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; }
static getDerivedStateFromError() { return { hasError: true }; }
componentDidCatch(error, info) { rollbar.error('React ErrorBoundary caught an error', error, { info }); }
render() { if (this.state.hasError) { return <h2>Something went wrong.</h2>; }
return this.props.children; }}
export default ErrorBoundary;Then wrap your App in the Error Boundary
src/index.js
import React from 'react';import ReactDOM from 'react-dom/client';import App from './App';import ErrorBoundary from './ErrorBoundary';
const root = ReactDOM.createRoot(document.getElementById('root'));root.render( <ErrorBoundary> <App /> </ErrorBoundary>);Please, check the JavaScript Configuration Reference for further information.
React’s error boundaries can catch render-time errors and pass them to Rollbar.
src/ErrorBoundary.js
import React from 'react';import rollbar from './rollbar';
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; }
static getDerivedStateFromError() { return { hasError: true }; }
componentDidCatch(error, info) { rollbar.error('React ErrorBoundary caught an error', error, { info }); }
render() { if (this.state.hasError) { return <h2>Something went wrong.</h2>; }
return this.props.children; }}
export default ErrorBoundary;Then wrap your App in the Error Boundary
src/index.js
import React from 'react';import ReactDOM from 'react-dom/client';import App from './App';import ErrorBoundary from './ErrorBoundary';
const root = ReactDOM.createRoot(document.getElementById('root'));root.render( <ErrorBoundary> <App /> </ErrorBoundary>);Start by connecting to your existing project and then run vercel link in the CLI to link to the project locally.
Run vercel env pull to make the latest environment variables available to your project locally.
Install the Rollbar npm package
npm install --save rollbarCreate a Rollbar configuration file (e.g, rollbar.config.js) in the root of your project and add the following content:
// rollbar.config.jsexport default { accessToken: '{{YOUR_SECRET}}', captureUncaught: true, captureUnhandledRejections: true, payload: { environment: 'dev', client: { javascript: { code_version: '1.0.0', }, }, },};Create a Vue plugin for Rollbar (e.g., rollbar.js) in your project and add the following content:
import Rollbar from 'rollbar';import config from './rollbar.config';
const rollbar = new Rollbar(config);
export default { install(app) { app.config.errorHandler = (error, vm, info) => { rollbar.error(error, { vueComponent: vm, info }); if (app.config.devtools) { console.error(error); } }; app.provide('rollbar', rollbar); },};Register the Rollbar plugin in your main app file. In your main app file (usually main.jsor app.js), import and use the Rollbar plugin:
import './assets/main.css';
import { createApp } from 'vue';import App from './App.vue';import RollbarPlugin from './rollbar'; // Path to your rollbar.js file
const app = createApp(App);
// Registering the Rollbar Error handlerapp.use(RollbarPlugin);
createApp(App).mount('#app');Create a new component for testing. Create a new file called RollbarTest.vue in your components folder (or any suitable location) and add the following content:
<!-- RollbarTest.vue --><template> <div> <button @click="triggerError">Trigger Error</button> </div></template>
<script> export default { methods: { triggerError() { // Simulate an error throw new Error('Testing Rollbar integration'); }, }, };</script>Add the RollbarTest component to the main app file:
<script setup> import RollbarTest from './components/RollbarTest.vue';</script>
<template> <main> <RollbarTest /> </main></template>Register the testing component. In your main app file (usually main.js or app.js), import the RollbarTest component and add it to your app:
import './assets/main.css';
import { createApp } from 'vue';import App from './App.vue';import RollbarPlugin from './rollbar'; // Path to your rollbar.js fileimport RollbarTest from './components/RollbarTest.vue'; // Path to your RollbarTest.vue file
const app = createApp(App);
// Registering the Rollbar Error handlerapp.use(RollbarPlugin);
// Registering the Rollbar tester componentapp.component('RollbarTest', RollbarTest);
createApp(App).mount('#app');You should see a button labeled Trigger Error on the page when you run the application. Clicking this button will simulate an error, and Rollbar will capture it and display it on your Rollbar dashboard.
Remember that this testing component (RollbarTest) is just for testing purposes. In a real-world scenario, errors would occur in your application naturally due to user interactions or other factors. The Rollbar integration, as configured in the previous steps, will capture and report those errors in your Vue 3 application.
Check the Configuration Reference for more information on the available configuration options.
Start by connecting to your existing project and then run vercel link in the CLI to link to the project locally.
Run vercel env pull to make the latest environment variables available to your project locally.
First, install the Rollbar JavaScript SDK by running the following command in your project directory:
npm install rollbarYou’ll need to configure Rollbar with your access token. You’ll typically place the configuration in your main entry file (e.g., main.js, main.ts, or a Svelte store if you’re using one).
src/main.js
import Rollbar from 'rollbar';
const rollbar = new Rollbar({ accessToken: `{{YOUR_SECRET}}` captureUncaught: true, captureUnhandledRejections: true, payload: { environment: process.env.NODE_ENV === 'production' ? 'production' : 'development' }});
// Expose Rollbar globally so that your components can access itwindow.rollbar = rollbar;To integrate Rollbar into Svelte components, you can use the Rollbar instance in your components. For instance, you can call it in a lifecycle method (like onMount) or inside event handlers to track user interactions.
<script> function triggerHandledError() { try { throw new Error("This is a handled error triggered by a button."); } catch (err) { window.rollbar.error("Handled error occurred in App.svelte", err); } }
function triggerUnhandledError() { setTimeout(() => { throw new Error("This is an unhandled error triggered by a button."); }, 0); }
function triggerUnhandledPromiseRejection() { new Promise((resolve, reject) => { reject("This is an unhandled promise rejection triggered by a button."); }); }</script>
<p>Click the buttons below to trigger errors.</p> <button on:click={triggerHandledError}>Trigger Handled Error</button><button on:click={triggerUnhandledError}>Trigger Unhandled Error</button><button on:click={triggerUnhandledPromiseRejection}>Trigger Unhandled Promise Rejection</button>Start by connecting to your existing project and then run vercel link in the CLI to link to the project locally.
Run vercel env pull to make the latest environment variables available to your project locally.
Install the Rollbar rollbar.js package using npm:
$ npm install --save rollbarImport rollbar into your app and configure it to catch uncaught exceptions:
import * as Rollbar from 'rollbar'; // When using Typescript < 3.6.0.// `import Rollbar from 'rollbar';` is the required syntax for Typescript 3.6.x.// However, it will only work when setting either `allowSyntheticDefaultImports`// or `esModuleInterop` in your Typescript options.
import { BrowserModule } from '@angular/platform-browser';import { Injectable, Injector, InjectionToken, NgModule, ErrorHandler} from '@angular/core';import { AppComponent } from './app.component';
const rollbarConfig = { accessToken: '{{YOUR_SECRET}}' captureUncaught: true, captureUnhandledRejections: true,};
@Injectable()export class RollbarErrorHandler implements ErrorHandler { constructor(@Inject(RollbarService) private rollbar: Rollbar) {}
handleError(err:any) : void { this.rollbar.error(err.originalError || err); }}
export function rollbarFactory() { return new Rollbar(rollbarConfig);}
export const RollbarService = new InjectionToken<Rollbar>('rollbar');
@NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: [ { provide: ErrorHandler, useClass: RollbarErrorHandler }, { provide: RollbarService, useFactory: rollbarFactory } ]})export class AppModule { }Run the following command in your Javascript console. Rollbar should catch the error and send it to your account:
window.onerror("TestError: Hello world", window.location.href)If your system consists of the following
@angular/cli: 1.4.3node: 6.11.3os: darwin x64@angular/animations: 4.4.3@angular/cli: 1.4.3@angular/common: 4.4.3@angular/compiler: 4.4.3@angular/compiler-cli: 4.4.3@angular/core: 4.4.3@angular/forms: 4.4.3@angular/http: 4.4.3@angular/platform-browser: 4.4.3@angular/platform-browser-dynamic: 4.4.3@angular/router: 4.4.3@angular/language-service: 4.4.3typescript: 2.3.4there are some further steps you may need to implement in order to get rollbar.js working for you.
When compiling, if you get the error Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, then the inline factory function in providers should be an exported function.
Another error you may encounter when compiling is Property 'error' does not exist on type '{}'. In this case, the RollbarErrorHandler var rollbar needs to have a type explicitly defined, i.e. var rollbar: Rollbar.
Start by connecting your existing Vercel project to Rollbar. This will create a new Rollbar project and provide you with the access tokens needed to send error payloads.
Run vercel env pull to sync the latest Rollbar access tokens to your local environment variables, making them available to your project.
To use the JavaScript rollbar.js SDK, simply copy-paste the following code into the <head> of any page you'd like to monitor. Add it before all other <script> tags to ensure that errors in those scripts are reported to Rollbar.
<script>var _rollbarConfig = { accessToken: '{{YOUR_SECRET}}', captureUncaught: true, captureUnhandledRejections: true, payload: { environment: 'testenv', // context: 'rollbar/test' client: { javascript: { code_version: '1.0', // source_map_enabled: true, // guess_uncaught_frames: true } } }};// Rollbar Snippet!function(r){var e={};function o(n){if(e[n])return e[n].exports;var t=e[n]={i:n,l:!1,exports:{}};return r[n].call(t.exports,t,t.exports,o),t.l=!0,t.exports}o.m=r,o.c=e,o.d=function(r,e,n){o.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:n})},o.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},o.t=function(r,e){if(1&e&&(r=o(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var t in r)o.d(n,t,function(e){return r[e]}.bind(null,t));return n},o.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return o.d(e,"a",e),e},o.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},o.p="",o(o.s=0)}([function(r,e,o){"use strict";var n=o(1),t=o(5);_rollbarConfig=_rollbarConfig||{},_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://cdn.rollbar.com/rollbarjs/refs/tags/v2.26.0/rollbar.min.js",_rollbarConfig.async=void 0===_rollbarConfig.async||_rollbarConfig.async;var a=n.setupShim(window,_rollbarConfig),l=t(_rollbarConfig);window.rollbar=n.Rollbar,a.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,l)},function(r,e,o){"use strict";var n=o(2),t=o(3);function a(r){return function(){try{return r.apply(this,arguments)}catch(r){try{console.error("[Rollbar]: Internal error",r)}catch(r){}}}}var l=0;function i(r,e){this.options=r,this._rollbarOldOnError=null;var o=l++;this.shimId=function(){return o},"undefined"!=typeof window&&window._rollbarShims&&(window._rollbarShims[o]={handler:e,messages:[]})}var s=o(4),d=function(r,e){return new i(r,e)},c=function(r){return new s(d,r)};function u(r){return a((function(){var e=this,o=Array.prototype.slice.call(arguments,0),n={shim:e,method:r,args:o,ts:new Date};window._rollbarShims[this.shimId()].messages.push(n)}))}i.prototype.loadFull=function(r,e,o,n,t){var l=!1,i=e.createElement("script"),s=e.getElementsByTagName("script")[0],d=s.parentNode;i.crossOrigin="",i.src=n.rollbarJsUrl,o||(i.async=!0),i.onload=i.onreadystatechange=a((function(){if(!(l||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){i.onload=i.onreadystatechange=null;try{d.removeChild(i)}catch(r){}l=!0,function(){var e;if(void 0===r._rollbarDidLoad){e=new Error("rollbar.js did not load");for(var o,n,a,l,i=0;o=r._rollbarShims[i++];)for(o=o.messages||[];n=o.shift();)for(a=n.args||[],i=0;i<a.length;++i)if("function"==typeof(l=a[i])){l(e);break}}"function"==typeof t&&t(e)}()}})),d.insertBefore(i,s)},i.prototype.wrap=function(r,e,o){try{var n;if(n="function"==typeof e?e:function(){return e||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._rollbar_wrapped&&(r._rollbar_wrapped=function(){o&&"function"==typeof o&&o.apply(this,arguments);try{return r.apply(this,arguments)}catch(o){var e=o;throw e&&("string"==typeof e&&(e=new String(e)),e._rollbarContext=n()||{},e._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=e),e}},r._rollbar_wrapped._isWrap=!0,r.hasOwnProperty))for(var t in r)r.hasOwnProperty(t)&&(r._rollbar_wrapped[t]=r[t]);return r._rollbar_wrapped}catch(e){return r}};for(var p="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleAnonymousErrors,handleUnhandledRejection,captureEvent,captureDomContentLoaded,captureLoad".split(","),f=0;f<p.length;++f)i.prototype[p[f]]=u(p[f]);r.exports={setupShim:function(r,e){if(r){var o=e.globalAlias||"Rollbar";if("object"==typeof r[o])return r[o];r._rollbarShims={},r._rollbarWrappedError=null;var l=new c(e);return a((function(){e.captureUncaught&&(l._rollbarOldOnError=r.onerror,n.captureUncaughtExceptions(r,l,!0),e.wrapGlobalEventHandlers&&t(r,l,!0)),e.captureUnhandledRejections&&n.captureUnhandledRejections(r,l,!0);var a=e.autoInstrument;return!1!==e.enabled&&(void 0===a||!0===a||"object"==typeof a&&a.network)&&r.addEventListener&&(r.addEventListener("load",l.captureLoad.bind(l)),r.addEventListener("DOMContentLoaded",l.captureDomContentLoaded.bind(l))),r[o]=l,l}))()}},Rollbar:c}},function(r,e,o){"use strict";function n(r,e,o,n){r._rollbarWrappedError&&(n[4]||(n[4]=r._rollbarWrappedError),n[5]||(n[5]=r._rollbarWrappedError._rollbarContext),r._rollbarWrappedError=null);var t=e.handleUncaughtException.apply(e,n);o&&o.apply(r,n),"anonymous"===t&&(e.anonymousErrorsPending+=1)}r.exports={captureUncaughtExceptions:function(r,e,o){if(r){var t;if("function"==typeof e._rollbarOldOnError)t=e._rollbarOldOnError;else if(r.onerror){for(t=r.onerror;t._rollbarOldOnError;)t=t._rollbarOldOnError;e._rollbarOldOnError=t}e.handleAnonymousErrors();var a=function(){var o=Array.prototype.slice.call(arguments,0);n(r,e,t,o)};o&&(a._rollbarOldOnError=t),r.onerror=a}},captureUnhandledRejections:function(r,e,o){if(r){"function"==typeof r._rollbarURH&&r._rollbarURH.belongsToShim&&r.removeEventListener("unhandledrejection",r._rollbarURH);var n=function(r){var o,n,t;try{o=r.reason}catch(r){o=void 0}try{n=r.promise}catch(r){n="[unhandledrejection] error getting `promise` from event"}try{t=r.detail,!o&&t&&(o=t.reason,n=t.promise)}catch(r){}o||(o="[unhandledrejection] error getting `reason` from event"),e&&e.handleUnhandledRejection&&e.handleUnhandledRejection(o,n)};n.belongsToShim=o,r._rollbarURH=n,r.addEventListener("unhandledrejection",n)}}}},function(r,e,o){"use strict";function n(r,e,o){if(e.hasOwnProperty&&e.hasOwnProperty("addEventListener")){for(var n=e.addEventListener;n._rollbarOldAdd&&n.belongsToShim;)n=n._rollbarOldAdd;var t=function(e,o,t){n.call(this,e,r.wrap(o),t)};t._rollbarOldAdd=n,t.belongsToShim=o,e.addEventListener=t;for(var a=e.removeEventListener;a._rollbarOldRemove&&a.belongsToShim;)a=a._rollbarOldRemove;var l=function(r,e,o){a.call(this,r,e&&e._rollbar_wrapped||e,o)};l._rollbarOldRemove=a,l.belongsToShim=o,e.removeEventListener=l}}r.exports=function(r,e,o){if(r){var t,a,l="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(t=0;t<l.length;++t)r[a=l[t]]&&r[a].prototype&&n(e,r[a].prototype,o)}}},function(r,e,o){"use strict";function n(r,e){this.impl=r(e,this),this.options=e,function(r){for(var e=function(r){return function(){var e=Array.prototype.slice.call(arguments,0);if(this.impl[r])return this.impl[r].apply(this.impl,e)}},o="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleAnonymousErrors,handleUnhandledRejection,_createItem,wrap,loadFull,shimId,captureEvent,captureDomContentLoaded,captureLoad".split(","),n=0;n<o.length;n++)r[o[n]]=e(o[n])}(n.prototype)}n.prototype._swapAndProcessMessages=function(r,e){var o,n,t;for(this.impl=r(this.options);o=e.shift();)n=o.method,t=o.args,this[n]&&"function"==typeof this[n]&&("captureDomContentLoaded"===n||"captureLoad"===n?this[n].apply(this,[t[0],o.ts]):this[n].apply(this,t));return this},r.exports=n},function(r,e,o){"use strict";r.exports=function(r){return function(e){if(!e&&!window._rollbarInitialized){for(var o,n,t=(r=r||{}).globalAlias||"Rollbar",a=window.rollbar,l=function(r){return new a(r)},i=0;o=window._rollbarShims[i++];)n||(n=o.handler),o.handler._swapAndProcessMessages(l,o.messages);window[t]=n,window._rollbarInitialized=!0}}}}]);// End Rollbar Snippet</script>Let's generate some errors with adding some lines after the Rollbar Snippet like this:
<script>Rollbar.info('Hello world!'); // Sending an arbitrary message to Rollbar
var a = null;a.hello(); // Creating an error with an invalid line of code. The SDK will automatically catch and report it.</script>
<p>Sending Errors to Rollbar</p>Save the file and open it with any browser. An info level Hello world! and an Uncaught TypeError should appear on your Rollbar Items page.
Rollbar can track which of your Person (users) are affected by each error. Also, you can add more information to the payload to understand errors in-depth. You can check further instructions for Person (user) and Custom Data enrichment in the documentation.
<script>var _rollbarConfig = { accessToken: '{{YOUR_SECRET}}', captureUncaught: true, captureUnhandledRejections: true, payload: { environment: 'testenv', // context: 'rollbar/test' client: { javascript: { code_version: '1.0', // source_map_enabled: true, // guess_uncaught_frames: true } },
// Adding info about the user affected by this event (optional) // The 'id' field is required, anything else is optional person: { id: '1234', username: 'testuser', email: 'user@email' },
// Example of adding arbitrary metadata (optional) custom: { trace_id: 'aabbccddeeff', feature_flag: [ 'feature_1', 'feature_2' ] } }};// Rollbar Snippet!function(r){var e={};function o(n){if(e[n])return e[n].exports;var t=e[n]={i:n,l:!1,exports:{}};return r[n].call(t.exports,t,t.exports,o),t.l=!0,t.exports}o.m=r,o.c=e,o.d=function(r,e,n){o.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:n})},o.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},o.t=function(r,e){if(1&e&&(r=o(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var t in r)o.d(n,t,function(e){return r[e]}.bind(null,t));return n},o.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return o.d(e,"a",e),e},o.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},o.p="",o(o.s=0)}([function(r,e,o){"use strict";var n=o(1),t=o(5);_rollbarConfig=_rollbarConfig||{},_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://cdn.rollbar.com/rollbarjs/refs/tags/v2.26.0/rollbar.min.js",_rollbarConfig.async=void 0===_rollbarConfig.async||_rollbarConfig.async;var a=n.setupShim(window,_rollbarConfig),l=t(_rollbarConfig);window.rollbar=n.Rollbar,a.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,l)},function(r,e,o){"use strict";var n=o(2),t=o(3);function a(r){return function(){try{return r.apply(this,arguments)}catch(r){try{console.error("[Rollbar]: Internal error",r)}catch(r){}}}}var l=0;function i(r,e){this.options=r,this._rollbarOldOnError=null;var o=l++;this.shimId=function(){return o},"undefined"!=typeof window&&window._rollbarShims&&(window._rollbarShims[o]={handler:e,messages:[]})}var s=o(4),d=function(r,e){return new i(r,e)},c=function(r){return new s(d,r)};function u(r){return a((function(){var e=this,o=Array.prototype.slice.call(arguments,0),n={shim:e,method:r,args:o,ts:new Date};window._rollbarShims[this.shimId()].messages.push(n)}))}i.prototype.loadFull=function(r,e,o,n,t){var l=!1,i=e.createElement("script"),s=e.getElementsByTagName("script")[0],d=s.parentNode;i.crossOrigin="",i.src=n.rollbarJsUrl,o||(i.async=!0),i.onload=i.onreadystatechange=a((function(){if(!(l||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){i.onload=i.onreadystatechange=null;try{d.removeChild(i)}catch(r){}l=!0,function(){var e;if(void 0===r._rollbarDidLoad){e=new Error("rollbar.js did not load");for(var o,n,a,l,i=0;o=r._rollbarShims[i++];)for(o=o.messages||[];n=o.shift();)for(a=n.args||[],i=0;i<a.length;++i)if("function"==typeof(l=a[i])){l(e);break}}"function"==typeof t&&t(e)}()}})),d.insertBefore(i,s)},i.prototype.wrap=function(r,e,o){try{var n;if(n="function"==typeof e?e:function(){return e||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._rollbar_wrapped&&(r._rollbar_wrapped=function(){o&&"function"==typeof o&&o.apply(this,arguments);try{return r.apply(this,arguments)}catch(o){var e=o;throw e&&("string"==typeof e&&(e=new String(e)),e._rollbarContext=n()||{},e._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=e),e}},r._rollbar_wrapped._isWrap=!0,r.hasOwnProperty))for(var t in r)r.hasOwnProperty(t)&&(r._rollbar_wrapped[t]=r[t]);return r._rollbar_wrapped}catch(e){return r}};for(var p="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleAnonymousErrors,handleUnhandledRejection,captureEvent,captureDomContentLoaded,captureLoad".split(","),f=0;f<p.length;++f)i.prototype[p[f]]=u(p[f]);r.exports={setupShim:function(r,e){if(r){var o=e.globalAlias||"Rollbar";if("object"==typeof r[o])return r[o];r._rollbarShims={},r._rollbarWrappedError=null;var l=new c(e);return a((function(){e.captureUncaught&&(l._rollbarOldOnError=r.onerror,n.captureUncaughtExceptions(r,l,!0),e.wrapGlobalEventHandlers&&t(r,l,!0)),e.captureUnhandledRejections&&n.captureUnhandledRejections(r,l,!0);var a=e.autoInstrument;return!1!==e.enabled&&(void 0===a||!0===a||"object"==typeof a&&a.network)&&r.addEventListener&&(r.addEventListener("load",l.captureLoad.bind(l)),r.addEventListener("DOMContentLoaded",l.captureDomContentLoaded.bind(l))),r[o]=l,l}))()}},Rollbar:c}},function(r,e,o){"use strict";function n(r,e,o,n){r._rollbarWrappedError&&(n[4]||(n[4]=r._rollbarWrappedError),n[5]||(n[5]=r._rollbarWrappedError._rollbarContext),r._rollbarWrappedError=null);var t=e.handleUncaughtException.apply(e,n);o&&o.apply(r,n),"anonymous"===t&&(e.anonymousErrorsPending+=1)}r.exports={captureUncaughtExceptions:function(r,e,o){if(r){var t;if("function"==typeof e._rollbarOldOnError)t=e._rollbarOldOnError;else if(r.onerror){for(t=r.onerror;t._rollbarOldOnError;)t=t._rollbarOldOnError;e._rollbarOldOnError=t}e.handleAnonymousErrors();var a=function(){var o=Array.prototype.slice.call(arguments,0);n(r,e,t,o)};o&&(a._rollbarOldOnError=t),r.onerror=a}},captureUnhandledRejections:function(r,e,o){if(r){"function"==typeof r._rollbarURH&&r._rollbarURH.belongsToShim&&r.removeEventListener("unhandledrejection",r._rollbarURH);var n=function(r){var o,n,t;try{o=r.reason}catch(r){o=void 0}try{n=r.promise}catch(r){n="[unhandledrejection] error getting `promise` from event"}try{t=r.detail,!o&&t&&(o=t.reason,n=t.promise)}catch(r){}o||(o="[unhandledrejection] error getting `reason` from event"),e&&e.handleUnhandledRejection&&e.handleUnhandledRejection(o,n)};n.belongsToShim=o,r._rollbarURH=n,r.addEventListener("unhandledrejection",n)}}}},function(r,e,o){"use strict";function n(r,e,o){if(e.hasOwnProperty&&e.hasOwnProperty("addEventListener")){for(var n=e.addEventListener;n._rollbarOldAdd&&n.belongsToShim;)n=n._rollbarOldAdd;var t=function(e,o,t){n.call(this,e,r.wrap(o),t)};t._rollbarOldAdd=n,t.belongsToShim=o,e.addEventListener=t;for(var a=e.removeEventListener;a._rollbarOldRemove&&a.belongsToShim;)a=a._rollbarOldRemove;var l=function(r,e,o){a.call(this,r,e&&e._rollbar_wrapped||e,o)};l._rollbarOldRemove=a,l.belongsToShim=o,e.removeEventListener=l}}r.exports=function(r,e,o){if(r){var t,a,l="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(t=0;t<l.length;++t)r[a=l[t]]&&r[a].prototype&&n(e,r[a].prototype,o)}}},function(r,e,o){"use strict";function n(r,e){this.impl=r(e,this),this.options=e,function(r){for(var e=function(r){return function(){var e=Array.prototype.slice.call(arguments,0);if(this.impl[r])return this.impl[r].apply(this.impl,e)}},o="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleAnonymousErrors,handleUnhandledRejection,_createItem,wrap,loadFull,shimId,captureEvent,captureDomContentLoaded,captureLoad".split(","),n=0;n<o.length;n++)r[o[n]]=e(o[n])}(n.prototype)}n.prototype._swapAndProcessMessages=function(r,e){var o,n,t;for(this.impl=r(this.options);o=e.shift();)n=o.method,t=o.args,this[n]&&"function"==typeof this[n]&&("captureDomContentLoaded"===n||"captureLoad"===n?this[n].apply(this,[t[0],o.ts]):this[n].apply(this,t));return this},r.exports=n},function(r,e,o){"use strict";r.exports=function(r){return function(e){if(!e&&!window._rollbarInitialized){for(var o,n,t=(r=r||{}).globalAlias||"Rollbar",a=window.rollbar,l=function(r){return new a(r)},i=0;o=window._rollbarShims[i++];)n||(n=o.handler),o.handler._swapAndProcessMessages(l,o.messages);window[t]=n,window._rollbarInitialized=!0}}}}]);// End Rollbar Snippet</script>For further information on the JavaScript SDK configuration, please check the Configuration Reference.
Start by connecting to your existing project and then run vercel link in the CLI to link to the project locally.
Run vercel env pull to make the latest environment variables available to your project locally.
Just copy and paste the prompt below into your AI-enabled IDE (such as Cursor, GitHub Copilot or CodeWhisperer), and it will automatically add and configure the correct Rollbar SDK for your project. All you'll need to do is paste in your access token afterward.
"Add the official Rollbar SDK to this project based on the programming language and framework used. Follow Rollbar’s official documentation to install and configure the SDK correctly. Automatically initialize Rollbar with best practices for this environment. Leave a clear placeholder comment for me to paste in my Rollbar access token."