Manual Setup

Learn how to set up the SDK manually.

If you can't (or prefer not to) run the automatic setup, you can follow the instructions below to configure the Sentry SvelteKit SDK in your application. This guide is also useful to adjust the pre-set configuration if you used the installation wizard for automatic setup.

Copied
npm install --save @sentry/sveltekit

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

  1. If you don't already have a client hooks file, create a new one in src/hooks.client.(js|ts).

  2. At the top of your client hooks file, initialize the Sentry SDK as shown in the snippet below. See the Basic Options page to view other SDK configuration options.

hooks.client.js
Copied
import * as Sentry from '@sentry/sveltekit';

Sentry.init({
  dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,

  // Optional: Initialize Session Replay:
  integrations: [Sentry.replayIntegration()],
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});
  1. Add the handleErrorWithSentry function to the handleError hook:
hooks.client.js
Copied
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();

  1. If you don't already have a server hooks file, create a new one in src/hooks.server.(js|ts).

  2. At the top of your server hooks file, initialize the Sentry SDK as shown in the snippet below. See the Basic Options page to view other SDK configuration options.

hooks.server.js
Copied
import * as Sentry from '@sentry/sveltekit';

Sentry.init({
  dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
});
  1. Add the handleErrorWithSentry function to the handleError hook:
hooks.server.js
Copied
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();
  1. Add the Sentry request handler to the handle hook. If you're already using your own handler(s), use SvelteKit's sequence function to add the Sentry handler before your handler(s):
hooks.server.js
Copied
export const handle = Sentry.sentryHandle();
// Or use `sequence`:
// export const handle = sequence(Sentry.sentryHandle(), yourHandler());

Add the sentrySvelteKit plugins to your vite.config.(js|ts) file so the Sentry SDK can apply build-time features. Make sure that it is added before the sveltekit plugin:

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

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

The sentrySvelteKit() function adds Vite plugins to your Vite config to:

  • Automatically upload source maps to Sentry
  • Automatically instrument load functions for performance monitoring

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
vite.config.js
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,
        sourcemaps: {
          assets: ['./build/*/**/*'],
          ignore: ['**/build/client/**/*'],
          filesToDeleteAfterUpload: ['./build/**/*.map'],
        },
      },
    }),
    sveltekit(),
  ],
  // ... rest of your Vite config
};

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

The SDK will only auto-instrument load functions in +page or +layout files that don't contain any Sentry code. If you have custom Sentry code in these files, you'll have to manually add the Sentry wrapper to your load functions.

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

vite.config.js
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
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 don't want to use auto-instrumentation, you can also 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
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
Copied
import { wrapServerLoadWithSentry } from "@sentry/sveltekit";

export const load = wrapServerLoadWithSentry(({ fetch }) => {
  const res = await fetch("/api/data");
  const data = await res.json();
  return { data };
});

Available since version 7.91.0

The sentryHandle function you added to your handle hook in hooks.server.ts during server-side setup injects a small inline <script> tag into the HTML response of the server. This script attempts to proxy 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. To enable the script, you need to add an exception for the sentryHandle script:

First, specify your nonce in the fetchProxyScriptNonce option in your sentryHandle call:

hooks.server.ts
Copied
// Add the nonce to the <script> tag:
export const handle = sentryHandle({fetchProxyScriptNonce: '<your-nonce>'});

Then, adjust your SvelteKit CSP configuration:

Copied
const config = {
  kit: {
    csp: {
      directives: {
        'script-src': ['nonce-<your-nonce>'],
      },
    },
  },
};

If you do not want to inject the script responsible for instrumenting client-side load calls, you can disable injection by passing injectFetchProxyScript: false to sentryHandle:

hooks.server.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 in your load functions on the client. This also means that potential spans created on the server for these fetch calls will not be connected to the client-side trace.

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