Svelte
Set up Human Behavior with Svelte applications
Quickstart
Human Behavior works seamlessly to record sessions on your Svelte app.
Step 1: Installation
npm install humanbehavior-js
# or
yarn add humanbehavior-jsStep 2: Environment Variables
Create an environment file (.env) with your API key:
VITE_HUMANBEHAVIOR_API_KEY=your-api-key-hereImportant: For SvelteKit, environment variables must start with VITE_ to be accessible in the browser.
Step 3: Basic Setup
For SvelteKit (SSR-enabled)
Update your +layout.svelte file:
<script lang="ts">
import favicon from '$lib/assets/favicon.svg';
import '../app.css';
import Navigation from '$lib/Navigation.svelte';
import { HumanBehaviorTracker } from 'humanbehavior-js';
import { browser } from '$app/environment';
let { children } = $props();
// Initialize HumanBehavior when in browser
if (browser) {
const apiKey = import.meta.env.VITE_HUMANBEHAVIOR_API_KEY;
if (apiKey) {
HumanBehaviorTracker.init(apiKey);
}
}
</script>
<svelte:head>
<link rel="icon" href={favicon} />
</svelte:head>
<div class="min-h-screen bg-gray-50">
<Navigation />
{@render children?.()}
</div>Important: The browser check prevents the tracker from initializing during server-side rendering, which would cause errors since browser APIs aren't available on the server.
For Regular Svelte (non-SSR)
In your main.js or main.ts file:
import App from './App.svelte';
import { HumanBehaviorTracker } from 'humanbehavior-js';
// Direct initialization (no browser check needed)
const tracker = HumanBehaviorTracker.init('your-api-key-here');
const app = new App({
target: document.body
});
export default app;Step 4: Using in Components
Now you can use HumanBehavior directly in any Svelte component:
<script>
import { HumanBehaviorTracker } from 'humanbehavior-js';
function handleClick() {
HumanBehaviorTracker.capture('button_clicked', { button: 'cta' });
}
function handleFormSubmit() {
HumanBehaviorTracker.identifyUser({
userProperties: { email: 'user@example.com', plan: 'premium' }
});
}
</script>
<button on:click={handleClick}>Click Me</button>
<form on:submit={handleFormSubmit}>
<!-- form content -->
</form>That's it! The SDK now automatically tracks user interactions, navigation, and console events. Everything past here is optional.
Features
- Direct SDK integration
- SvelteKit SSR compatibility
- TypeScript support included
- Automatic session recording
- Custom event tracking
- User identification
Troubleshooting
- Check browser console for any error messages
- Verify your API key is correct and starts with
VITE_ - Ensure the tracker is initialized before any user interaction
- For SvelteKit: Make sure you're using the
browsercheck to avoid SSR issues - Make sure
.envis in your project root directory