Documentation Index Fetch the complete documentation index at: https://mintlify.com/getsentry/sentry-javascript/llms.txt
Use this file to discover all available pages before exploring further.
The Sentry SvelteKit SDK provides comprehensive error monitoring and performance tracking for SvelteKit applications with support for both client and server-side rendering.
Installation
Install with Wizard
The easiest way to set up Sentry in SvelteKit is using the Sentry Wizard: npx @sentry/wizard@latest -i sveltekit
The wizard will:
Install the @sentry/sveltekit package
Create hooks files for client and server
Configure Vite for source maps
Set up automatic error tracking
Manual Installation
npm install @sentry/sveltekit
Version Compatibility
SvelteKit 2.0+ : Fully supported
Svelte 5 : Full support including runes
Vite 4.2+ : Required for proper source map generation
Check the adapter compatibility for your deployment target.
Basic Setup
Client-Side Configuration
Create src/hooks.client.ts:
import { handleErrorWithSentry , init } from '@sentry/sveltekit' ;
import type { HandleClientError } from '@sveltejs/kit' ;
init ({
dsn: 'YOUR_DSN_HERE' ,
tracesSampleRate: 1.0 ,
replaysSessionSampleRate: 0.1 ,
replaysOnErrorSampleRate: 1.0 ,
integrations: [
// Add client-side integrations
],
});
// Custom error handler (optional)
const myErrorHandler : HandleClientError = ({ error , event }) => {
console . error ( 'Client error:' , error );
};
export const handleError = handleErrorWithSentry ( myErrorHandler );
Server-Side Configuration
Create src/hooks.server.ts:
import { handleErrorWithSentry , sentryHandle , init } from '@sentry/sveltekit' ;
import type { HandleServerError , Handle } from '@sveltejs/kit' ;
import { sequence } from '@sveltejs/kit/hooks' ;
init ({
dsn: 'YOUR_DSN_HERE' ,
tracesSampleRate: 1.0 ,
});
// Optional: Custom error handler
const myErrorHandler : HandleServerError = ({ error , event }) => {
console . error ( 'Server error:' , error );
};
export const handleError = handleErrorWithSentry ( myErrorHandler );
// Sentry handle must be first!
export const handle : Handle = sequence (
sentryHandle (),
// Add your other handles here
);
Vite Configuration
Add Sentry to your vite.config.ts:
import { sveltekit } from '@sveltejs/kit/vite' ;
import { sentrySvelteKit } from '@sentry/sveltekit' ;
import { defineConfig } from 'vite' ;
export default defineConfig ({
plugins: [
sentrySvelteKit ({
sourceMapsUploadOptions: {
org: 'your-org' ,
project: 'your-project' ,
authToken: process . env . SENTRY_AUTH_TOKEN ,
},
}),
sveltekit (),
] ,
}) ;
Error Handling
Client-Side Errors
Errors in Svelte components are automatically captured:
< script lang = "ts" >
import * as Sentry from '@sentry/sveltekit' ;
async function handleClick () {
try {
await riskyOperation ();
} catch ( error ) {
Sentry . captureException ( error );
}
}
</ script >
< button on : click = { handleClick } >
Click me
</ button >
Server Load Functions
Errors in load functions are automatically captured:
// src/routes/+page.server.ts
import * as Sentry from '@sentry/sveltekit' ;
import type { PageServerLoad } from './$types' ;
export const load : PageServerLoad = async ({ params }) => {
try {
const data = await fetchData ( params . id );
return { data };
} catch ( error ) {
Sentry . captureException ( error );
throw error ;
}
};
Universal Load Functions
// src/routes/+page.ts
import * as Sentry from '@sentry/sveltekit' ;
import type { PageLoad } from './$types' ;
export const load : PageLoad = async ({ fetch , params }) => {
return await Sentry . startSpan (
{
name: 'load-user-data' ,
op: 'function.load' ,
},
async () => {
const response = await fetch ( `/api/users/ ${ params . id } ` );
return response . json ();
},
);
};
Track server-side form actions:
// src/routes/contact/+page.server.ts
import * as Sentry from '@sentry/sveltekit' ;
import type { Actions } from './$types' ;
export const actions : Actions = {
default : async ({ request }) => {
return await Sentry . startSpan (
{
name: 'contact-form-submission' ,
op: 'form.action' ,
},
async () => {
const data = await request . formData ();
const email = data . get ( 'email' );
try {
await sendEmail ( email );
return { success: true };
} catch ( error ) {
Sentry . captureException ( error );
return { error: 'Failed to send email' };
}
},
);
},
};
API Routes
// src/routes/api/users/+server.ts
import * as Sentry from '@sentry/sveltekit' ;
import { json } from '@sveltejs/kit' ;
import type { RequestHandler } from './$types' ;
export const GET : RequestHandler = async ({ url }) => {
try {
const users = await fetchUsers ();
return json ( users );
} catch ( error ) {
Sentry . captureException ( error );
return json (
{ error: 'Internal Server Error' },
{ status: 500 }
);
}
};
export const POST : RequestHandler = async ({ request }) => {
return await Sentry . startSpan (
{
name: 'create-user' ,
op: 'http.server' ,
},
async () => {
const data = await request . json ();
const user = await createUser ( data );
return json ( user , { status: 201 });
},
);
};
Page Load Tracking
Page loads are automatically tracked with the sentryHandle() function.
Custom Spans
import * as Sentry from '@sentry/sveltekit' ;
export async function complexOperation () {
return await Sentry . startSpan (
{
name: 'complex-operation' ,
op: 'function' ,
attributes: {
userId: '123' ,
operation: 'data-processing' ,
},
},
async () => {
// Your operation logic
const result = await processData ();
return result ;
},
);
}
Database Queries
import * as Sentry from '@sentry/sveltekit' ;
import { db } from '$lib/db' ;
export async function getUser ( id : string ) {
return await Sentry . startSpan (
{
name: 'db.query.user' ,
op: 'db.query' ,
attributes: {
'db.system' : 'postgresql' ,
'db.operation' : 'SELECT' ,
},
},
async () => {
return await db . user . findUnique ({ where: { id } });
},
);
}
Context and User Information
Setting User Context
// src/hooks.server.ts
import * as Sentry from '@sentry/sveltekit' ;
import type { Handle } from '@sveltejs/kit' ;
import { sequence } from '@sveltejs/kit/hooks' ;
const authHandle : Handle = async ({ event , resolve }) => {
const user = await getUser ( event . cookies );
if ( user ) {
Sentry . setUser ({
id: user . id ,
email: user . email ,
username: user . username ,
});
}
return resolve ( event );
};
export const handle = sequence (
sentryHandle (),
authHandle
);
Adding Context
import * as Sentry from '@sentry/sveltekit' ;
Sentry . setContext ( 'order' , {
id: 'ORDER-123' ,
total: 99.99 ,
items: 3 ,
});
Sentry . setTag ( 'payment_method' , 'credit_card' );
Sentry . setTag ( 'region' , 'us-west' );
Session Replay
Enable session replay for debugging:
// src/hooks.client.ts
import { init , replayIntegration } from '@sentry/sveltekit' ;
init ({
dsn: 'YOUR_DSN_HERE' ,
integrations: [
replayIntegration ({
maskAllText: true ,
blockAllMedia: true ,
}),
],
replaysSessionSampleRate: 0.1 ,
replaysOnErrorSampleRate: 1.0 ,
});
Adapter-Specific Configuration
Vercel
Netlify
Cloudflare Pages
Node
No additional configuration needed. Works out of the box.
// svelte.config.js
import adapter from '@sveltejs/adapter-netlify' ;
export default {
kit: {
adapter: adapter ({
edge: false , // Set to true for edge functions
}),
} ,
} ;
// For Cloudflare Pages, use the cloudflare adapter
import adapter from '@sveltejs/adapter-cloudflare' ;
export default {
kit: {
adapter: adapter (),
} ,
} ;
// svelte.config.js
import adapter from '@sveltejs/adapter-node' ;
export default {
kit: {
adapter: adapter (),
} ,
} ;
Environment Variables
Add to your .env file:
# Public (client-side)
PUBLIC_SENTRY_DSN = your-dsn-here
# Private (server-side only)
SENTRY_AUTH_TOKEN = your-auth-token
SENTRY_ORG = your-org
SENTRY_PROJECT = your-project
Best Practices
Separate Hooks Always use separate hooks files for client and server initialization.
Handle Order Place sentryHandle() first in the sequence to catch all errors.
Source Maps Configure Vite plugin for automatic source map upload.
User Context Set user context in a custom handle after authentication.
Troubleshooting
Ensure:
Both hooks.client.ts and hooks.server.ts are properly configured
sentryHandle() is called in the handle sequence
DSN is correctly set in both client and server configs
Verify:
Vite plugin is configured with correct auth token
Source maps are generated during build
org and project values are correct
Next Steps
Load Functions Track data loading performance
Form Actions Monitor form submissions
Session Replay Debug with session recordings
Adapters Configure for your deployment platform