datafast
v3.0.6
Published
Analytics SDK for DataFast — Web and React Native
Maintainers
Readme
Official DataFast SDK for web apps
Use this if you prefer npm packages over the <script> tag.
Looking for the CLI? Use
@datafast/clito query analytics and manage DataFast from your terminal. It is helpful for AI agents too 🤖
Installation
npm install datafastQuick Start
Same API as in the DataFast docs: use initDataFast once, then call trackPageview(), track(), identify(), and trackPayment(). All methods are async and return Promises.
import { initDataFast } from 'datafast';
const datafast = await initDataFast({
websiteId: 'your-website-id',
domain: 'yourdomain.com', // optional, defaults to current hostname
autoCapturePageviews: true, // optional: capture initial + SPA route changes
});
// Track page views
datafast.trackPageview();
// Or pass a path (e.g. for SPAs)
datafast.trackPageview('/pricing');
// Track custom events
datafast.track('button_click', { button: 'signup' });
// Identify users
datafast.identify('user_123', { email: '[email protected]', plan: 'pro' });
// Track payments (email-based)
datafast.trackPayment({ email: '[email protected]', amount: 99, currency: 'USD' });
// Or provider-ID based payment tracking
datafast.trackPayment({ stripe_session_id: 'cs_test_123' });
// Reset visitor identity (e.g. on logout)
datafast.reset();With React / Next.js
// lib/analytics.ts
import { initDataFast } from 'datafast';
let datafast: Awaited<ReturnType<typeof initDataFast>> | null = null;
export async function getAnalytics() {
if (!datafast) {
datafast = await initDataFast({
websiteId: process.env.NEXT_PUBLIC_DATAFAST_WEBSITE_ID!,
domain: process.env.NEXT_PUBLIC_DATAFAST_DOMAIN,
});
}
return datafast;
}Then in your app:
import { getAnalytics } from '@/lib/analytics';
export default function SignupButton() {
const handleSignup = async () => {
const analytics = await getAnalytics();
analytics.track('signup', { plan: 'free', source: 'homepage' });
};
return <button onClick={handleSignup}>Sign Up</button>;
}API
initDataFast(config) → Promise<DataFastWeb>
Initialize the SDK. Returns a client with trackPageview, track, identify, trackPayment, reset, and flush.
Config (DataFastWebConfig)
{
websiteId: string; // Required: Your DataFast website ID
domain?: string; // Optional: Defaults to current hostname
apiUrl?: string; // Optional: Custom API endpoint
debug?: boolean; // Optional: Enable debug logging
flushInterval?: number; // Optional: ms between flushes (default: 5000)
maxQueueSize?: number; // Optional: max events before flush (default: 10)
autoCapturePageviews?: boolean | {
enabled?: boolean; // Default true when object is provided
trackHashChanges?: boolean; // Default false
captureInitialPageview?: boolean; // Default true
debounceMs?: number; // Default 100
};
allowLocalhost?: boolean; // Allow tracking on localhost (default: false)
allowIframe?: boolean; // Allow tracking inside iframes (default: false)
allowedHostnames?: string[]; // Hostnames for cross-domain tracking
cookieless?: boolean; // Privacy-first mode: no ID cookies; see "Cookieless mode" below
onCookielessVisitorId?: (visitorId: string) => void; // Override default window.datafast.visitorId sync
}Cookieless mode (web)
See the full GDPR Cookieless Tracking guide for compliance details.
With cookieless: true, the SDK matches the hosted cookieless script’s storage model: sessionStorage for session + server-returned visitor id (no cookies for IDs), a fresh client visitor id per event with cookieless: true on the payload, and ad click ids (gclid, fbclid, etc.) parsed from the tracked URL when it is http(s). Successful responses that include visitorId update storage, getVisitorId(), and (by default) window.datafast.visitorId. In this mode, getTrackingParams() returns empty strings and buildCrossDomainUrl leaves the URL unchanged (no _df_* params).
When autoCapturePageviews is enabled, the SDK will:
- capture one initial pageview after
initDataFast - capture subsequent pageviews on
history.pushState,history.replaceState, and back/forward (popstate) - optionally include hash-route changes when
trackHashChanges: true
By default, tracking is silently disabled on localhost, file:// protocol, inside iframes, and for bots/headless browsers. Set allowLocalhost: true for local development.
datafast.trackPageview(path?) → Promise<void>
Track a page view. Omit path to use window.location.href (full URL including query params, UTMs, and ad click IDs). Pass a path for manual override. Duplicate pageviews for the same URL within 60 seconds are automatically skipped.
datafast.track(eventName, properties?) → Promise<void>
Track a custom event. properties is optional and must be Record<string, string | number | boolean>.
await datafast.track('purchase', { product: 'Pro Plan', price: 99 });datafast.identify(userId, properties?) → Promise<void>
Identify a logged-in user.
await datafast.identify('user_123', { name: 'John', email: '[email protected]' });datafast.trackPayment(data) → Promise<void>
Track a payment. data must include one of:
email, stripe_session_id, lemonsqueezy_order_id, polar_checkout_id, paddle_transaction_id.
amount and currency are optional.
await datafast.trackPayment({ email: '[email protected]', amount: 99, currency: 'USD' });
await datafast.trackPayment({ stripe_session_id: 'cs_test_123' });datafast.reset() → Promise<void>
Reset visitor identity (e.g. on logout). New visitor and session IDs are generated.
datafast.flush() → Promise<void>
Flush all queued events immediately.
datafast.getTrackingParams() → { _df_vid: string; _df_sid: string }
Get the current visitor and session IDs for cross-domain tracking. In cookieless mode this returns { _df_vid: '', _df_sid: '' }.
datafast.buildCrossDomainUrl(url) → string
Append visitor/session tracking params to a URL for cross-domain navigation. In cookieless mode the URL is returned unchanged.
datafast.isCookieless() → boolean
Whether the client was initialized with cookieless: true.
const url = datafast.buildCrossDomainUrl('https://other-domain.com/signup');
// => 'https://other-domain.com/signup?_df_vid=abc-123&_df_sid=s456-789'On the receiving domain, initDataFast automatically picks up the params and restores the visitor/session.
🇪🇺 Cookieless Mode (GDPR-Friendly)
No cookies. No consent banners. Full analytics.
Enable cookieless tracking by passing cookieless: true to initDataFast. The SDK uses sessionStorage instead of cookies for visitor/session IDs — fully compliant with GDPR and ePrivacy regulations.
import { initDataFast } from 'datafast';
const datafast = await initDataFast({
websiteId: 'your-website-id',
cookieless: true, // No cookies, no consent banner needed
});
datafast.trackPageview();
datafast.track('signup', { plan: 'pro' });In cookieless mode:
- Visitor and session IDs are stored in
sessionStorageonly getTrackingParams()returns empty stringsbuildCrossDomainUrl()leaves URLs unchanged (no_df_*params)- Each event sends a fresh client visitor ID with
cookieless: trueon the payload
Full setup guide and compliance details: GDPR Cookieless Tracking
Script Tag Alternative
If you prefer not to use npm, add the script tag instead:
<script src="https://datafa.st/script.js" data-website-id="your-website-id" async defer></script>License
MIT

