Svelte

Installing Rollbar SDK in the Svelte Framework | Support Level: Community

Integrating Rollbar into a Svelte Application

Setting up Rollbar in your Svelte application involves three main steps:

  1. Installing the Rollbar SDK
  2. Configuring Rollbar
  3. Capturing errors in your components

This guide covers Vite + Svelte and SvelteKit, on Svelte 4 and 5. It needs Node.js 20.19 or later, or 22.12 or later.


Installation

First, install the Rollbar npm package:

npm install rollbar

Or if using yarn:

yarn add rollbar

Configuration

Create Rollbar once, in your entry file. A second new Rollbar(...) in a store or a component reports every crash twice.

Vite + Svelte (src/main.js):

// src/main.js
import './app.css';
import { mount } from 'svelte';
import App from './App.svelte';
import Rollbar from 'rollbar';

const rollbar = new Rollbar({
  accessToken: import.meta.env.VITE_ROLLBAR_ACCESS_TOKEN,
  captureUncaught: true,
  captureUnhandledRejections: true,
  payload: {
    environment: import.meta.env.MODE || 'development',
    client: {
      javascript: {
        code_version: '1.0.0',
      }
    }
  }
});

// Expose Rollbar globally for use in Svelte components
window.rollbar = rollbar;

const app = mount(App, {
  target: document.getElementById('app'),
});

export default app;

On Svelte 4, delete the import { mount } from 'svelte'; line and use new App({ target: document.getElementById('app') }) instead of mount. Set VITE_ROLLBAR_ACCESS_TOKEN in .env. process.env does not exist in a Vite build, so read values from import.meta.env.

SvelteKit (src/hooks.client.js):

// src/hooks.client.js
import Rollbar from 'rollbar';
import { PUBLIC_ROLLBAR_ACCESS_TOKEN } from '$env/static/public';

const rollbar = new Rollbar({
  accessToken: PUBLIC_ROLLBAR_ACCESS_TOKEN,
  captureUncaught: true,
  captureUnhandledRejections: true,
  payload: {
    environment: import.meta.env.MODE || 'development',
  },
});

// Expose Rollbar globally for use in Svelte components
if (typeof window !== 'undefined') {
  window.rollbar = rollbar;
}

export const handleError = ({ error, event }) => {
  rollbar.error(error, { event });
};

Set PUBLIC_ROLLBAR_ACCESS_TOKEN in .env. Component code and load functions also run on the server, where window does not exist, so a helper that reports from shared code should call globalThis.window?.rollbar?.error(...).


Testing the Integration

Create a new Svelte component to test error capturing. For example, src/lib/RollbarTest.svelte:

<!-- src/lib/RollbarTest.svelte -->
<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 RollbarTest.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>

Include the RollbarTest component in your main application file. In Vite + Svelte that is src/App.svelte:

<!-- src/App.svelte -->
<script>
  import RollbarTest from './lib/RollbarTest.svelte';
</script>

<main>
  <RollbarTest />
</main>

In SvelteKit, do the same in src/routes/+page.svelte (add a <script> block if the page doesn't have one), importing from $lib/RollbarTest.svelte.

Run and Verify

Start your application:

npm run dev

Open http://localhost:5173 (npm run preview uses http://localhost:4173). You will see buttons to trigger various error types. Clicking these buttons will send errors to Rollbar, and you can verify this integration by checking your Rollbar dashboard.

Session Replay

Session Replay records what the user did before an error. It needs the rollbar/replay build of the SDK. In src/main.js (Vite) or src/hooks.client.js (SvelteKit), change the import to import Rollbar from 'rollbar/replay'; and add a replay block to the config:

import Rollbar from 'rollbar/replay';

const rollbar = new Rollbar({
  // ...your options from above
  replay: {
    enabled: true,
    triggers: [
      {
        type: 'occurrence',
        level: ['warning', 'error', 'critical', 'info'],
        samplingRatio: 1.0,
      },
    ],
  },
});

For triggers, sampling, and privacy options, see the Session Replay documentation.

TypeScript

npm run check needs three small changes. Tell TypeScript about window.rollbar: in SvelteKit, add interface Window { rollbar: import('rollbar').default } inside declare global in src/app.d.ts; in Vite + Svelte, put the same line at the top level of src/vite-env.d.ts, creating the file if your project has none. In src/main.ts, keep the ! in document.getElementById('app')!. Cast the caught error where you report it: /** @type {Error} */ (err).


Additional Resources

Adblocker Notice

Some users report Rollbar issues when using browsers with adblockers, typically shown as the error:

Loading failed for the module with source.

Did this page help you?