Svelte web analytics installation

  1. Install the package

    Required

    Install the PostHog JavaScript library using your package manager:

    npm install posthog-js
  2. Initialize PostHog

    Required

    If you haven't created a root layout already, create a new file called +layout.js in your src/routes folder. Check the environment is the browser, and initialize PostHog if so:

    src/routes/+layout.js
    import posthog from 'posthog-js'
    import { browser } from '$app/environment';
    import { onMount } from 'svelte';
    export const load = async () => {
    if (browser) {
    posthog.init(
    '<ph_project_api_key>',
    {
    api_host: 'https://us.i.posthog.com',
    defaults: '2026-01-30'
    }
    )
    }
    return
    };
    SvelteKit layout

    Learn more about SvelteKit layouts in the official documentation.

  3. Server-side setup

    Optional

    Install posthog-node using your package manager:

    npm install posthog-node --save

    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.js
    import { 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.

  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
    posthog.capture('my_custom_event', { property: 'value' })
  5. Next steps

    Recommended

    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.