Cloudflare Sveltekit Framework Guide

Learn how to add Cloudflare instrumentation to your SvelteKit app.

If you're running your SvelteKit app on Cloudflare Pages, you can use the Sentry SvelteKit SDK in combination with the Sentry Cloudflare SDK to add Sentry instrumentation.

First, install the Sentry SvelteKit SDK in your application. We recommend using the Sentry wizard to automatically install the SDK:

Copied
npx @sentry/wizard@latest -i sveltekit

If the setup through the wizard doesn't work for you, you can also set up the SvelteKit SDK manually.

After installing the Sentry SvelteKit SDK, you can move on to setting up the Cloudflare SDK. First, install the SDK with your package manager:

Copied
npm install @sentry/cloudflare --save

To use the SDK, you'll need to set either the nodejs_compat or nodejs_als compatibility flags in your wrangler.toml. This is because the SDK needs access to the AsyncLocalStorage API to work correctly.

wrangler.toml
Copied
compatibility_flags = ["nodejs_compat"]
# compatibility_flags = ["nodejs_als"]

To use this SDK, update your src/hooks.server.(ts|js) file to use the Sentry.wrapRequestHandler method from the Sentry Cloudflare SDK and remove the Sentry.init call from @sentry/sveltekit.

hooks.server.(ts|js)
Copied
 import { sequence } from "@sveltejs/kit/hooks";
 import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit";
-import * as Sentry from '@sentry/sveltekit';
+import * as Sentry from "@sentry/cloudflare";

-Sentry.init({
-  dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
-  tracesSampleRate: 1.0,
-
-  // uncomment the line below to enable Spotlight (https://spotlightjs.com)
-  // spotlight: import.meta.env.DEV,
-});
-
+const handleInitSentry = ({ event, resolve }) => {
+  return event.platform
+    ? Sentry.wrapRequestHandler(
+        {
+          options: {
+            dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
+            tracesSampleRate: 1.0,
+          },
+          request: event.request,
+          context: event.platform.ctx,
+        },
+        () => resolve(event)
+      )
+    : resolve(event);
+};
-// If you have custom handlers, make sure to place them after `sentryHandle()` in the `sequence` function.
-export const handle = sequence(sentryHandle());
+export const handle = sequence(handleInitSentry, sentryHandle());

export const handleError = handleErrorWithSentry(myErrorHandler);

If you need to use environmental variables, you can access them using event.platform.env.

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