# setAnalyticsConsent()

Manually sets the visitor's analytics consent state. **Only needed if you use a custom consent management platform (CMP) that does not integrate with Shopify's Customer Privacy API.** If your store relies on Shopify's built-in privacy tools, Shoplift handles consent automatically and you can skip this method entirely.

### Signature

```typescript
window.shoplift.setAnalyticsConsent(consent: boolean): Promise<void>
```

### Parameters

| Parameter | Type      | Required | Description                                         |
| --------- | --------- | -------- | --------------------------------------------------- |
| `consent` | `boolean` | Yes      | `true` to allow analytics tracking, `false` to deny |

### Returns

`Promise<void>` — resolves when the consent preference has been applied. This method handles errors internally and will not reject.

### When to Use This Method

#### Use when you have:

* A third-party consent management platform (OneTrust, Cookiebot, TrustArc, etc.) that is **not** integrated with Shopify's Customer Privacy API
* A custom-built consent solution
* Region-specific consent requirements that Shopify doesn't handle

#### Do not use when:

* Your store uses Shopify's standard Customer Privacy API (consent is handled automatically)
* You're using Shopify's built-in cookie banner
* You have no consent management system at all

### Basic Usage

```javascript
// Grant analytics consent
await window.shoplift.setAnalyticsConsent(true);

// Revoke analytics consent
await window.shoplift.setAnalyticsConsent(false);
```

### How Consent Affects Shoplift

Understanding the distinction between test assignment and analytics tracking is important:

| Concern                | Consent Required? | Details                                                                      |
| ---------------------- | ----------------- | ---------------------------------------------------------------------------- |
| **Test assignment**    | No                | Visitors are always assigned to a variant to ensure a consistent experience. |
| **Analytics tracking** | Yes               | Test data is only recorded in Shoplift's analytics when consent is granted.  |
| **Data collection**    | Yes               | Visitor behavioral data respects the consent state in real-time.             |

This means a visitor will always see the correct variant, but their participation is only reflected in your test results if they've consented to analytics tracking.

### Internal Behavior

#### When `consent = true`:

1. Updates `consentApproved` to `true`
2. Marks `hasConsentInteraction` as `true`
3. Syncs all queued events to server (including events queued before consent was granted)
4. Persists analytics data to localStorage

#### When `consent = false`:

1. Updates `consentApproved` to `false`
2. Marks `hasConsentInteraction` as `true`
3. Clears the analytics event queue
4. Prevents new analytics events from being queued
5. On next page load, removes `Shoplift_Analytics` from localStorage
6. Retains test assignments (`Shoplift_Essential` remains in localStorage)

### Integration Pattern

The general pattern for connecting any CMP to Shoplift:

```javascript
function syncConsentWithShoplift(hasConsent, maxAttempts = 50) {
  let attempts = 0;

  function trySync() {
    if (window.shoplift) {
      window.shoplift.setAnalyticsConsent(hasConsent);
    } else if (attempts < maxAttempts) {
      attempts++;
      setTimeout(trySync, 100);
    } else {
      console.warn('Shoplift did not load — consent not synced.');
    }
  }

  trySync();
}
```

#### Mapping CMP Categories

Different CMPs use different category names. Shoplift only needs the **analytics / statistics / performance** category:

| CMP Category                         | Maps to Shoplift?     | Notes                                        |
| ------------------------------------ | --------------------- | -------------------------------------------- |
| Analytics / Statistics / Performance | **Yes** — pass `true` | This is the category Shoplift needs.         |
| Marketing / Targeting                | No                    | Shoplift doesn't do remarketing.             |
| Functional / Preferences             | No                    | Test assignment works regardless of consent. |
| Strictly Necessary                   | No                    | Core functionality always available.         |

### Error Handling

This method handles errors internally — it will always resolve and never reject. If an error occurs during the consent update (e.g., a network failure when syncing events), Shoplift logs the error and continues with the previous consent state. The visitor's test experience is not affected.

```javascript
// No try/catch needed, but safe to use if you prefer
await window.shoplift.setAnalyticsConsent(true);
```

### Timing Considerations

* **Call early**: Set consent as soon as it's available from your CMP.
* **Events queue before consent**: Before the visitor makes a consent decision, Shoplift queues analytics events. When consent is granted, all queued events are sent — so no data is lost from the pre-consent window.
* **Denial clears the queue**: If consent is denied, queued events are discarded and no new events are queued. If the visitor later grants consent, tracking resumes from that point forward — events from the denied period are not recoverable.
* **Listen for changes**: If the visitor updates their consent preferences mid-session, call `setAnalyticsConsent()` again with the new value.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.shoplift.ai/api-reference/reference/setanalyticsconsent.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
