Manual Setup
Learn how to manually set up Sentry in your SvelteKit app and capture your first errors.
For the fastest setup, we recommend using the wizard installer.
You need:
- A Sentry account and project
- Your application up and running
- SvelteKit version
2.0.0
+ - Vite version
4.2
+
Choose the features you want to configure, and this guide will show you how:
Run the command for your preferred package manager to add the Sentry SDK to your application:
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)
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)
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)
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)
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
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)
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.
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|ts)
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)
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)
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)
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 8.25.0
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)
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)
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
<script>
function throwTestError() {
throw new Error("Sentry Example Frontend Error");
}
</script>
<button type="button" onclick="{throwTestError}">Throw error</button>
Open the page sentry-example
in a browser and click the button to trigger a frontend error.
Important
Errors triggered from within your browser's developer tools (like the browser console) are sandboxed, so they will not trigger Sentry's error monitoring.
To test tracing, create a test API route like src/routes/sentry-example/+server.(js|ts)
:
+server.(js|ts)
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
<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).
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:
- Learn how to manually capture errors
- Continue to customize your configuration
- Get familiar with Sentry's product features like tracing, insights, and alerts
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").