> ## 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.

# Browser JS SDK

> Learn how to use FlockSDK via a script tag to power referrals on your website.

# Getting Started with FlockSDK

FlockSDK makes it simple to embed referral experiences on your website. This guide walks through the two main flows:

1. **Referrer** — the customer who sees and interacts with the referral widget.
2. **Invitee** — the visitor who lands on your site with a referral code.

FlockSDK is available via CDN, so you can add it to any webpage with just a script tag.

***

## 🧩 Installation

Add the following to your HTML page:

```javascript theme={null}
<!-- SDK JavaScript -->
<script src="https://app.withflock.com/public/sdk-js/index.js"></script>

<!-- SDK Styles -->
<link href="https://app.withflock.com/public/sdk-js/style.css" rel="stylesheet" />
```

Make sure this is loaded before you interact with `FlockSDK` in your scripts.

***

## 👥 Use Case: Referrer Setup

The **referrer** is your existing customer. The main flow here is:

1. Initialize the SDK
2. Identify the customer
3. Show the referral placement

### Example

```javascript theme={null}
<script>
  window.addEventListener('DOMContentLoaded', async () => {
    window.FlockSDK.shared.init({
      apiKey: 'YOUR_PUBLIC_API_KEY',
      environment: 'production', // or 'test'
    });

    await window.FlockSDK.shared.identify({
      externalUserId: 'referrer_123',
      email: 'referrer@example.com',
      name: 'Referrer',
    });

    // Show the referral placement (Placement ID can be found in the Flock campaign dashboard)
    await window.FlockSDK.shared.addPlacement('referrer');
  });
</script>
```

### Placement API (Recommended)

> **New:** Use `addPlacement(placementId)` on the singleton for opening campaign pages. Each campaign component now has a unique `placementId` for robust and future-proof integration.

A placement renders a Flock referral modal within your app, making it easy to prompt users to share and participate in your referral program.

### Example

```javascript theme={null}
await window.FlockSDK.shared.addPlacement('referrer');
```

* The legacy `renderWidget()` method is now **deprecated** and will be removed in a future release.
* Use the Placement API for all new integrations and update any usage of `renderWidget()` to `addPlacement(placementId)`.

***

### Legacy Widget API (Deprecated)

> **Deprecated:** `renderWidget()` is now deprecated. Use `addPlacement(placementId)` for all new integrations.

```javascript theme={null}
await window.FlockSDK.shared.renderWidget();
```

***

## 🌱 Use Case: Invitee Setup

The **invitee** is a visitor referred by someone else. The flow here is:

1. Capture referral code from the URL
2. Validate the referral
3. Create the referral when the invitee signs up

### Example

```javascript theme={null}
<script>
  window.addEventListener('DOMContentLoaded', async () => {
    window.FlockSDK.shared.init({
      apiKey: 'YOUR_PUBLIC_API_KEY',
      environment: 'production', // or 'test'
    });

    // If the referral code is in the URL like https://example.com/refer/<REFERRAL_CODE>
    const referralCode = window.location.path.split('/').filter(Boolean).pop()?.split('?')[0];

    if (referralCode) {
      const result = await window.FlockSDK.shared.validateReferralCode(referralCode);
      if (result.isValid) {
        console.log('Referral validated:', result.referredBy);
      } else {
        console.warn('Invalid referral code');
      }
    }

    // Later, once the invitee signs up:
    // await window.FlockSDK.shared.identify({...})
    // await window.FlockSDK.shared.createReferral();
  });
</script>
```

### ✅ `validateReferralCode(code, options)`

This method checks if the referral code is valid and stores the metadata in the specified storage.

```javascript theme={null}
// Using default storage (localStorage)
await window.FlockSDK.shared.validateReferralCode('jane123');

// Specifying storage type
await window.FlockSDK.shared.validateReferralCode('jane123', { storage: 'cookie' });
```

The options parameter supports:

* `storage`: Where to store the referral metadata
* `'localStorage'` (default) - Persists in the browser's local storage, can only be accessed by the same domain.
* `'cookie'` - Useful for cross-subdomain scenarios.

<Warning>
  When using cross-subdomain referrals, make sure to use the `cookie` storage option. This allows the referral data to be shared between subdomains of the same root domain.

  ```javascript theme={null}
  // Works across subdomains
  // User lands on: shop.example.com
  await window.FlockSDK.shared.validateReferralCode('CODE123', { storage: 'cookie' });
  // User navigates to: app.example.com
  // Referral data is still available!

  // Won't work across subdomains
  // User lands on: shop.example.com
  await window.FlockSDK.shared.validateReferralCode('CODE123', { storage: 'localStorage' });
  // User navigates to: app.example.com
  // Referral data is lost!
  ```

  Note: Cookies only work for subdomains of the same root domain. They won't work across completely different domains (e.g., example.com → another.com).
</Warning>

### 🆕 `createReferral()`

After the invitee signs up and is identified:

```javascript theme={null}
await window.FlockSDK.shared.identify({
  externalUserId: 'invitee_456',
  email: 'invitee@example.com',
  name: 'Invitee',
});

await window.FlockSDK.shared.createReferral(); // Automatically reads referral code from localStorage or cookies
```

Or you can pass it explicitly:

```javascript theme={null}
await window.FlockSDK.shared.createReferral({ referralCode: 'jane123' });
```

***

## 🧠 Tips

* Always call `identify()` before `addPlacement()` or `createReferral()`.

***

## ✅ Recap

| Role     | Key Methods                              |
| -------- | ---------------------------------------- |
| Referrer | `identify`, `addPlacement`               |
| Invitee  | `validateReferralCode`, `createReferral` |

With these tools, you can power robust referral experiences in just a few lines of code.

Happy referring! 🚀
