Skip to content

Analytics

Kitbase provides privacy-friendly web analytics out of the box. Track pageviews, sessions, user engagement, and more without cookies.

Overview

Once you initialize the SDK, Kitbase automatically tracks key metrics:

MetricDescription
Unique VisitorsDistinct users visiting your site
SessionsUser sessions (30-minute timeout)
PageviewsTotal page views
Pages per SessionAverage pages viewed per session
Bounce RatePercentage of single-page sessions
Avg. Session DurationAverage time spent per session
RevenueTotal revenue tracked

Quick Start

There are two ways to add Kitbase Analytics to your website:

Add these script tags to your website's HTML, preferably in the <head> section:

html
<!-- Kitbase Web Analytics -->
<script>
  window.KITBASE_CONFIG = { token: '<YOUR_API_KEY>' };
</script>
<script defer src="https://kitbase.dev/script.js"></script>

That's it! The script will automatically:

  • Track page views on every navigation
  • Track user sessions with a 30-minute timeout
  • Track clicks on external links
  • Collect device, browser, and geographic data

Install the package:

bash
npm install @kitbase/analytics
# or
pnpm add @kitbase/analytics
# or
yarn add @kitbase/analytics

Initialize the SDK:

typescript
import { Kitbase } from '@kitbase/analytics';

const kitbase = new Kitbase({ token: '<YOUR_API_KEY>' });

Lite Build

For a smaller bundle size (~12KB vs ~50KB), use the lite build which excludes offline queue support:

typescript
import { Kitbase } from '@kitbase/analytics/lite';

Configuration

All tracking features are enabled by default. You can disable specific features if needed:

typescript
const kitbase = new Kitbase({
  token: '<YOUR_API_KEY>',
  analytics: {
    autoTrackSessions: true,       // Track sessions (default: true)
    autoTrackPageViews: true,      // Track page views (default: true)
    autoTrackOutboundLinks: true,  // Track outbound links (default: true)
    sessionTimeout: 30 * 60 * 1000, // Session timeout (default: 30 min)
  }
});
OptionDefaultDescription
autoTrackSessionstrueTrack session start automatically
autoTrackPageViewstrueTrack page views automatically
autoTrackOutboundLinkstrueTrack clicks on external links
sessionTimeout1800000Session timeout in ms (30 minutes)

Auto-Tracked Events

The SDK sends these events to the __analytics channel:

EventTriggerData Collected
session_startNew session beginsReferrer, UTM params, device info
screen_viewPage navigationPath, title, referrer
outbound_linkExternal link clickedURL, link text
revenuetrackRevenue() calledAmount, currency, order ID

Page Views

Automatic Tracking

typescript
const kitbase = new Kitbase({
  token: '<YOUR_API_KEY>',
  autoTrackPageViews: true,
});

// Or enable after initialization
kitbase.enableAutoPageViews();

Manual Tracking

typescript
await kitbase.trackPageView({
  path: '/products/123',           // Optional: defaults to current path
  referrer: 'https://google.com',  // Optional: defaults to document.referrer
  title: 'Product Details',        // Optional: defaults to document.title
});

SPA Support

For single-page applications, page views are tracked automatically on route changes when autoTrackPageViews is enabled.

Sessions

Sessions are automatically managed with a 30-minute inactivity timeout.

typescript
// Get current session
const session = kitbase.getSession();
// => {
//   id: 'sess_abc123',
//   startedAt: 1705321800000,
//   lastActivityAt: 1705323600000
// }

// Get session ID
const sessionId = kitbase.getSessionId();

// Start a new session
kitbase.reset();

Session Duration

Session duration is calculated server-side using the time between events, with a 30-minute cap for idle periods. This ensures accurate duration even if users leave tabs open.

Bounce Rate

A session is considered a "bounce" if the user views only one page. Bounce rate is calculated server-side as:

Bounce Rate = (Single-page Sessions ÷ Total Sessions) × 100

Track when users click links to external domains.

typescript
const kitbase = new Kitbase({
  token: '<YOUR_API_KEY>',
  autoTrackOutboundLinks: true, // Default: true
});

// Or track manually
await kitbase.trackOutboundLink({
  url: 'https://partner-site.com',
  text: 'Visit Partner',
});

Revenue

Track revenue events for e-commerce analytics.

typescript
await kitbase.trackRevenue({
  amount: 99.99,
  currency: 'USD',
  orderId: 'order-123',
  productId: 'prod-456',
  tags: { plan: 'premium' },
});
ParameterTypeRequiredDescription
amountnumberYesRevenue amount
currencystringNoCurrency code (e.g., "USD")
orderIdstringNoOrder identifier
productIdstringNoProduct identifier
tagsobjectNoAdditional metadata

Dashboard Breakdowns

The dashboard lets you break down analytics by various dimensions:

Device & Browser

DimensionExample Values
DeviceDesktop, Mobile, Tablet
BrowserChrome, Safari, Firefox, Edge
OSWindows, macOS, iOS, Android

Geographic

DimensionExample Values
CountryUnited States, Germany, Japan
RegionCalifornia, Bavaria, Tokyo
CitySan Francisco, Munich, Shibuya

Traffic Sources

DimensionExample Values
Referrergoogle.com, twitter.com, direct
UTM Sourcegoogle, newsletter, facebook
UTM Mediumcpc, email, social
UTM Campaignspring_sale, launch_2024

Pages

DimensionDescription
Top PagesMost viewed pages
Entry PagesFirst page of sessions
Exit PagesLast page of sessions
Avg. Time on PageTime spent per page

Data Enrichment

The SDK automatically collects (without cookies):

DataSource
Device typeUser agent parsing
Browser & versionUser agent parsing
OS & versionUser agent parsing
Country, region, cityIP geolocation (server-side)
Referrerdocument.referrer
UTM parametersURL query parameters
Page path & titlewindow.location, document.title

Privacy-Friendly

Kitbase doesn't use cookies for analytics. User identification uses localStorage for anonymous IDs, which can be disabled.

Script Tag Advanced Configuration

When using the script tag method, you can customize the behavior through window.KITBASE_CONFIG:

html
<script>
  window.KITBASE_CONFIG = {
    // Required: Your SDK key from the dashboard
    token: '<YOUR_API_KEY>',

    // Optional: Enable debug logging
    debug: false,

    // Optional: Custom API endpoint (for self-hosted)
    baseUrl: 'https://api.kitbase.dev',

    // Analytics configuration
    analytics: {
      // Automatically track page views (default: false)
      autoTrackPageViews: true,

      // Automatically track sessions (default: true)
      autoTrackSessions: true,

      // Track clicks on external links (default: true)
      autoTrackOutboundLinks: true,

      // Session timeout in milliseconds (default: 30 minutes)
      sessionTimeout: 1800000
    }
  };
</script>
<script defer src="https://kitbase.dev/script.js"></script>

Accessing the SDK Instance

After the script loads, you can access the SDK instance via window.kitbase:

html
<script>
  // Wait for the script to load
  document.addEventListener('DOMContentLoaded', function() {
    // Track a custom event
    window.kitbase.track({
      channel: 'engagement',
      event: 'Button Clicked',
      tags: { button_id: 'cta-header' }
    });

    // Track revenue
    window.kitbase.trackRevenue({
      amount: 49.99,
      currency: 'USD',
      orderId: 'order-123'
    });

    // Identify a user
    window.kitbase.identify({
      userId: 'user_123',
      traits: {
        email: 'user@example.com',
        plan: 'premium'
      }
    });
  });
</script>

Content Security Policy (CSP)

If your site uses a Content Security Policy, add the following directives:

script-src 'self' https://kitbase.dev;
connect-src 'self' https://api.kitbase.dev;

Subresource Integrity (SRI)

For additional security, you can use SRI to verify the script integrity:

html
<script
  src="https://kitbase.dev/script.js"
  integrity="sha384-..."
  crossorigin="anonymous"
  defer
></script>

Contact support for the current SRI hash.

Released under the MIT License.