SvelteKit on Cloudflare
Learn how to instrument your SvelteKit app on Cloudflare Workers and Pages and capture your first errors with Sentry.
You need:
- A Sentry account and project
- Your application up and running
- SvelteKit version
2.0.0+
(we recommend2.31.0
or higher for best support) - Vite version
4.2
or newer
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 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.
src/hooks.client.(js|ts)
import * as Sentry from "@sentry/sveltekit";
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0example-org / example-project",
// 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
integrations: [
// session-replay
Sentry.replayIntegration(),
// session-replay
// user-feedback
Sentry.feedbackIntegration({
// Additional SDK configuration goes in here, for example:
colorScheme: "system",
}),
// user-feedback
],
// session-replay
// 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
// logs
// Enable logs to be sent to Sentry
enableLogs: true,
// logs
});
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();
Requires SvelteKit 2.31.0
or higher and @sentry/sveltekit
10.8.0
or higher.
Configure server-side instrumentation and tracing in your svelte.config.js
file:
svelte.config.js
const config = {
kit: {
experimental: {
instrumentation: {
server: true,
},
// performance
tracing: {
server: true,
},
// performance
},
},
};
export default config;
Create a server hooks file src/hooks.server.(js|ts)
in 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 Sentry's Cloudflare request handler to the handle
hook.
src/hooks.server.(js|ts)
import {
handleErrorWithSentry,
sentryHandle,
initCloudflareSentryHandle,
} from "@sentry/sveltekit";
import { sequence } from "@sveltejs/kit/hooks";
import * as Sentry from "@sentry/sveltekit";
export const handle = sequence(
initCloudflareSentryHandle({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0example-org / example-project",
// 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
// logs
// Enable logs to be sent to Sentry
enableLogs: true,
// logs
}),
sentryHandle(),
);
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();
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
});
Since the SDK needs access to the AsyncLocalStorage
API, you need to set either the nodejs_compat
or nodejs_als
compatibility flags in your wrangler.(jsonc|toml)
configuration file:
wrangler.jsonc
{
"compatibility_flags": [
"nodejs_als",
// "nodejs_compat"
],
}
Additionally, add the CF_VERSION_METADATA
binding in the same file:
wrangler.jsonc
{
// ...
"version_metadata": {
"binding": "CF_VERSION_METADATA",
},
}
To upload source maps for clear error stack traces, add your Sentry auth token, 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",
// store your auth token in an environment variable
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
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
- Learn how to manually instrument SvelteKit-specific features
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").