Back to Frameworks
🧡
Svelte
Integrate Dwellcount into your Svelte application with stores and actions.
Installation
npm install @dwellcount/svelteSetup
Initialize Dwellcount once in your app entry point:
// src/lib/analytics.ts or +layout.svelte
import { initDwellcount } from '@dwellcount/svelte';
initDwellcount({
siteId: 'YOUR_SITE_ID',
version: '1.0.0',
// endpoint: 'https://your-server.com/api/ingest' // Self-hosted
});Store-based API
Use the tracker store functions in any component:
<script>
import { track, identify, setBackendVersion } from '@dwellcount/svelte';
async function handleClick() {
// Track custom event
track('button_clicked', { location: 'hero' });
// Fetch data and capture backend version
const response = await fetch('/api/data');
const version = response.headers.get('X-App-Version');
if (version) {
setBackendVersion({ version });
}
}
function handleLogin(userId) {
identify(userId, { plan: 'pro' });
}
</script>
<button on:click={handleClick}>
Click Me
</button>trackAction
Use the use:trackAction directive for declarative tracking:
<script>
import { trackAction } from '@dwellcount/svelte';
</script>
<!-- Track click event -->
<button use:trackAction={{ event: 'cta_clicked', props: { variant: 'primary' } }}>
Get Started
</button>
<!-- Track with custom trigger -->
<div
use:trackAction={{
event: 'product_viewed',
props: { productId: 123 },
on: 'mouseenter'
}}
>
Product Card
</div>
<!-- Track form submission -->
<form use:trackAction={{ event: 'form_submitted', on: 'submit' }}>
<input type="email" placeholder="Email" />
<button type="submit">Subscribe</button>
</form>SvelteKit Integration
For SvelteKit apps, initialize in your root layout:
<!-- src/routes/+layout.svelte -->
<script>
import { onMount } from 'svelte';
import { initDwellcount, track } from '@dwellcount/svelte';
import { page } from '$app/stores';
import { browser } from '$app/environment';
// Initialize once on client
if (browser) {
initDwellcount({
siteId: 'YOUR_SITE_ID',
version: '1.0.0',
});
}
// Track page views on navigation
$: if (browser && $page.url) {
track('page_view', {
path: $page.url.pathname,
});
}
</script>
<slot />Available Functions
| Function | Description |
|---|---|
| initDwellcount(config) | Initialize the tracker |
| track(event, props?) | Track a custom event |
| identify(userId, traits?) | Identify a user |
| setBackendVersion(version) | Set backend version info |
| trackAction | Svelte action for declarative tracking |