Svelte web analytics installation

Install posthog-js using your package manager:

npm install --save posthog-js

Then, if you haven't created a root layout already, create a new file called +layout.js in your src/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.js
import 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-11-30',
})
}
return
};

Next steps

After installing PostHog and ensuring autocapture is enabled, head to your web analytics dashboard to see your data. And then check out our getting started guide.

PostHog tip: Web analytics works with anonymous events. This means if you are primarily using PostHog for web analytics, it can be significantly cheaper for you.

Community questions

Was this page useful?

Questions about this page? or post a community question.