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

# Evaluate feature flags before consent with the JavaScript SDK

> Serve the same flag variant to a visitor across page loads before they answer your consent banner, and hold Mixpanel events on the device until they accept.

Some sites need to show a flagged experience, such as a badge or a layout change, before the visitor answers the consent banner, while sending no events to Mixpanel until the visitor accepts. This guide sets up the JavaScript SDK so the visitor's flag variant stays the same across page loads before consent, the exposure event waits on the device, and queued events send when the visitor accepts. For background, see [Implement Feature Flags (Web)](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript/javascript-flags.md).

> [!WARNING]
>
> In this setup, the SDK does the following before the visitor gives consent:
>
> 1. Stores the visitor's distinct ID in a cookie or local storage.
> 2. Stores queued events in local storage.
> 3. Sends a flag request to Mixpanel that includes the distinct ID and device ID.
>
> If a visitor's browser blocks local storage, or saving to the queue fails, for example because storage is full, the SDK sends each event right away instead of queueing it. For those visitors, `batch_autostart: false` doesn't hold the exposure event. See [Events send before the visitor accepts](#events-send-before-the-visitor-accepts).
>
> Whether that's allowed under the consent rules for your site is your decision. Review this setup with your privacy or legal team before you ship it.

## Before you begin

* The JavaScript SDK is installed on your site. See [Mixpanel SDKs: Javascript](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript).
* You have a feature flag in your project and know its flag key. See [Feature Flags](https://docs.mixpanel.com/docs/featureflags).
* Your consent management tool gives you a callback or event when the visitor accepts and when they decline.
* Feature Flags availability depends on your plan. See [pricing](https://mixpanel.com/pricing/). For the permissions you need to create flags, see [Roles and permissions](https://docs.mixpanel.com/docs/orgs-and-projects/roles-and-permissions.md).

## EU data residency and consent rules

If your project uses EU data residency, set `api_host: 'https://api-eu.mixpanel.com'` in every `init()` call on this page, including the tracking instance in Path B. The flag request uses the same host as events, so this one setting sends both to Mixpanel's EU servers. See [EU Residency](https://docs.mixpanel.com/docs/privacy/eu-residency.md) and [EU Data Residency](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript#eu-data-residency) in the JavaScript SDK reference.

EU residency controls where Mixpanel stores and processes your data. It doesn't change what the SDK stores on the visitor's device before consent. In France, the CNIL requires consent before a site reads or writes an identifier in a cookie or local storage, unless the storage is strictly necessary or falls under one of the CNIL's exemptions. Other EU regulators apply similar rules under the ePrivacy Directive. This setup stores a distinct ID and queued events and sends a flag request before consent, so your privacy or legal team needs to decide whether it fits your consent basis. If it doesn't, evaluate flags after the visitor accepts.

## Settings that break pre-consent flags

Don't use these settings on the instance that evaluates flags. Each one stops flags from working until the visitor accepts.

| Setting | What happens before consent |
| - | - |
| `opt_out_tracking_by_default: true` | The SDK stores an opt-out status for the visitor. On the next page load, it reads that status, then deletes and stops storing the visitor's distinct ID. The SDK creates a new device ID on every page load, so the visitor can get a different variant each time. |
| `consent_mode: 'require_consent'` | The SDK sends nothing before `opt_in_tracking()`, including the flag request. The visitor gets no variant until they accept. |

## Choose your setup

Pick the path that matches how you load Mixpanel on the page.

| If you... | Use |
| - | - |
| Run one Mixpanel instance that evaluates flags and tracks events | [Path A: one instance](#path-a-one-instance) |
| Evaluate flags in one instance on page load, and track events in a second instance that loads after consent, for example from a tag manager | [Path B: separate flag and tracking instances](#path-b-separate-flag-and-tracking-instances) |

Path A is the default. It has one identity and one event queue, so there's nothing to keep in sync. Use Path B only when your tracking instance can't load before consent.

## Path A: one instance

In Path A, a single JavaScript SDK instance loads before the consent banner, evaluates flags, queues events in local storage, and starts sending them when the visitor accepts.

### Path A settings

| Setting | Value | Notes |
| - | - | - |
| `flags` | `true` | Turns on flag requests. Use an object with `context` instead if your flags use a custom [Variant Assignment Key](https://docs.mixpanel.com/docs/featureflags#targeting-&-identity-management) or [runtime targeting](https://docs.mixpanel.com/docs/featureflags#targeting-&-identity-management). See [Flag initialization](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript/javascript-flags.md#flag-initialization) for how to pass `context`. |
| `batch_requests` | `true` | The default. The SDK queues events in local storage instead of sending each one right away. |
| `batch_autostart` | `false` | The queue doesn't send until you call `start_batch_senders()`. The default is `true`. |
| `opt_out_tracking_by_default` | Leave unset | Unset is the same as `false`. See [Settings that break pre-consent flags](#settings-that-break-pre-consent-flags). |
| `consent_mode` | Leave unset | See [Settings that break pre-consent flags](#settings-that-break-pre-consent-flags). |

### Set up Path A

**1. Initialize the SDK before the consent banner loads**

```javascript theme={"system"}
mixpanel.init('YOUR_PROJECT_TOKEN', {
  flags: true,
  batch_requests: true,
  batch_autostart: false,
});
```

Replace `YOUR_PROJECT_TOKEN` with the token from your project settings. On the visitor's first page load, the SDK creates a device ID and stores it. Later page loads reuse it. The flag request goes out as soon as the SDK loads.

**2. Read the flag where the visitor sees the feature**

```javascript theme={"system"}
const variant = await mixpanel.flags.get_variant_value('YOUR_FLAG_KEY', 'control');
```

Replace `YOUR_FLAG_KEY` with the flag key from the flag's page in Mixpanel. The SDK tracks a `$experiment_started` exposure event and adds it to the queue in local storage. It doesn't send it. Any other events you track before consent wait in the same queue.

If you load the SDK from the CDN snippet, the library loads asynchronously, and `mixpanel.flags` doesn't exist until it finishes. Read flags inside the `loaded` callback in your `init()` options so the call runs after the SDK is ready:

```javascript theme={"system"}
mixpanel.init('YOUR_PROJECT_TOKEN', {
  flags: true,
  batch_requests: true,
  batch_autostart: false,
  loaded: async function (mixpanel) {
    const variant = await mixpanel.flags.get_variant_value('YOUR_FLAG_KEY', 'control');
  },
});
```

If you import the SDK from npm, you can call `mixpanel.flags` right after `init()`.

**3. Start sending events when the visitor accepts**

```javascript theme={"system"}
// Run on every page load, so a visitor who already accepted keeps sending events.
if (hasStoredConsent()) {
  mixpanel.start_batch_senders();
}

// Run when the visitor accepts the banner.
onConsentGranted(function () {
  mixpanel.opt_in_tracking();
  mixpanel.start_batch_senders();
});
```

Replace `hasStoredConsent` with a check of your consent tool's saved choice, and `onConsentGranted` with its accept callback. `batch_autostart: false` applies on every page load, and `start_batch_senders()` only lasts for the current page, so call it on every page load where consent is already stored. Once it runs, the SDK sends the queued events, including the exposure event, and sends later events as they happen. `opt_in_tracking()` clears the opt-out that `opt_out_tracking()` saved if the visitor declined earlier and now accepts. Without it, their events stay blocked. It also sends an `$opt_in` event.

**4. Stop storing data when the visitor declines**

```javascript theme={"system"}
onConsentDeclined(function () {
  mixpanel.opt_out_tracking();
});
```

Replace `onConsentDeclined` with your consent tool's decline callback. `opt_out_tracking()` stops the queue, deletes the queued events, and stops storing the visitor's distinct ID. If you've called `identify()` for this visitor, it also deletes their user profile. To keep the profile, call `mixpanel.opt_out_tracking({delete_user: false})`.

> [!NOTE]
>
> If the visitor doesn't answer the banner, the queued events stay in local storage. They send on a later page if the visitor accepts there.

### Verify Path A

1. Open your site in a private browser window and don't answer the consent banner.
2. In your browser's developer tools, open the **Network** tab and filter for `mixpanel`. You should see a request to `/flags/` and no request to `/track/`.
3. Open the **Application** tab. Under **Local storage**, the `__mpq_YOUR_PROJECT_TOKEN_ev` entry should hold a `$experiment_started` event. Under **Cookies**, the `mp_YOUR_PROJECT_TOKEN_mixpanel` cookie should hold a `distinct_id`.
4. Reload the page. The `distinct_id` and the variant should stay the same.
5. Accept the consent banner. You should see a request to `/track/` that includes `$experiment_started`, and the queue entry should empty.

If the `distinct_id` changes on reload, or you see a `/track/` request before you accept, go to [Troubleshooting](#troubleshooting).

## Path B: separate flag and tracking instances

In Path B, a flag instance loads before the consent banner and evaluates flags. A tracking instance loads after the visitor accepts. Both instances use the same project token and the same stored identity, so the exposure event and the visitor's later events share a distinct ID.

The SDK stores the identity under `mp_` plus the `persistence_name` value, or under `mp_YOUR_PROJECT_TOKEN_mixpanel` if `persistence_name` is unset. Two instances share an identity only when they use the same `persistence` and `persistence_name` values.

### Path B settings

Flag instance:

| Setting | Value | Notes |
| - | - | - |
| `flags` | `true` | Use an object with `context` if your flags use a custom [Variant Assignment Key](https://docs.mixpanel.com/docs/featureflags#targeting-&-identity-management) or [runtime targeting](https://docs.mixpanel.com/docs/featureflags#targeting-&-identity-management). See [Flag initialization](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript/javascript-flags.md#flag-initialization) for how to pass `context`. |
| `batch_requests` | `true` | The default. |
| `batch_autostart` | `false` | Holds the exposure event until you call `start_batch_senders()`. |
| `persistence` | `'localStorage'` or `'cookie'` | Must match the tracking instance. `'cookie'` is the default. |
| `persistence_name` | Leave unset, or the same value as the tracking instance | A different value gives the flag instance its own distinct ID. |
| `opt_out_tracking_by_default` | Leave unset | See [Settings that break pre-consent flags](#settings-that-break-pre-consent-flags). |

Tracking instance:

| Setting | Value | Notes |
| - | - | - |
| `persistence` | Same as the flag instance | Tells the SDK whether to read the distinct ID from a cookie or from local storage. If it doesn't match, the tracking instance looks in the wrong place, doesn't find the flag instance's distinct ID, and creates a new one. Its events then won't match the exposure event. |
| `persistence_name` | Same as the flag instance, or unset in both | Sets the name of the cookie or local storage entry that holds the distinct ID. A different name points the tracking instance at a different entry, so it creates its own distinct ID. |

### Set up Path B

**1. Initialize the flag instance before the consent banner loads**

```javascript theme={"system"}
mixpanel.init('YOUR_PROJECT_TOKEN', {
  flags: true,
  batch_requests: true,
  batch_autostart: false,
  persistence: 'localStorage',
}, 'preconsent');
```

Replace `YOUR_PROJECT_TOKEN` with the token from your project settings. The third argument names the instance, so you reach it as `mixpanel.preconsent`. Don't name an instance `flags`, since `mixpanel.flags` is already the flags API.

**2. Read the flag from the flag instance**

```javascript theme={"system"}
const variant = await mixpanel.preconsent.flags.get_variant_value('YOUR_FLAG_KEY', 'control');
```

Replace `YOUR_FLAG_KEY` with the flag key from the flag's page in Mixpanel. The exposure event waits in the queue.

If you load the SDK from the CDN snippet, the library loads asynchronously, and `mixpanel.preconsent` doesn't exist until it finishes. Read flags inside the `loaded` callback of the flag instance's `init()` options. The callback receives the flag instance, so use its `flags` property directly:

```javascript theme={"system"}
mixpanel.init('YOUR_PROJECT_TOKEN', {
  flags: true,
  batch_requests: true,
  batch_autostart: false,
  persistence: 'localStorage',
  loaded: async function (preconsent) {
    const variant = await preconsent.flags.get_variant_value('YOUR_FLAG_KEY', 'control');
  },
}, 'preconsent');
```

If you import the SDK from npm, you can call `mixpanel.preconsent.flags` right after `init()`.

**3. When the visitor accepts, initialize the tracking instance with the same storage settings**

```javascript theme={"system"}
mixpanel.init('YOUR_PROJECT_TOKEN', {
  persistence: 'localStorage',
}, 'tracking');
```

The tracking instance reads the distinct ID the flag instance stored. If you load the tracking instance from a tag manager, set the same `persistence` and `persistence_name` values in the tag's init options.

**4. Send the flag instance's queued events**

```javascript theme={"system"}
// Run when the visitor accepts the banner.
mixpanel.tracking.opt_in_tracking();
mixpanel.preconsent.start_batch_senders();

// Run on every page load where the visitor already accepted.
mixpanel.preconsent.start_batch_senders();
```

Both instances use the same project token, so they share one event queue in local storage. Once the tracking instance loads, it can also send the exposure event from that queue. If both instances send it, Mixpanel keeps one copy, because it drops events that repeat the same event name, time, distinct ID, and `$insert_id`.

`opt_in_tracking()` clears the opt-out that `opt_out_tracking()` saved if the visitor declined earlier and now accepts. The opt-out is stored per project token, so it covers both instances, and one call clears it for both. Without it, their events stay blocked. It also sends an `$opt_in` event. `start_batch_senders()` only lasts for the current page, so call it on every page load where consent is already stored, and initialize the tracking instance on those page loads too.

**5. When the visitor declines, stop the flag instance from storing data**

```javascript theme={"system"}
mixpanel.preconsent.opt_out_tracking();
```

This deletes the queued exposure event and stops storing the distinct ID.

> [!NOTE]
>
> If you already know the visitor's ID before consent, for example a logged-in user ID from your own system, you can pass it in the flag context so the flag request uses that ID: `flags: { context: { distinct_id: 'YOUR_USER_ID' } }`. A `distinct_id` or `device_id` in `context` replaces the value the SDK would send in the flag request only. It doesn't change the ID stored by either instance, so the exposure event and later events still carry the stored ID. To make them match, call `identify('YOUR_USER_ID')` on both instances, for example `mixpanel.preconsent.identify('YOUR_USER_ID')` and, after consent, `mixpanel.tracking.identify('YOUR_USER_ID')`.

### Verify Path B

1. Open your site in a private browser window and don't answer the consent banner.
2. In the **Network** tab, you should see a request to `/flags/` and no request to `/track/`.
3. Reload the page. In the console, `mixpanel.preconsent.get_distinct_id()` should return the same value as before the reload.
4. Accept the consent banner. In the console, `mixpanel.tracking.get_distinct_id()` should return the same value as `mixpanel.preconsent.get_distinct_id()`.
5. You should see a request to `/track/` that includes `$experiment_started`.

If the two instances return different distinct IDs, go to [Troubleshooting](#troubleshooting).

## Troubleshooting

### The distinct ID changes on every page load

`opt_out_tracking_by_default` is on, or the browser holds an opt-out from an earlier visit. Remove `opt_out_tracking_by_default` from the init options. To test again, clear the site's data in the browser, which removes the stored `__mp_opt_in_out_YOUR_PROJECT_TOKEN` status.

### The visitor gets no variant before consent

`consent_mode: 'require_consent'` is set, which blocks the flag request until `opt_in_tracking()`. Remove it. If it's not set, check that `flags` is in the init options.

### Events send before the visitor accepts

Check these causes:

* `batch_autostart` isn't `false` on the instance that tracks the exposure. Set it to `false`.
* A `track()` call passes `{send_immediately: true}`, which skips the queue. Remove that option from events you track before consent.
* The browser can't use local storage. The SDK then turns off queueing, sends each event right away, and logs `Turning off Mixpanel request-queueing` to the console.
* Saving to the queue failed, for example because local storage is full. The SDK sends that event right away instead of dropping it.

If no event can leave the device before consent, test local storage before you read the flag, and show the default experience when the test fails. Skipping `get_variant_value()` means no exposure event is tracked:

```javascript theme={"system"}
function canUseLocalStorage() {
  try {
    const key = '__mp_storage_test';
    window.localStorage.setItem(key, '1');
    window.localStorage.removeItem(key);
    return true;
  } catch (e) {
    return false;
  }
}

// In Path B, use mixpanel.preconsent.flags.get_variant_value(...)
const variant = canUseLocalStorage()
  ? await mixpanel.flags.get_variant_value('YOUR_FLAG_KEY', 'control')
  : 'control';
```

The check only tests local storage at the moment it runs. If storage fills up afterward, a later save to the queue can still fail, and that event sends right away.

### The flag instance and tracking instance have different distinct IDs

The instances use different `persistence` or `persistence_name` values, so each stores its own identity. Set the same values in both init calls, including in the tag manager tag that loads the tracking instance.

## Next steps

* [Implement Feature Flags (Web)](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript/javascript-flags.md) for flag context, persistence, and exposure event details.
* [Opt out of tracking](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript#opt-out-of-tracking) in the JavaScript SDK reference.
* [Protecting user data](https://docs.mixpanel.com/docs/privacy/protecting-user-data.md) for other privacy controls.


## Related topics

- [Implement Feature Flags (Web)](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript/javascript-flags.md)
- [Mixpanel SDKs: Javascript](https://docs.mixpanel.com/docs/tracking-methods/sdks/javascript.md)
- [Feature Flags](https://docs.mixpanel.com/docs/featureflags.md)
