NPM SDK / Package

The DataSaaS NPM package provides a fully typed JavaScript/TypeScript SDK for tracking events, managing sessions, and integrating with React and Next.js applications.

Installation

npm install datasaas

Or with your preferred package manager:

yarn add datasaas
pnpm add datasaas

Basic Setup

Initialize DataSaaS with your website ID and domain. The initDataSaaS function returns a client instance you can use to track events.

import { initDataSaaS } from 'datasaas';

const ds = await initDataSaaS({
  websiteId: 'ds_YOUR_WEBSITE_ID',
  domain: 'yourdomain.com',
  autoCapturePageviews: true,
});

// Track a custom event
ds.track('signup', { plan: 'pro' });

React / Next.js

Wrap your app with DataSaaSProvider for automatic pageview tracking and access to the SDK via hooks.

// app/providers.tsx (or app/layout.tsx)
import { DataSaaSProvider } from 'datasaas/react';

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <DataSaaSProvider config={{
      websiteId: process.env.NEXT_PUBLIC_DATASAAS_WEBSITE_ID!,
      domain: process.env.NEXT_PUBLIC_DATASAAS_DOMAIN,
      autoCapturePageviews: true,
    }}>
      {children}
    </DataSaaSProvider>
  );
}

Then use the hooks in any component:

import { useDataSaaS, useTrack } from 'datasaas/react';

export function SignupButton() {
  const ds = useDataSaaS();
  // or use the convenience hook:
  // const track = useTrack();

  return (
    <button onClick={() => ds.track('button_click', { label: 'signup' })}>
      Sign Up
    </button>
  );
}
Info

Store your website ID and domain in environment variables. For Next.js, prefix them with NEXT_PUBLIC_ so they are available in client-side code.

Singleton Pattern

If you need to access the SDK outside of React components (e.g., in utility functions or API handlers), use the singleton getter:

import { getAnalytics } from 'datasaas';

// Returns the initialized instance, or null if not yet initialized
const ds = getAnalytics();
ds?.track('background_event', { source: 'worker' });

Configuration Options

OptionTypeDefaultDescription
websiteIdstringRequired. Your website ID (e.g., ds_YOUR_WEBSITE_ID)
domainstringauto-detectYour website domain for event validation
apiUrlstringhttps://datasaas.coCustom API endpoint URL
debugbooleanfalseEnable console logging for debugging
allowLocalhostbooleanfalseAllow tracking on localhost / 127.0.0.1
autoCapturePageviewsbooleantrueAutomatically track page views and SPA navigation
flushIntervalnumber5000Milliseconds between event queue flushes
maxQueueSizenumber20Maximum events to batch before forcing a flush
allowedHostnamesstring[]Array of hostnames where tracking is allowed. Useful for multi-domain setups

API Methods

MethodDescription
track(event, meta?)Track a custom event with optional metadata
goal(name, meta?)Track a goal completion event
trackPageview(url?)Manually track a pageview (useful when autoCapturePageviews is off)
identify({ user_id, ...props })Associate the visitor with a user ID in your system
flush()Force-send all queued events immediately
reset()Clear cookies and generate a new visitor/session ID
getVisitorId()Returns the current visitor ID string
getSessionId()Returns the current session ID string
buildCrossDomainUrl(url)Appends visitor/session params to a URL for cross-domain tracking
getTrackingParams()Returns an object with current visitor and session params
optOut()Disable tracking for the current visitor
optIn()Re-enable tracking after an opt-out
shutdown()Flush remaining events and tear down the SDK

Cross-Domain Tracking

If your users navigate between different domains (e.g., from your marketing site to your app), use buildCrossDomainUrl to preserve visitor identity:

import { getAnalytics } from 'datasaas';

const ds = getAnalytics();

// When linking to another domain
const url = ds?.buildCrossDomainUrl('https://app.yourdomain.com/login');
// Returns: https://app.yourdomain.com/login?ds_vid=xxx&ds_sid=xxx

// Use in a link
<a href={url}>Go to app</a>

The receiving domain will automatically pick up the visitor and session IDs from the URL parameters, ensuring continuity across domains.

Troubleshooting

Events not appearing in the dashboard

  • Enable debug: true in the config to see console logs
  • Verify your websiteId matches your dashboard settings
  • Check that domain matches the hostname of your site
  • If testing locally, set allowLocalhost: true

Duplicate pageviews

  • Make sure you're not using both the script tag and the NPM package on the same page
  • If using React strict mode, the provider handles double-mount correctly — duplicates in dev mode are expected

TypeScript types not found

  • The package includes built-in TypeScript declarations. If types aren't resolving, try restarting your IDE or running npm install again
Tip

The NPM package and the tracking script (script.js) are interchangeable — use one or the other, not both. The NPM package is best for JavaScript-heavy applications where you want programmatic control.