Analytics

Enable web analytics for your application with Plausible, Google Analytics or PostHog.

Syntax

$ vela enable analytics [--provider <plausible|google|posthog>]

Without --provider you’re prompted to pick one. Outside a terminal (CI, scripts) the flag is required. You’re then asked for the provider’s configuration values, and any already present in your .env are kept without asking.

Analytics has no dependencies. It only touches the root layout and .env, so it works on static sites with no backend.

What you get

  • A component at src/lib/components/analytics/analytics.svelte that loads the provider’s script and tracks page views, including client-side navigations.
  • <Analytics /> mounted at the top level of src/routes/+layout.svelte, above {@render children()}.
  • The provider’s PUBLIC_* variables added to .env.

The component reads its configuration from $env/dynamic/public and renders nothing until the variables are set, so a local checkout with a blank .env sends no data. Set the same variables on each deploy target with vela env set.

Providers

Plausible

$ vela enable analytics --provider plausible
VariableDescription
PUBLIC_PLAUSIBLE_DOMAINThe site as registered in Plausible, e.g. example.com.

Loads plausible.io/js/script.js, which tracks client-side navigations on its own. If you self-host Plausible, change the script src in the component to point at your instance.

Google Analytics

$ vela enable analytics --provider google
VariableDescription
PUBLIC_GA_MEASUREMENT_IDThe measurement ID, e.g. G-XXXXXXXXXX.

Loads gtag.js with automatic page views turned off, then sends a page_view event from afterNavigate so each route change is counted exactly once. A gtag helper in src/lib/components/analytics/gtag.ts is available for custom events:

import { gtag } from '$lib/components/analytics/gtag';

gtag('event', 'sign_up', { method: 'email' });

PostHog

$ vela enable analytics --provider posthog
VariableDescription
PUBLIC_POSTHOG_KEYThe project API key, e.g. phc_....
PUBLIC_POSTHOG_HOSTThe ingestion host. Defaults to https://us.i.posthog.com; use https://eu.i.posthog.com for EU projects or your own instance.

Installs posthog-js and initialises it on mount with the 2025-05-24 defaults, which capture a pageview on every history change. Import posthog anywhere for custom events:

import posthog from 'posthog-js';

posthog.capture('sign_up');

Switching providers

Run the command again with a different --provider. The component is overwritten with the new provider’s implementation, the new variables are appended to .env and the layout is left alone, since <Analytics /> is already mounted. Remove the old provider’s variables from .env yourself.

Customising

The generated component is yours to edit. Common changes are gating it behind a cookie consent banner, skipping it for signed-in admins, or adding custom events with the helpers above.

To remove analytics entirely, run vela disable analytics.