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 datasaasOr with your preferred package manager:
yarn add datasaas
pnpm add datasaasBasic 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>
);
}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
| Option | Type | Default | Description |
|---|---|---|---|
| websiteId | string | — | Required. Your website ID (e.g., ds_YOUR_WEBSITE_ID) |
| domain | string | auto-detect | Your website domain for event validation |
| apiUrl | string | https://datasaas.co | Custom API endpoint URL |
| debug | boolean | false | Enable console logging for debugging |
| allowLocalhost | boolean | false | Allow tracking on localhost / 127.0.0.1 |
| autoCapturePageviews | boolean | true | Automatically track page views and SPA navigation |
| flushInterval | number | 5000 | Milliseconds between event queue flushes |
| maxQueueSize | number | 20 | Maximum events to batch before forcing a flush |
| allowedHostnames | string[] | — | Array of hostnames where tracking is allowed. Useful for multi-domain setups |
API Methods
| Method | Description |
|---|---|
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: truein the config to see console logs - Verify your
websiteIdmatches your dashboard settings - Check that
domainmatches 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 installagain
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.