sentry-svelte-sdk

작성자: sentry

Svelte 및 SvelteKit을 위한 완전한 Sentry SDK 설정입니다. "Svelte에 Sentry 추가", "SvelteKit에 Sentry 추가", "@sentry/sveltekit 설치" 또는 구성 요청 시 사용하세요.

npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-svelte-sdk

All Skills > SDK Setup > Svelte SDK

Sentry Svelte SDK

Opinionated wizard that scans your project and guides you through complete Sentry setup for Svelte and SvelteKit.

Invoke This Skill When

  • User asks to "add Sentry to Svelte" or "set up Sentry" in a Svelte/SvelteKit app
  • User wants error monitoring, tracing, session replay, or logging in Svelte or SvelteKit
  • User mentions @sentry/svelte, @sentry/sveltekit, or Sentry SDK for Svelte

Note: SDK versions and APIs below reflect current Sentry docs at time of writing (@sentry/sveltekit ≥10.8.0, SvelteKit ≥2.31.0). Always verify against docs.sentry.io/platforms/javascript/guides/sveltekit/ before implementing.


Phase 1: Detect

Run these commands to understand the project before making any recommendations:

# Detect framework type
cat package.json | grep -E '"svelte"|"@sveltejs/kit"|"@sentry/svelte"|"@sentry/sveltekit"'

# Check for SvelteKit indicators
ls svelte.config.js svelte.config.ts vite.config.ts vite.config.js 2>/dev/null

# Check SvelteKit version (determines which setup pattern to use)
cat package.json | grep '"@sveltejs/kit"'

# Check if Sentry is already installed
cat package.json | grep '"@sentry/'

# Check existing hook files
ls src/hooks.client.ts src/hooks.client.js src/hooks.server.ts src/hooks.server.js \
   src/instrumentation.server.ts 2>/dev/null

# Detect logging libraries (Node side)
cat package.json | grep -E '"pino"|"winston"|"consola"'

# Detect if there's a backend (Go, Python, Ruby, etc.) in adjacent directories
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3

What to determine:

QuestionImpact
@sveltejs/kit in package.json?SvelteKit path vs. plain Svelte path
SvelteKit ≥2.31.0?Modern (instrumentation.server.ts) vs. legacy setup
@sentry/sveltekit already present?Skip install, go straight to feature config
vite.config.ts present?Source map upload via Vite plugin available
Backend directory found?Trigger Phase 4 cross-link suggestion

Phase 2: Recommend

Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:

Recommended (core coverage):

  • Error Monitoring — always; auto-captures unhandled errors on client and server
  • Tracing — SvelteKit has both client-side navigation spans and server-side request spans; always recommend
  • Session Replay — recommended for user-facing SvelteKit apps (client-side only)

Optional (enhanced observability):

  • Logging — structured logs via Sentry.logger.*; recommend when app uses server-side logging or needs log-to-trace correlation

Recommendation logic:

FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingAlways for SvelteKit (client + server); for plain Svelte when calling APIs
Session ReplayUser-facing app, login flows, or checkout pages present
LoggingApp already uses server-side logging, or structured log search is needed

Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add structured Logging?"


Phase 3: Guide

Determine Setup Path

Your projectPackageSetup complexity
SvelteKit (≥2.31.0)@sentry/sveltekit5 files to create/modify
SvelteKit (<2.31.0)@sentry/sveltekit3 files (init in hooks.server.ts)
Plain Svelte (no @sveltejs/kit)@sentry/svelteSingle entry point

Path A: SvelteKit (Recommended — Modern, ≥2.31.0)

Option 1: Wizard (Recommended)

You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:

npx @sentry/wizard@latest -i sveltekit

It handles login, org/project selection, SDK installation, client/server hooks, Vite plugin config, source map upload, and adds a /sentry-example-page.

Once it finishes, come back and skip to Verification.

If the user skips the wizard, proceed with Option 2 (Manual Setup) below.

Option 2: Manual Setup

Step 1 — Install

npm install @sentry/sveltekit --save

Step 2 — svelte.config.js — Enable instrumentation

import adapter from "@sveltejs/adapter-auto";

const config = {
  kit: {
    adapter: adapter(),
    experimental: {
      instrumentation: { server: true },
      tracing: { server: true },
    },
  },
};

export default config;

Step 3 — src/instrumentation.server.ts — Server-side init (runs once at startup)

import * as Sentry from "@sentry/sveltekit";

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.SENTRY_ENVIRONMENT,
  release: process.env.SENTRY_RELEASE,

  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },
  tracesSampleRate: 1.0,    // lower to 0.1–0.2 in production
  enableLogs: true,
});

Step 4 — src/hooks.client.ts — Client-side init

import * as Sentry from "@sentry/sveltekit";

Sentry.init({
  dsn: import.meta.env.PUBLIC_SENTRY_DSN ?? import.meta.env.VITE_SENTRY_DSN,
  environment: import.meta.env.MODE,

  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },
  tracesSampleRate: 1.0,

  integrations: [
    Sentry.replayIntegration({
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],

  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  enableLogs: true,
});

export const handleError = Sentry.handleErrorWithSentry();

Step 5 — src/hooks.server.ts — Server hooks (no init here in modern setup)

import * as Sentry from "@sentry/sveltekit";
import { sequence } from "@sveltejs/kit/hooks";

export const handleError = Sentry.handleErrorWithSentry();

// sentryHandle() instruments incoming requests and creates root spans
export const handle = Sentry.sentryHandle();

// If you have other handle functions, compose with sequence():
// export const handle = sequence(Sentry.sentryHandle(), myAuthHandle);

Step 6 — vite.config.ts — Source maps (requires SENTRY_AUTH_TOKEN)

import { sveltekit } from "@sveltejs/kit/vite";
import { sentrySvelteKit } from "@sentry/sveltekit";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    // sentrySvelteKit MUST come before sveltekit()
    sentrySvelteKit({
      org: process.env.SENTRY_ORG,
      project: process.env.SENTRY_PROJECT,
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
    sveltekit(),
  ],
});

Add to .env (never commit):

SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slug

Path B: SvelteKit Legacy (<2.31.0 or @sentry/sveltekit <10.8.0)

Skip instrumentation.server.ts and svelte.config.js changes. Instead, put Sentry.init() directly in hooks.server.ts:

// src/hooks.server.ts (legacy — init goes here)
import * as Sentry from "@sentry/sveltekit";

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 1.0,
  enableLogs: true,
});

export const handleError = Sentry.handleErrorWithSentry();
export const handle = Sentry.sentryHandle();

hooks.client.ts and vite.config.ts are identical to the modern path.


Path C: Plain Svelte (no SvelteKit)

Install:

npm install @sentry/svelte --save

Configure in entry point (src/main.ts or src/main.js) before mounting the app:

import * as Sentry from "@sentry/svelte";
import App from "./App.svelte";

Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN,
  environment: import.meta.env.MODE,

  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },

  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration({
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],

  tracesSampleRate: 1.0,
  tracePropagationTargets: ["localhost", /^https:\/\/yourapi\.io/],
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  enableLogs: true,
});

const app = new App({ target: document.getElementById("app")! });
export default app;

Optional: Svelte component tracking (auto-injects tracking into all components):

// svelte.config.js
import { withSentryConfig } from "@sentry/svelte";

export default withSentryConfig(
  { compilerOptions: {} },
  { componentTracking: { trackComponents: true } }
);

For Each Agreed Feature

Walk through features one at a time. Load the reference file, follow its steps, then verify before moving on:

FeatureReferenceLoad when...
Error Monitoring${SKILL_ROOT}/references/error-monitoring.mdAlways (baseline)
Tracing${SKILL_ROOT}/references/tracing.mdAPI calls / distributed tracing needed
Session Replay${SKILL_ROOT}/references/session-replay.mdUser-facing app
Logging${SKILL_ROOT}/references/logging.mdStructured logs / log-to-trace correlation

For each feature: Read ${SKILL_ROOT}/references/<feature>.md, follow steps exactly, verify it works.


Configuration Reference

Key Sentry.init() Options

OptionTypeDefaultNotes
dsnstringRequired. Use env var; SDK is disabled when empty
environmentstring"production"e.g., "staging", "development"
releasestringe.g., "my-app@1.2.3" or git SHA
dataCollectionobjectControl what data is collected (userInfo, cookies, headers, etc.)
dataCollection.userInfobooleantrueAuto-populate user.* fields from instrumentation
dataCollection.cookiesboolean|objecttrueCookie collection and filtering
dataCollection.httpHeadersobject{request: true, response: true}HTTP header collection for requests/responses
dataCollection.httpBodiesstring[]["incomingRequest", "outgoingRequest", "incomingResponse", "outgoingResponse"]Which HTTP body types to collect
dataCollection.queryParamsboolean|objecttrueQuery parameter collection and filtering
tracesSampleRatenumber0–1; use 1.0 in dev, 0.1–0.2 in prod
tracesSamplerfunctionPer-transaction sampling; overrides tracesSampleRate
tracePropagationTargets(string|RegExp)[]URLs that receive distributed tracing headers
replaysSessionSampleRatenumberFraction of all sessions recorded (client only)
replaysOnErrorSampleRatenumberFraction of error sessions recorded (client only)
enableLogsbooleanfalseEnable Sentry.logger.* API
beforeSendLogfunctionFilter/modify logs before send
debugbooleanfalseVerbose SDK output to console

Server-Only Options (instrumentation.server.ts / hooks.server.ts)

OptionTypeNotes
serverNamestringHostname tag on server events
includeLocalVariablesbooleanAttach local vars to stack frames
shutdownTimeoutnumberms to flush events before process exit (default: 2000)

Adapter Compatibility

AdapterSupport
@sveltejs/adapter-auto / adapter-vercel (Node)✅ Full
@sveltejs/adapter-node✅ Full
@sveltejs/adapter-cloudflare⚠️ Partial — requires extra setup
Vercel Edge Runtime❌ Not supported

SvelteKit File Summary

FilePurposeModernLegacy
src/instrumentation.server.tsServer Sentry.init() — runs once at startup✅ Required
src/hooks.client.tsClient Sentry.init() + handleError✅ Required✅ Required
src/hooks.server.tshandleError + sentryHandle() (no init)✅ Required✅ Init goes here
svelte.config.jsEnable experimental.instrumentation.server✅ Required
vite.config.tssentrySvelteKit() plugin for source maps✅ Recommended✅ Recommended
.envSENTRY_AUTH_TOKEN, SENTRY_ORG, SENTRY_PROJECT✅ For source maps✅ For source maps

Verification

After setup, trigger test events to confirm Sentry is receiving data:

<!-- src/routes/sentry-test/+page.svelte -->
<script>
  import * as Sentry from "@sentry/sveltekit";
</script>

<button onclick={() => { throw new Error("Sentry client test"); }}>
  Test Client Error
</button>

<button onclick={() => Sentry.captureMessage("Sentry test message", "info")}>
  Test Message
</button>
// src/routes/sentry-test/+server.ts
export const GET = () => {
  throw new Error("Sentry server test");
};

Check the Sentry dashboard:

  • Issues → both errors should appear within seconds
  • Traces → look for route-based transactions
  • Replays → session recording visible after page interaction
  • Logs → structured log entries (if logging enabled)

If nothing appears, set debug: true in Sentry.init() and check the browser/server console for SDK output.


Phase 4: Cross-Link

After completing Svelte/SvelteKit setup, check for a companion backend missing Sentry coverage:

# Look for backend in adjacent directories
ls ../backend ../server ../api ../go ../python 2>/dev/null
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3
cat ../Gemfile 2>/dev/null | head -3

If a backend exists without Sentry configured, suggest the matching skill:

Backend detectedSuggest skill
Go (go.mod)sentry-go-sdk
Python (requirements.txt, pyproject.toml)sentry-python-sdk
Ruby (Gemfile)sentry-ruby-sdk
Node.js (Express, Fastify, etc.)Use @sentry/node — see docs.sentry.io/platforms/javascript/guides/express/

Troubleshooting

IssueSolution
Events not appearingSet debug: true, check DSN, open browser console for SDK errors
Source maps not workingRun npm run build (not dev), verify SENTRY_AUTH_TOKEN is set
Server errors not capturedEnsure handleErrorWithSentry() is exported from hooks.server.ts
Client errors not capturedEnsure handleErrorWithSentry() is exported from hooks.client.ts
Session replay not recordingConfirm replayIntegration() is in client init only (never server)
sentryHandle() + other handles not composingWrap with sequence(Sentry.sentryHandle(), myHandle)
Ad-blocker blocking eventsSet tunnel: "/sentry-tunnel" and add a server-side relay endpoint
SvelteKit instrumentation not activatingConfirm experimental.instrumentation.server: true in svelte.config.js
Cloudflare adapter issuesConsult docs.sentry.io/platforms/javascript/guides/sveltekit/ for adapter-specific notes
wrapLoadWithSentry / wrapServerLoadWithSentry errorsThese are legacy wrappers — remove them; sentryHandle() instruments load functions automatically in ≥10.8.0

sentry의 다른 스킬

generate-frontend-forms
sentry
Sentry의 새로운 폼 시스템을 사용하여 폼을 생성하는 가이드입니다. 폼, 폼 필드, 유효성 검사 또는 자동 저장 기능을 구현할 때 사용하세요.
official
sentry-snapshots-cocoa
sentry
Apple/Cocoa 프로젝트를 위한 전체 Sentry Snapshots 설정입니다. "SnapshotPreviews 설정", "Apple 스냅샷 테스트 설정", "Apple 스냅샷 업로드" 요청 시 사용하세요.
official
architecture-review
sentry
직원 수준의 코드베이스 건강 검토. 모놀리식 모듈, 무음 실패, 타입 안전성 격차, 테스트 커버리지 구멍, LLM 친화성 문제를 찾습니다.
official
linear-type-labeler
sentry
Linear 이슈를 분류하고, 각 이슈의 제목과 설명 내용을 기반으로 Sentry 워크스페이스의 레이블 분류 체계에서 Type 레이블을 적용합니다.
official
sentry-flutter-sdk
sentry
Flutter 및 Dart를 위한 완전한 Sentry SDK 설정입니다. "Flutter에 Sentry 추가", "sentry_flutter 설치", "Dart에서 Sentry 설정" 또는 오류 구성을 요청받았을 때 사용하세요.
official
vercel-react-best-practices
sentry
Vercel Engineering의 React 및 Next.js 성능 최적화 가이드라인입니다. 이 스킬은 React/Next.js 코드를 작성, 검토 또는 리팩토링할 때 사용해야 합니다.
official
sentry-tanstack-start-sdk
sentry
TanStack Start React용 전체 Sentry SDK 설정. "TanStack Start에 Sentry 추가", "@sentry/tanstackstart-react 설치" 또는 오류 구성 요청 시 사용…
official
bump-size-limit
sentry
.size-limit.js 파일에서 크기 제한을 올립니다. size-limit CI 검사가 실패할 때 사용합니다. 사용자가 크기 제한 실패, 번들 크기 검사 실패, CI 크기 문제를 언급할 때 사용하세요.
official