Manual Setup

Learn how to manually set up Sentry in your SvelteKit app and capture your first errors.

You need:

  • A Sentry account and project
  • Your application up and running
  • SvelteKit version 2.0.0+
  • Vite version 4.2+
Notes on SvelteKit adapter compatibility

The SvelteKit Sentry SDK is designed to work out of the box with several SvelteKit adapters and their underlying server runtimes. Here's an overview of the current support:

  • Fully supported Node.js runtimes
  • Supported non-Node.js runtimes
  • Currently not supported
    • Non-Node.js server runtimes, such as Vercel's edge runtime, are not yet supported.
  • Other adapters
    • Other SvelteKit adapters might work, but they're not currently officially supported. We're looking into extending first-class support to more adapters in the future.

Choose the features you want to configure, and this guide will show you how:

Want to learn more about these features?
  • Issues (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and unhandled rejections. If you have something that looks like an exception, Sentry can capture it.
  • Tracing: Track software performance while seeing the impact of errors across multiple systems. For example, distributed tracing allows you to follow a request from the frontend to the backend and back.
  • Session Replay: Get to the root cause of an issue faster by viewing a video-like reproduction of what was happening in the user's browser before, during, and after the problem.

Run the command for your preferred package manager to add the Sentry SDK to your application:

Copied
npm install @sentry/sveltekit --save

If you're updating your Sentry SDK to the latest version, check out our migration guide to learn more about breaking changes.

You need to initialize and configure the Sentry SDK in three places: the client side, the server side, and your Vite config.

Create a client hooks file src/hooks.client.(js|ts) in the src folder of your project if you don't have one already. In this file, import and initialize the Sentry SDK and add the handleErrorWithSentry function to the handleError hook.

hooks.client.(js|ts)
Copied
import * as Sentry from "@sentry/sveltekit";
Sentry.init({ dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", // Adds request headers and IP for users, for more info visit: // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#sendDefaultPii sendDefaultPii: true, // performance // Set tracesSampleRate to 1.0 to capture 100% // of transactions for tracing. // We recommend adjusting this value in production // Learn more at // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate tracesSampleRate: 1.0, // performance // session-replay integrations: [Sentry.replayIntegration()], // Capture Replay for 10% of all sessions, // plus for 100% of sessions with an error // Learn more at // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration replaysSessionSampleRate: 0.1, replaysOnErrorSampleRate: 1.0, // session-replay });
const myErrorHandler = ({ error, event }) => { console.error("An error occurred on the client side:", error, event); };
export const handleError = Sentry.handleErrorWithSentry(myErrorHandler);
// or alternatively, if you don't have a custom error handler: // export const handleError = handleErrorWithSentry();

Create a server hooks file src/hooks.server.(js|ts) in the src folder of your project if you don't have one already. In this file, import and initialize the Sentry SDK and add the handleErrorWithSentry function to the handleError hook and the Sentry request handler to the handle hook.

hooks.server.(js|ts)
Copied
import * as Sentry from "@sentry/sveltekit";
Sentry.init({ dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", // Adds request headers and IP for users, for more info visit: // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#sendDefaultPii sendDefaultPii: true, // performance // Set tracesSampleRate to 1.0 to capture 100% // of transactions for tracing. // We recommend adjusting this value in production // Learn more at // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate tracesSampleRate: 1.0, // performance });
const myErrorHandler = ({ error, event }) => { console.error("An error occurred on the server side:", error, event); };
export const handleError = Sentry.handleErrorWithSentry(myErrorHandler);
// or alternatively, if you don't have a custom error handler: // export const handleError = handleErrorWithSentry();
export const handle = Sentry.sentryHandle();
// Or use `sequence` if you're using your own handler(s): // export const handle = sequence(Sentry.sentryHandle(), yourHandler());
Having CSP issues with `fetch` instrumentation on older SvelteKit versions?

If you're using SvelteKit versions older than 2.16.0 and encounter Content Security Policy (CSP) errors related to Sentry's fetch instrumentation, you can find support in our Troubleshooting guide.

Add the sentrySvelteKit plugin before sveltekit in your vite.config.(js|ts) file to automatically upload source maps to Sentry and instrument load functions for tracing if it's configured.

vite.config.(js|ts)
Copied
import { sveltekit } from "@sveltejs/kit/vite";
import { sentrySvelteKit } from "@sentry/sveltekit";
import { defineConfig } from "vite"; export default defineConfig({
plugins: [sentrySvelteKit(), sveltekit()],
// ... rest of your Vite config });

To upload source maps for clear error stack traces, create an environment variable for your auth token and add your Sentry organization, and project slug in your vite.config.(js|ts) file:

vite.config.(js|ts)
Copied
import { sveltekit } from "@sveltejs/kit/vite";
import { sentrySvelteKit } from "@sentry/sveltekit";

export default {
  plugins: [
sentrySvelteKit({ sourceMapsUploadOptions: { org: "example-org", project: "example-project", authToken: process.env.SENTRY_AUTH_TOKEN,
}, }), sveltekit(), ], // ... rest of your Vite config };

To keep your auth token secure, always store it in an environment variable instead of directly in your files:

.env
Copied
SENTRY_AUTH_TOKEN=sntrys_YOUR_TOKEN_HERE

sentrySvelteKit tries to auto-detect your SvelteKit adapter to configure source maps upload correctly. If you're using an unsupported adapter or the wrong one is detected, set it using the adapter option:

vite.config.(js|ts)
Copied
import { sveltekit } from "@sveltejs/kit/vite";
import { sentrySvelteKit } from "@sentry/sveltekit";

export default {
  plugins: [
    sentrySvelteKit({
adapter: "vercel",
}), sveltekit(), ], // ... rest of your Vite config };

The points explain additional optional configuration or more in-depth customization of your Sentry SvelteKit SDK setup.

The SDK primarily uses SvelteKit's hooks to collect error and performance data. However, SvelteKit doesn't yet offer a hook for universal or server-only load function calls. Therefore, the SDK uses a Vite plugin to auto-instrument load functions so that you don't have to add a Sentry wrapper to each function manually.

Auto-instrumentation is enabled by default when you add the sentrySvelteKit() function call to your vite.config.(js|ts). However, you can customize the behavior, or disable it entirely. If you disable it you can still manually wrap specific load functions with the withSentry function.

By passing the autoInstrument option to sentrySvelteKit you can disable auto-instrumentation entirely, or customize which load functions should be instrumented:

vite.config.(js|ts)
Copied
import { sveltekit } from "@sveltejs/kit/vite";
import { sentrySvelteKit } from "@sentry/sveltekit";

export default {
  plugins: [
    sentrySvelteKit({
autoInstrument: { load: true, serverLoad: false, },
}), sveltekit(), ], // ... rest of your Vite config };

If you set the autoInstrument option to false, the SDK won't auto-instrument any load functions. You can still manually instrument specific load functions.

vite.config.(js|ts)
Copied
import { sveltekit } from '@sveltejs/kit/vite';
import { sentrySvelteKit } from '@sentry/sveltekit';

export default {
  plugins: [
    sentrySvelteKit({
autoInstrument: false;
}), sveltekit(), ], // ... rest of your Vite config };

Instead or in addition to Auto Instrumentation, you can manually instrument certain SvelteKit-specific features with the SDK:

SvelteKit's universal and server load functions are instrumented automatically by default. If you don't want to use load auto-instrumentation, you can disable it, and manually instrument specific load functions with the SDK's load function wrappers.

Use the wrapLoadWithSentry function to wrap universal load functions declared in +page.(js|ts) or +layout.(js|ts)

+(page|layout).(js|ts)
Copied
import { wrapLoadWithSentry } from "@sentry/sveltekit";
export const load = wrapLoadWithSentry(({ fetch }) => {
const res = await fetch("/api/data"); const data = await res.json(); return { data }; });

Or use the wrapServerLoadWithSentry function to wrap server-only load functions declared in +page.server.(js|ts) or +layout.server.(js|ts)

+(page|layout).server.(js|ts)
Copied
import { wrapServerLoadWithSentry } from "@sentry/sveltekit";
export const load = wrapServerLoadWithSentry(({ fetch }) => {
const res = await fetch("/api/data"); const data = await res.json(); return { data }; });

You can also manually instrument server (API) routes with the SDK. This is useful if you have custom server routes that you want to trace or if you want to capture error() calls within your server routes:

+server.(js|ts)
Copied
import { wrapServerRouteWithSentry } from "@sentry/sveltekit";
export const GET = wrapServerRouteWithSentry(async () => {
// your endpoint logic return new Response("Hello World"); });

If you're deploying your application to Cloudflare Pages, you need to adjust your server-side setup. Follow this guide to configure Sentry for Cloudflare.

You can prevent ad blockers from blocking Sentry events using tunneling. Use the tunnel option to add an API endpoint in your application that forwards Sentry events to Sentry servers.

To enable tunneling, update Sentry.init in your hooks.client.(js|ts) file with the following option:

hooks.client.(js|ts)
Copied
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",,
  tunnel: "/tunnel",
});

This will send all events to the tunnel endpoint. However, the events need to be parsed and redirected to Sentry, so you'll need to do additional configuration on the server. You can find a detailed explanation on how to do this on our Troubleshooting page.

Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.

To verify that Sentry captures errors and creates issues in your Sentry project, create a test page, for example, at src/routes/sentry-example/+page.svelte with a button that throws an error when clicked:

+page.svelte
Copied
<script>
  function throwTestError() {
    throw new Error("Sentry Example Frontend Error");
  }
</script>

<button type="button" onclick="{throwTestError}">Throw error</button>

To test tracing, create a test API route like src/routes/sentry-example/+server.(js|ts):

+server.(js|ts)
Copied
export const GET = async () => {
  throw new Error("Sentry Example API Route Error");
};

Next, update your test button to call this route and throw an error if the response isn't ok:

+page.svelte
Copied
<script>
  import * as Sentry from "@sentry/sveltekit";

  function throwTestError() {
    Sentry.startSpan(
      {
        name: "Example Frontend Span",
        op: "test",
      },
      async () => {
        const res = await fetch("/sentry-example");
        if (!res.ok) {
          throw new Error("Sentry Example Frontend Error");
        }
      },
    );
  }
</script>

<button type="button" onclick="{throwTestError}">
  Throw error with trace
</button>

Open the page sentry-example in a browser and click the button to trigger two errors:

  • a frontend error
  • an error within the API route

Additionally, this starts a trace to measure the time it takes for the API request to complete.

Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).

Need help locating the captured errors in your Sentry project?
  1. Open the Issues page and select an error from the issues list to view the full details and context of this error. For an interactive UI walkthrough, click here.
  2. Open the Traces page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, click here.
  3. Open the Replays page and select an entry from the list to get a detailed view where you can replay the interaction and get more information to help you troubleshoot.

At this point, you should have integrated Sentry into your SvelteKit application and should already be sending data to your Sentry project.

Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:

Are you having problems setting up the SDK?
Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").