npm package: @fluid-app/fairshare
Description: Fairshare functionality for Fluid Commerce applications
Author: Fluid Commerce
Latest version: 0.2.13

# FairShare SDK

A lightweight, privacy-focused tracking SDK for Fluid Commerce that seamlessly tracks user events, attribution, and conversions while prioritizing performance and user privacy.

## Important: Integration with Fluid SDK

**For most use cases, you don't need to install or initialize FairShare directly.**

FairShare is automatically included and initialized when you use the Fluid SDK. We recommend using the Fluid SDK directly for the simplest integration:

```typescript
import { initializeFluid } from "@fluid-app/fluid";

// This initializes both Fluid SDK and FairShare
// Attribution is now handled server-side via the settings API
initializeFluid({
  fluidShop: "your-shop-id",
});
```

The remainder of this documentation is for advanced use cases where you need to use FairShare independently from the Fluid SDK.

## Features

- **Server-side Attribution**: Attribution is automatically handled by the Fluid Commerce backend via the settings API
- **Session Management**: Uses localStorage instead of cookies to maintain sessions
- **Page Visit Tracking**: Automatic tracking of page views with metadata
- **Event Tracking**: Easy-to-use API for tracking custom events
- **Browser Fingerprinting**: Privacy-focused device identification for cross-session attribution
- **Event Batching**: Efficiently batches events to minimize network requests

## Installation

```bash
npm install @fluid-app/fairshare
# or
yarn add @fluid-app/fairshare
# or
pnpm add @fluid-app/fairshare
```

## Quick Start

```typescript
import { initializeFairshare, trackFairshareEvent } from "@fluid-app/fairshare";

// Initialize the SDK
initializeFairshare({
  fluidShop: "your-shop-id",
  debug: true, // Enable debug logging (optional)
  // Attribution is now handled server-side via the settings API
});

// Track a custom event (e.g., Add to Cart)
trackFairshareEvent({
  eventName: "ADD_TO_CART",
  data: {
    product_id: 123,
    variant_id: 456,
    quantity: 1,
  },
});
```

## Attribution Tracking

Attribution is now handled automatically by the Fluid Commerce backend via the settings API. The server parses URLs and provides attribution data, eliminating the need for client-side pattern matching.

### Server-side Attribution Benefits

- **Automatic URL parsing**: The server automatically extracts attribution from various URL formats
- **No client configuration needed**: Attribution patterns are managed server-side
- **Consistent attribution**: Centralized logic ensures consistent attribution across all touchpoints
- **Better performance**: No client-side regex processing required

### How Server-side Attribution Works

1. When a user visits your site, the URL is sent to the Fluid Commerce backend
2. The server parses the URL using centralized attribution logic
3. Attribution data is returned via the settings API and stored locally
4. All tracked events automatically include the server-determined attribution
5. Conversions are credited to the correct source based on server-side attribution rules

### Attribution Models

FairShare uses a **last-touch attribution model** by default. This means that if a user visits multiple attribution URLs, the most recent one will be used for tracking.

## API Reference

### Core Functions

#### `initializeFairshare(config)`

Initializes the FairShare SDK.

```typescript
interface FairshareConfig {
  // Required: Your Fluid shop identifier
  fluidShop: string;

  // Optional: Enable debug mode for console logging
  debug?: boolean;

  // Optional: Custom API endpoint for all Fluid API requests
  apiEndpoint?: string;

  // Optional: Attribution override that overrides URL-based attribution
  attributionOverride?:
    | {
        email: string;
      }
    | {
        username: string;
      }
    | {
        share_guid: string;
      }
    | {
        fluid_rep_id: number;
      }
    | {
        external_id: string;
      };

  // Optional: Configure tracking behavior
  trackingSettings?: {
    // Disable automatic page visit tracking on initialization (default: false)
    disableAutoPageTracking?: boolean;
  };

  // Optional: Configure event batching
  batchSize?: number; // Maximum events per batch (default: 10)
  batchInterval?: number; // Milliseconds between batch sends (default: 1000)
  maxQueueSize?: number; // Maximum events to store if offline (default: 100)
  flushIntervalMs?: number; // Auto-flush interval (default: 10000)
}
```

#### `trackFairshareEvent(event)`

Tracks a custom event with data.

```typescript
trackFairshareEvent({
  eventName: "CHECKOUT_STARTED",
  data: {
    cart_token: "cart_123456",
    metadata: {
      // Optional additional data
    },
  },
});
```

#### `getSessionToken()`

Gets the current session token.

```typescript
const sessionToken = getSessionToken();
```

#### `getAttribution()`

Gets the current attribution data.

```typescript
const attribution = getAttribution();
console.log(attribution?.username); // e.g., "influencer-name"
console.log(attribution?.email); // e.g., "affiliate@example.com"
console.log(attribution?.share_guid); // e.g., "abc123-def456-ghi789"
console.log(attribution?.fluid_rep_id); // e.g., 12345
console.log(attribution?.external_id); // e.g., "external-affiliate-id"
```

#### `reset()`

Clears all stored data and resets the SDK state.

```typescript
reset();
```

## Event Tracking Examples

### Add to Cart

```typescript
trackFairshareEvent({
  eventName: "ADD_TO_CART",
  data: {
    product_id: 123,
    variant_id: 456,
    quantity: 1,
    price: "19.99",
    metadata: {
      // Optional additional data
      product_name: "Blue Sweater",
      category: "Apparel",
    },
  },
});
```

### Checkout Started

```typescript
trackFairshareEvent({
  eventName: "CHECKOUT_STARTED",
  data: {
    cart_token: "cart_123456",
    metadata: {
      total_amount: "49.99",
      currency: "USD",
      items_count: 3,
    },
  },
});
```

## Debugging

Enable debug mode to see detailed logging in the browser console:

```typescript
initializeFairshare({
  fluidShop: "your-shop-id",
  debug: true,
  // Attribution is now handled server-side via the settings API
  // Optional: Use attribution override for specific scenarios
  // You can use any of these attribution data formats:
  attributionOverride: {
    email: "affiliate@example.com",
  },
  // OR
  // attributionOverride: { username: "influencer-username" },
  // OR
  // attributionOverride: { share_guid: "abc123-def456-ghi789" },
  // OR
  // attributionOverride: { fluid_rep_id: 12345 },
  // OR
  // attributionOverride: { external_id: "external-affiliate-id" },
});
```

You can also check localStorage directly to see what data is being stored:

- `fs_attribution` - Current attribution data
- `fs_session` - Session token
- `fs_fingerprint` - Browser fingerprint
- `fs_event_queue` - Queued events waiting to be sent

## License

MIT