- 1
Install PostHog
RequiredYour goal in this step: Install the PostHog JavaScript web and Node SDKs.Install
posthog-js
using your package manager:npm install --save posthog-jsThen, if you haven't created a root layout already, create a new file called
+layout.js
in yoursrc/routes
folder In this file, check the environment is the browser, and initialize PostHog if so. You can get both your API key and instance address in your project settings.routes/+layout.jsimport posthog from 'posthog-js'import { browser } from '$app/environment';export const load = async () => {if (browser) {posthog.init('<ph_project_api_key>', {api_host: 'https://us.i.posthog.com',defaults: '2025-05-24',})}return};Install
posthog-node
using your package manager:npm install posthog-node --saveThen, 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.jsimport { PostHog } from 'posthog-node';export async function load() {const posthog = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' });posthog.capture({distinctId: 'distinct_id_of_the_user',event: 'event_name',})await posthog.shutdown()}Note: Make 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. - 2
Set up client-side exception capture
RequiredSvelteKit Hooks can be used to capture exceptions in the client and server-side.
Capture exceptions in the
handleError
callback in your client-side hooks file:src/hooks.client.jsimport posthog from 'posthog-js';import type { HandleClientError } from '@sveltejs/kit';export const handleError = ({ error, status }: HandleClientError) => {// SvelteKit 2.0 offers a reliable way to check for a 404 error:if (status !== 404) {posthog.captureException(error);}}; - 3
Set up server-side exception capture
RequiredTo capture exceptions on the server-side, you will also need to implement the
handleError
callback:src/hooks.server.tsimport type { HandleServerError } from '@sveltejs/kit';import { PostHog } from 'posthog-node';const client = new PostHog('<ph_project_api_key>',{ host: 'https://us.i.posthog.com' })export const handleError = async ({ error, status }: HandleServerError) => {if (status !== 404) {client.captureException(error);await client.shutdown();}}; - 5
SvelteKit error tracking installation
Questions? Ask Max AI.
It's easier than reading through 698 pages of documentation
Community questions
Was this page useful?
Next article
Hono error tracking installation
Error tracking enables you to track, investigate, and resolve exceptions your customers face. Start by installing the posthog-node package using your package manager: Hono uses app.onError to handle uncaught exceptions. You can take advantage of this for error tracking. Remember to export your project API key as an environment variable.