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

# SvelteKit SDK

> Error monitoring and performance tracking for SvelteKit applications

The Sentry SvelteKit SDK provides comprehensive error monitoring and performance tracking for SvelteKit applications with support for both client and server-side rendering.

## Installation

<Steps>
  <Step title="Install with Wizard">
    The easiest way to set up Sentry in SvelteKit is using the Sentry Wizard:

    ```bash theme={null}
    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
  </Step>

  <Step title="Manual Installation">
    <CodeGroup>
      ```bash npm theme={null}
      npm install @sentry/sveltekit
      ```

      ```bash yarn theme={null}
      yarn add @sentry/sveltekit
      ```

      ```bash pnpm theme={null}
      pnpm add @sentry/sveltekit
      ```
    </CodeGroup>
  </Step>
</Steps>

## 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](https://docs.sentry.io/platforms/javascript/guides/sveltekit/#prerequisites) for your deployment target.

## Basic Setup

### Client-Side Configuration

Create `src/hooks.client.ts`:

```typescript theme={null}
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`:

```typescript theme={null}
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`:

```typescript theme={null}
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:

```svelte theme={null}
<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:

```typescript theme={null}
// 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

```typescript theme={null}
// 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();
    },
  );
};
```

## Form Actions

Track server-side form actions:

```typescript theme={null}
// 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

```typescript theme={null}
// 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 });
    },
  );
};
```

## Performance Monitoring

### Page Load Tracking

Page loads are automatically tracked with the `sentryHandle()` function.

### Custom Spans

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
// 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

```typescript theme={null}
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:

```typescript theme={null}
// 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

<Tabs>
  <Tab title="Vercel">
    No additional configuration needed. Works out of the box.
  </Tab>

  <Tab title="Netlify">
    ```javascript theme={null}
    // svelte.config.js
    import adapter from '@sveltejs/adapter-netlify';

    export default {
      kit: {
        adapter: adapter({
          edge: false, // Set to true for edge functions
        }),
      },
    };
    ```
  </Tab>

  <Tab title="Cloudflare Pages">
    ```typescript theme={null}
    // For Cloudflare Pages, use the cloudflare adapter
    import adapter from '@sveltejs/adapter-cloudflare';

    export default {
      kit: {
        adapter: adapter(),
      },
    };
    ```
  </Tab>

  <Tab title="Node">
    ```javascript theme={null}
    // svelte.config.js
    import adapter from '@sveltejs/adapter-node';

    export default {
      kit: {
        adapter: adapter(),
      },
    };
    ```
  </Tab>
</Tabs>

## Environment Variables

Add to your `.env` file:

```bash theme={null}
# 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

<CardGroup cols={2}>
  <Card title="Separate Hooks" icon="split">
    Always use separate hooks files for client and server initialization.
  </Card>

  <Card title="Handle Order" icon="list-ol">
    Place sentryHandle() first in the sequence to catch all errors.
  </Card>

  <Card title="Source Maps" icon="map">
    Configure Vite plugin for automatic source map upload.
  </Card>

  <Card title="User Context" icon="user">
    Set user context in a custom handle after authentication.
  </Card>
</CardGroup>

## Troubleshooting

<Accordion title="Errors Not Captured">
  Ensure:

  1. Both `hooks.client.ts` and `hooks.server.ts` are properly configured
  2. `sentryHandle()` is called in the handle sequence
  3. DSN is correctly set in both client and server configs
</Accordion>

<Accordion title="Source Maps Not Working">
  Verify:

  1. Vite plugin is configured with correct auth token
  2. Source maps are generated during build
  3. `org` and `project` values are correct
</Accordion>

## Next Steps

<CardGroup cols={2}>
  <Card title="Load Functions" icon="download" href="/load-functions">
    Track data loading performance
  </Card>

  <Card title="Form Actions" icon="file-signature" href="/form-actions">
    Monitor form submissions
  </Card>

  <Card title="Session Replay" icon="video" href="/session-replay">
    Debug with session recordings
  </Card>

  <Card title="Adapters" icon="plug" href="/adapters">
    Configure for your deployment platform
  </Card>
</CardGroup>
