analytics.tube
GuidesSvelte

Svelte (Vite / Client-Side)

Integrate analytics-tube with your client-side Svelte application

This guide explains how to integrate analytics-tube with your standard client-side Svelte applications, typically built using Vite (e.g., via npm create vite@latest -- --template svelte).

How to Add analytics-tube to Your Client-Side Svelte App

The most straightforward method is to add the analytics-tube tracking script directly to your index.html file.

Retrieve Your Tracking Script

Navigate to your analytics-tube dashboard to obtain your code snippet:

<script
  src="https://app.analytics.tube/api/script.js"
  data-site-id="YOUR_SITE_ID"
  defer
></script>

Replace YOUR_SITE_ID with your actual Site ID.

Locate Your index.html File

For Vite-based Svelte projects, this file is typically located at the root of your project as index.html.

Add the Snippet to index.html

Open index.html and paste the analytics-tube tracking snippet just before the closing </head> tag or </body> tag.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <!-- Or your favicon -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Svelte App</title>
    <!-- analytics-tube Tracking Snippet -->
    <script
      src="https://app.analytics.tube/api/script.js"
      data-site-id="YOUR_SITE_ID"
      defer
    ></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script> <!-- Or main.ts -->
    <!-- Or place script here, before </body> -->
  </body>
</html>

Ensure YOUR_SITE_ID is replaced.

Verify Installation

Deploy your application and check your analytics-tube dashboard for incoming data. You can also inspect your browser's network tab to confirm script.js is loaded.

SPA Page View Tracking: analytics-tube's script is designed to automatically track route changes in client-side Svelte SPAs using common routers (like svelte-routing or svelte-spa-router). If page views aren't tracked correctly after navigation, you might need to manually trigger window.analytics-tube.pageview() after each route change, using your router's specific API for navigation events.

Custom Event Tracking

From any Svelte component, you can track custom events:

<script>
  function handleClientAction() {
    // Ensure running in browser, though for client-side Svelte this is usually the case
    if (typeof window !== 'undefined' && window.analytics-tube) {
      window.analytics-tube.event('user_action_svelte_vite', { component: 'MySvelteViteComponent' });
    }
  }
</script>

<button on:click={handleClientAction}>Perform Client Svelte Action</button>

Always check for window.analytics-tube before calling its methods.