> ## Documentation Index
> Fetch the complete documentation index at: https://docs.withflock.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> Integrate Flock referral and rewards platform into your Node server with the official Node.js SDK. This guide covers setup, configuration, and usage for server-side applications.

## Overview

The Node.js SDK enables seamless integration of [Flock](https://www.withflock.com) referral and rewards into your backend services. Effortlessly build powerful referral programs, track customer engagement, and manage rewards programmatically.

* Identify and manage customers
* Ingest checkpoints to trigger rewards at key milestones
* Webhook event verification
* Fetch live campaigns
* Create and manage referrals
* Officially supported by the Flock team

***

## Installation

Install the SDK using npm or yarn:

```bash theme={null}
# Using npm
npm install @wflock/node-flock

# Using yarn
yarn add @wflock/node-flock
```

***

## Quick Start

### Initialize the SDK

```typescript theme={null}
import { FlockSDK } from '@wflock/node-flock';

// Initialize with your service access key
const sdk = new FlockSDK({
  accessKey: 'your-service-access-key', // Get this from the Flock dashboard
});
```

<Note>
  Your service access key should be kept secure and never exposed in client-side code. This SDK is designed for server-side use only.
</Note>

***

## Core Features

### 1. Ingest Checkpoints

Trigger checkpoints to record key milestones in your user journey and/or trigger rewards. See [Checkpoints](/core-features/checkpoints) for more details.

```typescript theme={null}
// Ingest a checkpoint
await sdk.checkpoints.ingest('purchase_completed', {
  externalUserId: 'user_123',   // The user ID in your system
  environment: 'production',    // or 'test'
});
```

### 2. Customer Management

Identify customers

```typescript theme={null}
// Identify a customer
const customer = await sdk.customers.identify({
  externalUserId: 'external_user_123',      // The user ID in your system
  email: 'user@example.com',
  name: 'Jane Doe',
  customProperties: {                    // Optional custom properties
    plan: 'premium',
    signupDate: '2025-01-15'
  }
});
```

<Note>
  Checkpoints are the recommended way to trigger rewards. Configure which checkpoints trigger rewards in the Flock dashboard.
</Note>

### 3. Campaign Management

Fetch live campaign details.

```typescript theme={null}
// Get live campaign for an environment
const campaign = await sdk.campaigns.getLive({
  environment: 'production', // or 'test'
  customerId: 'customer_123' // This is Flock internal ID that you get after calling the identify method
});
```

### 4. Referral Management

Sometimes, you may want to validate and create a referral from your backend.

```typescript theme={null}

// Validate a referral code
const validation = await sdk.referrals.validate('JANE123');

if (validation.isValid) {
  console.log('Valid referral code from:', validation.referredBy);
  // Create a referral
  const referral = await sdk.referrals.create({
    campaignId: 'campaign_123',
    referralCode: 'JANE123',
    refereeId: 'customer_123' // This is Flock internal ID that you get after calling the identify method
  });
}
```

### 5. Webhook Verification

Verify webhook events sent from Flock to ensure they are legitimate and secure:

```typescript theme={null}
// Express.js route handler example
app.post('/webhooks/flock', (req, res) => {
  try {
    // Get the signature from the headers
    const signature = req.headers['x-flock-signature'];

    if (!signature) {
      return res.status(401).json({ error: 'Missing signature header' });
    }

    // Validate and construct the webhook event
    const event = sdk.webhooks.constructEvent({
      secret: 'your_webhook_secret', // Get this from the Flock dashboard
      signature,
      payload: req.body,
      maxAge: 5 * 60 * 1000, // Optional: 5 minutes in milliseconds
    });

    // Handle the event based on its type
    switch (event.name) {
      case 'invitee.accepted':
        console.log(`Invitee ${event.data.invitee.id} accepted an invitation`);
        // Process the event...
        break;

      // Handle other event types...
      default:
        console.log(`Received unknown event type: ${event.name}`);
    }

    res.status(200).json({ received: true });
  } catch (error) {
    console.error('Webhook error:', error.message);
    return res.status(400).json({ error: error.message });
  }
});
```

### 6. Direct reward trigger (not recommended)

<Warning>
  Direct reward triggering should only be used when checkpoint-based rewards don't meet your needs. For most use cases, ingesting checkpoints is the recommended approach.
</Warning>

Trigger rewards programmatically:

```typescript theme={null}
// Trigger a reward
await sdk.rewards.trigger({
  externalUserId: 'user_123',
  environment: 'production', // or 'test'
  rewardFor: ['self', 'referral_partner'] // Who should receive the reward
});
```

***

## Best Practices

1. **Keep your access key secure** - Never expose it in client-side code
2. **Identify users early** - Call `identify()` before other operations
3. **Use checkpoints for rewards** - Configure reward triggers in the dashboard

***

## Support

* Email: [support@withflock.com](mailto:support@withflock.com)

***
