SvelteKit Error Tracking installation
Install with the wizard
Run this command in your project directory to add PostHog to your SvelteKit project. The wizard detects your framework, installs the SDK, and sets up your first events.
Or set it up manually by following the rest of this guide.
- 1
Install the package
RequiredInstall the PostHog JavaScript library using your package manager:
- 2
Initialize PostHog
RequiredIf you haven't created a root layout already, create a new file called
+layout.jsin yoursrc/routesfolder. Check the environment is the browser, and initialize PostHog if so:src/routes/+layout.jsSvelteKit layoutLearn more about SvelteKit layouts in the official documentation.
- 3
Server-side setup
OptionalInstall
posthog-nodeusing your package manager:Then, initialize the PostHog Node client where you'd like to use it on the server side. For example, in a load function:
routes/+page.server.jsNoteMake sure to always call
posthog.shutdown()after capturing events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately. - 4
Send events
Click around and view a couple pages to generate some events. PostHog automatically captures pageviews, clicks, and other interactions for you.
If you'd like, you can also manually capture custom events:
JavaScript - 5
Set up client-side exception capture
RequiredSvelteKit Hooks can be used to capture exceptions in the client and server-side.
Capture exceptions in the
handleErrorcallback in your client-side hooks file:src/hooks.client.js - 6
Set up server-side exception capture
RequiredTo capture exceptions on the server-side, you will also need to implement the
handleErrorcallback:src/hooks.server.ts - 7







