Source: https://datafa.st/docs/npm
Markdown source: https://datafa.st/docs/npm.md
Description: Install and use the DataFast npm package in your JavaScript or TypeScript applications, including React, Next.js, Vue, Angular, and React Native / Expo.

# DataFast NPM SDK

Install [DataFast as an npm package](https://www.npmjs.com/package/datafast) for type-safe analytics tracking in JavaScript and TypeScript applications. Perfect for React, Next.js, Vue, Angular, and other web frameworks.

## Why use the SDK?

- **TypeScript support** - Full type definitions for autocomplete and type safety
- **Framework agnostic** - Works with React, Vue, Angular, Svelte, React Native / Expo, and vanilla JS
- **Automatic tracking** - Built-in page view, session, and device tracking
- **Offline-ready** - Queues events when offline and syncs when back online

## Installation

```bash
npm install datafast
```

> Check out the [official NPM package](https://www.npmjs.com/package/datafast) for more details.

## Quick Start

### Basic setup

```typescript
import { initDataFast } from 'datafast';

// Initialize the SDK
const datafast = await initDataFast({
  websiteId: 'dfid_******',
  domain: 'your_domain.com', // optional, defaults to current hostname
  autoCapturePageviews: true, // auto-tracks initial + SPA route changes
});

// That's it — pageviews are tracked automatically!

// Track custom events
datafast.track('signup', { email: 'user@example.com' });

// Identify users
datafast.identify('user_123', { 
  email: 'user@example.com',
  plan: 'pro' 
});
```

### React / Next.js example

```typescript
// lib/analytics.ts
import { initDataFast } from 'datafast';

let datafast: any = 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,
      autoCapturePageviews: true,
    });
  }
  return datafast;
}
```

Then use it in your app:

```typescript
// app/page.tsx or components/SignupButton.tsx
import { getAnalytics } from '@/lib/analytics';

export default function SignupButton() {
  const handleSignup = async () => {
    const analytics = await getAnalytics();
    
    // Track the signup event
    analytics.track('signup', {
      email: 'user@example.com',
      name: 'John Doe',
    });
  };

  return <button onClick={handleSignup}>Sign Up</button>;
}
```

### Automatic page view tracking in Next.js

With `autoCapturePageviews: true`, the SDK handles page view tracking automatically — no `useEffect` or `usePathname` boilerplate needed. It hooks into the History API and captures initial load + SPA navigations out of the box.

If you need more control, you can pass an options object:

```typescript
const datafast = await initDataFast({
  websiteId: 'dfid_******',
  autoCapturePageviews: {
    trackHashChanges: true,       // include hash-route changes (default: false)
    captureInitialPageview: true,  // fire pageview on init (default: true)
    debounceMs: 100,               // debounce rapid navigations (default: 100)
  },
});
```

If you prefer **manual** tracking (e.g. to add custom data), disable auto capture and use `usePathname`:

```typescript
// app/layout.tsx or pages/_app.tsx
'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { getAnalytics } from '@/lib/analytics';

export default function RootLayout({ children }) {
  const pathname = usePathname();

  useEffect(() => {
    (async () => {
      const analytics = await getAnalytics();
      analytics.trackPageview();
    })();
  }, [pathname]);

  return <html><body>{children}</body></html>;
}
```

### React Native / Expo example

Use the dedicated React Native entrypoint and the built-in provider + hooks when tracking analytics from a mobile app.  
> For a full walkthrough, see the **[React Native / Expo guide](https://datafa.st/docs/react-native)**.

Install these packages:

```bash
npm install datafast @react-native-async-storage/async-storage @react-native-community/netinfo expo-constants expo-device
```

Wrap your app with the provider:

```tsx
import { DataFastProvider } from 'datafast/react-native';

export default function RootLayout() {
  return (
    <DataFastProvider
      config={{
        websiteId: process.env.EXPO_PUBLIC_DATAFAST_WEBSITE_ID!,
        // Must match the domain configured in your DataFast website settings
        domain: process.env.EXPO_PUBLIC_DATAFAST_DOMAIN!,
        debug: __DEV__,
      }}>
      {/* your navigation / screens here */}
    </DataFastProvider>
  );
}
```

Then track screens and events with hooks:

```tsx
import { useDataFastScreen, useDataFastTrack } from 'datafast/react-native';

export default function HomeScreen() {
  useDataFastScreen('HomeScreen');
  const track = useDataFastTrack();

  return (
    <Pressable onPress={() => track('cta_click', { source: 'home_screen' })}>
      <Text>Tap to send a test event</Text>
    </Pressable>
  );
}
```

## Configuration Options

```typescript
interface DataFastWebConfig {
  websiteId: string;        // Required: Your DataFast website ID
  domain?: string;          // Optional: Domain (defaults to current hostname)
  apiUrl?: string;          // Optional: Custom API endpoint
  debug?: boolean;          // Optional: Enable debug logging
  flushInterval?: number;   // Optional: Flush interval in ms (default: 5000)
  maxQueueSize?: number;    // Optional: Max queue size before flush (default: 10)
  autoCapturePageviews?: boolean | {
    enabled?: boolean;          // Default true when object is provided
    trackHashChanges?: boolean; // Track hash-route changes (default: false)
    captureInitialPageview?: boolean; // Fire pageview on init (default: true)
    debounceMs?: number;        // Debounce rapid navigations (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
}
```

> **Localhost & iframe behavior:** By default, the SDK silently disables tracking on localhost, `file://` protocol, and inside iframes. It also detects bots and headless browsers automatically. To enable tracking during local development, set `allowLocalhost: true`. To enable tracking inside iframes, set `allowIframe: true`.

## API Methods

### Track custom events

```typescript
// Simple event
datafast.track('button_click');

// Event with custom data
datafast.track('purchase', {
  amount: 99.99,
  currency: 'USD',
  product: 'Premium Plan'
});
```

### Track page views

If you enabled `autoCapturePageviews`, pageviews are tracked automatically — you don't need to call `trackPageview()` manually. If you prefer manual control:

```typescript
// Track current page (sends full URL including query params, UTMs, etc.)
datafast.trackPageview();

// Track a specific path
datafast.trackPageview('/custom/path');
```

### Identify users

```typescript
// Simple identification
datafast.identify('user_123');

// With user properties
datafast.identify('user_123', {
  email: 'user@example.com',
  name: 'John Doe',
  plan: 'premium',
  signup_date: '2024-01-15'
});
```

### Flush events manually

By default, events are queued and sent automatically. You can manually flush:

```typescript
// Force send all queued events immediately
await datafast.flush();
```

### Reset the client

Clear visitor ID and session (useful for logout):

```typescript
datafast.reset();
```

### Cross-domain tracking (SDK)

If you need to track users across different root domains using the SDK (instead of the script tag), use the cross-domain helpers:

```typescript
const datafast = await initDataFast({
  websiteId: 'dfid_******',
  allowedHostnames: ['myapp.io'], // declare your other domains
});

// Get the tracking params to pass to another domain
const params = datafast.getTrackingParams();
// => { _df_vid: 'abc-123', _df_sid: 's456-789' }

// Build a URL with tracking params appended
const url = datafast.buildCrossDomainUrl('https://myapp.io/signup');
// => 'https://myapp.io/signup?_df_vid=abc-123&_df_sid=s456-789'
```

When the user lands on the other domain (also running the SDK), `initDataFast` automatically reads the `_df_vid` and `_df_sid` params from the URL, restores the visitor/session, and cleans the params from the address bar.

> For the script tag approach, see [cross-domain tracking](/docs/cross-domain-tracking).

## Advanced Usage

### Custom storage adapter (web)

```typescript
import { createDataFastClient, createMemoryStorageAdapter } from 'datafast';

// Use in-memory storage (no persistence)
const datafast = await createDataFastClient({
  websiteId: 'dfid_******',
  storage: createMemoryStorageAdapter(),
  // ... other config
});
```

### Server-side tracking (Node.js)

```typescript
import { createDataFastClient } from '@datafast/core';

const datafast = await createDataFastClient({
  websiteId: 'dfid_******',
  domain: 'your_domain.com',
  // Provide custom storage and network adapters for Node.js
});
```

### Access the singleton client

After initialization, you can access the client anywhere:

```typescript
import { getDataFastClient } from 'datafast';

const datafast = getDataFastClient();
datafast.track('event_name');
```

## Package Structure

**`datafast`** - Main SDK for web applications

- Entry point: `datafast` or `datafast/web`
- Includes localStorage, fetch adapters
- Auto-detects device, viewport, referrer

**`datafast/react-native`** - React Native / Expo implementation

- Entry point: `datafast/react-native`
- Uses AsyncStorage, NetInfo, and Expo device/constants under the hood
- Provides mobile-friendly helpers like `trackScreen` alongside `track`, `identify`, etc.

## TypeScript Support

All packages include full TypeScript definitions:

```typescript
import type { 
  DataFastClient, 
  DataFastConfig,
  TrackEventData 
} from 'datafast';

const config: DataFastConfig = {
  websiteId: 'dfid_******',
  debug: true
};
```

## Troubleshooting

**Events not showing up?**

- Check your `websiteId` is correct
- Enable `debug: true` to see console logs
- Verify your domain matches your DataFast dashboard settings
- Check network requests in browser DevTools

**TypeScript errors?**

- Ensure you're using TypeScript 5.0+
- Run `npm install @types/node` if needed
