# SvelteKit quickstart

> Add Insights Orbit to a SvelteKit website, send your own events, wait for consent and check that visits arrive.

Source: https://docs.bifrostorbit.com/insights/developers/quickstart-sveltekit/

In about 10 minutes you add Insights Orbit to a SvelteKit website for Northwilds. Page views count on every page, also when SvelteKit changes pages without reloading, a button sends a **Brochure requested** event, and an optional banner asks visitors before anything is counted.

**Tested with:** SvelteKit 3.1.1, Svelte 5.57.3, Vite 8.3.6, Node.js 24, in `vite dev` and `vite preview`.

## Before you start

You need:

- **A site in Insights Orbit** with your website's addresses under **Site settings**. Add `localhost` too while you build on your computer, or events from it answer `403`. See [Add your first site](https://docs.bifrostorbit.com/insights/everyone/add-a-site/).
- **The site key**, from the site's **Install** screen. It isn't a secret.
- **Node.js 22 or later.**

## 1. Create the project

```bash
npx sv@latest create northwilds-site --template minimal --types ts --no-add-ons --install npm
cd northwilds-site
```

Add the site key:

```bash
# .env
INSIGHTS_SITE=SITE_KEY
```

SvelteKit 3 reads the environment variables you declare in `src/env.ts`. Mark this one `public`, since the browser sees it in the page anyway:

```ts
// src/env.ts
import { defineEnvVars } from '@sveltejs/kit/env';

export const variables = defineEnvVars({
	INSIGHTS_SITE: { public: true, schema: (value) => value || undefined }
});
```

The value is read when the app starts, and the website runs without it.

## 2. Add the script

Add the script to the root layout's `<svelte:head>`, so it is on every page. Replace `src/routes/+layout.svelte`:

```svelte
<!-- src/routes/+layout.svelte -->
<script lang="ts">
	import { INSIGHTS_SITE } from '$app/env/public';
	import favicon from '#lib/assets/favicon.svg';
	import type { LayoutProps } from './$types';

	let { children }: LayoutProps = $props();
</script>

<svelte:head>
	<link rel="icon" href={favicon} />
	{#if INSIGHTS_SITE}
		<script defer data-site={INSIGHTS_SITE} src="https://api.bifrostorbit.com/insights/v1/script.js"></script>
	{/if}
</svelte:head>

<header>
	<a href="/">Northwilds</a> <a href="/trips">Trips</a>
</header>

{@render children()}
```

- **The tag is rendered on the server** and loads once. Later page changes don't load it again: the script follows them through `history.pushState`.
- **Without a key**, no script is added.

Replace `src/routes/+page.svelte`:

```svelte
<!-- src/routes/+page.svelte -->
<main>
	<h1>Northwilds</h1>
	<p>Guided trips in the far north.</p>
	<a href="/trips">See the trips</a>
</main>
```

## 3. Send your own events

A small helper calls the script, or queues the call when the script hasn't loaded yet. The script runs the queue once it loads.

```ts
// src/lib/insights.ts
export type Details = Record<string, string | number | boolean>;
export type Money = { revenue: number; currency: string };

type Insights = {
	track?: (name: string, details?: Details, money?: Money) => void;
	consent?: (given?: boolean) => void;
	q?: unknown[][];
};

declare global {
	interface Window {
		insights?: Insights;
	}
}

export function track(name: string, details?: Details, money?: Money) {
	if (window.insights?.track) window.insights.track(name, details, money);
	else (window.insights ??= { q: [] }).q?.push(['track', name, details, money]);
}

export function consent(given = true) {
	if (window.insights?.consent) window.insights.consent(given);
	else (window.insights ??= { q: [] }).q?.push(['consent', given]);
}
```

Call `track` from the browser only, such as in a click handler or `onMount`:

```svelte
<!-- src/routes/trips/+page.svelte -->
<script lang="ts">
	import { track } from '#lib/insights.ts';

	let sent = $state(false);

	function requestBrochure() {
		track('Brochure requested', { trip: 'lofoten-ski-touring' });
		sent = true;
	}
</script>

<main>
	<h1>Lofoten ski touring week</h1>
	<p>Seven days of ski touring above the fjords, from €2,450.</p>
	<button type="button" disabled={sent} onclick={requestBrochure}>
		{sent ? 'On its way' : 'Send me the brochure'}
	</button>
</main>
```

- **Event names** are what goals look for, so use plain words. Details are text, numbers or true or false; never names or email addresses. [Send your own events](https://docs.bifrostorbit.com/insights/developers/send-events/) has the limits.
- **Revenue** goes in the third argument: `track('Trip booked', { trip: 'lofoten-ski-touring' }, { revenue: 2450, currency: 'EUR' })`.
- **To count it as success**, an Editor adds a goal under **Goals** that sends the event `Brochure requested`. See [Set up goals](https://docs.bifrostorbit.com/insights/everyone/goals/).

## 4. Wait for consent (optional)

Insights Orbit uses no cookies and keeps no personal data. Whether you still ask first is your decision with your adviser. See [What to write in your privacy notice](https://docs.bifrostorbit.com/insights/everyone/privacy-notice/). To ask first, add `data-consent="wait"` to the script in the layout:

```svelte
<script defer data-site={INSIGHTS_SITE} data-consent="wait" src="https://api.bifrostorbit.com/insights/v1/script.js"></script>
```

The script now counts nothing until the page calls `insights.consent()`. It doesn't remember the answer, so your banner keeps it and calls `consent()` on every page:

```svelte
<!-- src/lib/ConsentBanner.svelte -->
<script lang="ts">
	import { onMount } from 'svelte';
	import { consent } from '#lib/insights.ts';

	const KEY = 'northwilds-analytics';
	let open = $state(false);

	onMount(() => {
		const saved = localStorage.getItem(KEY);
		if (saved === 'yes') consent();
		open = saved === null;
	});

	function choose(answer: 'yes' | 'no') {
		localStorage.setItem(KEY, answer);
		open = false;
		consent(answer === 'yes');
	}
</script>

{#if open}
	<aside aria-label="Analytics">
		<p>May we count your visit? We use no cookies and keep no personal data.</p>
		<button type="button" onclick={() => choose('yes')}>Yes</button>
		<button type="button" onclick={() => choose('no')}>No thanks</button>
	</aside>
{/if}
```

In the layout, add `import ConsentBanner from '#lib/ConsentBanner.svelte';` and put `<ConsentBanner />` after `{@render children()}`.

- **Page views before the answer wait in memory**, up to 50, and are sent the moment the visitor says yes, so the page where they agreed still counts.
- **No thanks** drops what is waiting, and nothing is sent on later pages.
- **If you already have a consent tool**, call `consent()` from it instead of this banner.

## 5. Check that events arrive

Run `npm run dev`, open `http://localhost:5173`, go to **Trips** and select **Send me the brochure**. If you added the banner, select **Yes** first.

- **In the browser:** the **Network** tab shows `POST` requests to `collect` answering `202`, with your page views and the event. Events are sent two seconds after they happen, or at once when the page is hidden.
- **In Insights Orbit:** **Install** says **Visits are arriving**, **Right now** on the overview shows you on `/trips`, and **Events** lists **Brochure requested** within a few seconds.
- **From the API**, on the Growth plan, with a key that reads events:

```bash
curl "https://api.bifrostorbit.com/insights/v1/events?site=SITE_KEY&name=Brochure%20requested" \
  -H "Authorization: Bearer ins_live_…"
```

Nothing arrives? Browsers with Do Not Track or Global Privacy Control on, and automated browsers such as Playwright, send nothing on purpose. [Troubleshooting for developers](https://docs.bifrostorbit.com/insights/developers/troubleshooting/) lists every other cause.

## Next steps

- [The script](https://docs.bifrostorbit.com/insights/developers/the-script/): every option, opting out and labels.
- [Serve Insights Orbit from your own domain](https://docs.bifrostorbit.com/insights/developers/first-party-proxy/): so ad blockers don't hide visits.
- [Send events from a server](https://docs.bifrostorbit.com/insights/developers/server-api/): payments and bookings your server confirms.
- [Read raw events](https://docs.bifrostorbit.com/insights/developers/raw-event-api/): every event for your own data tools.
