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());

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 });

By default, sentrySvelteKit() will add an instance of the Sentry Vite Plugin, to upload source maps for both server and client builds. This means that when you run a production build (npm run build), source maps will be generated and uploaded to Sentry, so that you get readable stack traces in your Sentry issues.

However, you still need to specify your Sentry auth token as well as your org and project slugs. There are two ways to set them.

You can set them as environment variables, for example in a .env file:

  • SENTRY_ORG your Sentry org slug
  • SENTRY_PROJECT your Sentry project slug
  • SENTRY_AUTH_TOKEN your Sentry auth token (can be obtained from the Organization Token Settings)
  • SENTRY_URL your Sentry instance URL. This is only required if you use your own Sentry instance (as opposed to https://sentry.io).

Or, you can set them by passing a sourceMapsUploadOptions object to sentrySvelteKit, as seen in the example below. All available options are documented at the Sentry Vite plugin repo.

.env
Copied
SENTRY_AUTH_TOKEN=sntrys_YOUR_TOKEN_HERE

Using the sourceMapsUploadOptions object is useful if the default source maps upload doesn't work out of the box, for instance, if you have a customized build setup or if you're using the SDK with a SvelteKit adapter other than the supported adapters.

By default, sentrySvelteKit will try to detect your SvelteKit adapter to configure source maps upload correctly. If you're not using one of the supported adapters or the wrong one is detected, you can override the adapter detection by passing the adapter option to sentrySvelteKit:

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 };

You can disable automatic source maps upload in your Vite config:

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

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

If you disable automatic source maps upload, you must explicitly set a release value in your Sentry.init() configs. You can also skip the sentry-cli configuration step below.

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 };

If you're using a SvelteKit version older than sveltejs/kit@2.16.0, The Sentry SDK injects an inline <script> tag into the HTML response of the server. This script proxies all client-side fetch calls, so that fetch calls inside your load functions are captured by the SDK. However, if you configured CSP rules to block inline fetch scripts by default, this script will be blocked by the browser.

You have multiple options to solve this CSP issue:

The easiest option is to update @sveltejs/kit to at least version 2.16.0 (or newer). The SDK will not inject the fetch proxy script as it's no longer necessary.

To enable the script, add an exception for the sentryHandle script by adding the hash of the script to your CSP script source rules.

If your CSP is defined in svelte.config.js, you can add the hash to the csp.directives.script-src array:

svelte.config.js
Copied
const config = {
  kit: {
    csp: {
      directives: {
"script-src": [ "sha256-y2WkUILyE4eycy7x+pC0z99aZjTZlWfVwgUAfNc1sY8=", ], // + rest of your values
}, }, }, };

For external CSP configurations, add the following hash to your script-src directive:

Copied
'sha256-y2WkUILyE4eycy7x+pC0z99aZjTZlWfVwgUAfNc1sY8='

We will not make changes to this script any time soon, so the hash will stay consistent.

If you don't want to inject the script responsible for instrumenting client-side fetch calls, you can disable injection by passing injectFetchProxyScript: false to sentryHandle:

hooks.server.(js|ts)
Copied
export const handle = sentryHandle({ injectFetchProxyScript: false });

Note that if you disable the fetch proxy script, the SDK will not be able to capture spans for fetch calls made by SvelteKit when your route has a server load function. This also means that potential spans created on the server for these fetch calls will not be connected to the client-side trace.

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.

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