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

# Real-Time Triggers

> React to cohort changes with trigger(), segment(), segments(), and query()

The SDK provides methods to check cohort membership and react to changes in real-time, enabling dynamic personalization and targeting.

<CardGroup cols={4}>
  <Card title="trigger()" href="#trigger" icon="bell" />

  <Card title="segment()" href="#segment" icon="user" />

  <Card title="segments()" href="#segments" icon="users" />

  <Card title="query()" href="#query" icon="magnifying-glass" />
</CardGroup>

## Overview

Real-time triggers enable:

* **Personalization** based on cohort membership
* **Dynamic content** that updates as users qualify for cohorts
* **Conditional logic** for features, ads, and experiences
* **Real-time reactions** to cohort entry and exit

## trigger()

React to cohort entry and exit events in real-time. The handler fires whenever the user's membership in the specified segment changes.

### Usage

```javascript theme={"dark"}
permutive.trigger(segmentCode, parameterName, handler);
```

### Parameters

| Parameter       | Type     | Description                                                              |
| --------------- | -------- | ------------------------------------------------------------------------ |
| `segmentCode`   | number   | The cohort ID to watch                                                   |
| `parameterName` | string   | Parameter name (typically `"result"`)                                    |
| `handler`       | function | Callback on segment transitions (receives object with `result` property) |

### Example

```javascript theme={"dark"}
// React when user enters or exits a cohort
permutive.trigger(1010, 'result', function(obj) {
  if (obj.result) {
    // User just entered the cohort
    showEmailSubscriptionPopup();
    permutive.track('ShownEmailSubscriptionPopup', {});
  } else {
    // User exited the cohort
    hideEmailSubscriptionPopup();
  }
});
```

<Info>
  The handler receives `{ result: true }` when the user **enters** the segment and `{ result: false }` when they **exit**. For many segments (e.g., "5+ pageviews"), once a user qualifies they typically stay qualified, so you may only see the entry event. To check current membership at any time, use `permutive.segment()`.
</Info>

### Trigger Patterns

<Tabs>
  <Tab title="Personalization">
    ```javascript theme={"dark"}
    // Show personalized content when user qualifies
    permutive.trigger(12345, 'result', function(obj) {
      if (obj.result) {
        document.getElementById('premium-section').style.display = 'block';
        document.getElementById('standard-section').style.display = 'none';
      }
    });
    ```
  </Tab>

  <Tab title="Feature Flags">
    ```javascript theme={"dark"}
    // Enable beta features for beta testers cohort
    permutive.trigger(54321, 'result', function(obj) {
      if (obj.result) {
        enableBetaFeatures();
      }
    });
    ```
  </Tab>

  <Tab title="Messaging">
    ```javascript theme={"dark"}
    // Show targeted message when user enters cohort
    permutive.trigger(98765, 'result', function(obj) {
      if (obj.result) {
        showNotification('Special offer just for you!');
      }
    });
    ```
  </Tab>
</Tabs>

## segment()

Check if the user is in a specific cohort.

### Usage

```javascript theme={"dark"}
permutive.segment(segmentCode, handler);
```

### Parameters

| Parameter     | Type     | Description                  |
| ------------- | -------- | ---------------------------- |
| `segmentCode` | number   | The cohort ID to check       |
| `handler`     | function | Callback with boolean result |

### Example

```javascript theme={"dark"}
// Check if user is in cohort 12345
permutive.segment(12345, function(inCohort) {
  if (inCohort) {
    console.log('User is in cohort 12345');
  } else {
    console.log('User is NOT in cohort 12345');
  }
});
```

### Promise Form

```javascript theme={"dark"}
permutive.segment(12345)
  .then(function(inCohort) {
    console.log('In cohort:', inCohort);
  });
```

### Segment Patterns

<Tabs>
  <Tab title="Conditional Content">
    ```javascript theme={"dark"}
    // Show content based on cohort membership
    permutive.segment(12345, function(isPremium) {
      if (isPremium) {
        renderPremiumArticle();
      } else {
        renderPaywall();
      }
    });
    ```
  </Tab>

  <Tab title="A/B Testing">
    ```javascript theme={"dark"}
    // Use cohort for A/B test assignment
    permutive.segment(11111, function(inTestGroup) {
      if (inTestGroup) {
        runVariantB();
      } else {
        runVariantA();
      }
    });
    ```
  </Tab>

  <Tab title="Analytics">
    ```javascript theme={"dark"}
    // Tag analytics with cohort membership
    permutive.segment(12345, function(inCohort) {
      analytics.identify({
        is_premium_user: inCohort
      });
    });
    ```
  </Tab>
</Tabs>

## segments()

Get all cohorts the user belongs to.

### Usage

```javascript theme={"dark"}
permutive.segments(handler, type);
```

### Parameters

| Parameter | Type     | Description                                                              |
| --------- | -------- | ------------------------------------------------------------------------ |
| `handler` | function | Callback with segments array                                             |
| `type`    | string   | Optional: 'all' (default) or platform-specific ('dfp', 'appnexus', etc.) |

### Example

```javascript theme={"dark"}
// Get all segments
permutive.segments(function(segments) {
  console.log('All segments:', segments);
  // Output: [12345, 67890, 11111, ...]
});

// Get DFP-activated segments
permutive.segments(function(segments) {
  console.log('DFP segments:', segments);
}, 'dfp');
```

### Promise Form

```javascript theme={"dark"}
permutive.segments()
  .then(function(segments) {
    console.log('Segments:', segments);
  });
```

### Segments Patterns

<Tabs>
  <Tab title="Ad Targeting">
    ```javascript theme={"dark"}
    // Pass segments to ad server
    permutive.segments(function(segments) {
      googletag.cmd.push(function() {
        googletag.pubads().setTargeting('permutive', segments);
      });
    }, 'dfp');
    ```
  </Tab>

  <Tab title="Analytics">
    ```javascript theme={"dark"}
    // Send segments to analytics
    permutive.segments(function(segments) {
      analytics.track('PageView', {
        permutive_cohorts: segments,
        cohort_count: segments.length
      });
    });
    ```
  </Tab>

  <Tab title="Personalization">
    ```javascript theme={"dark"}
    // Personalize based on any matching cohort
    permutive.segments(function(segments) {
      var premiumCohorts = [12345, 67890, 11111];
      var isPremium = premiumCohorts.some(function(id) {
        return segments.includes(id);
      });

      if (isPremium) {
        showPremiumExperience();
      }
    });
    ```
  </Tab>
</Tabs>

## query()

Execute advanced queries against cohort data.

### Usage

```javascript theme={"dark"}
permutive.query(queryCode, handler);
```

<Warning>
  The `query()` method is reserved for future functionality and currently returns `{ result: false }`. Use `segment()` to check individual cohort membership or `segments()` to get all cohorts.
</Warning>

## ready()

Wait for SDK initialization or realtime data before checking cohorts.

### Usage

```javascript theme={"dark"}
permutive.ready(callback, stage);
```

### Parameters

| Parameter  | Type     | Description                           |
| ---------- | -------- | ------------------------------------- |
| `callback` | function | Called when stage is reached          |
| `stage`    | string   | 'initialised' (default) or 'realtime' |

### Example

```javascript theme={"dark"}
// Wait for SDK initialization
permutive.ready(function() {
  console.log('SDK is ready');
});

// Wait for realtime cohort data
permutive.ready(function() {
  permutive.segments(function(segments) {
    // Segments are now populated
    console.log('Realtime segments:', segments);
  });
}, 'realtime');
```

### Stages

| Stage         | When Fires                               |
| ------------- | ---------------------------------------- |
| `initialised` | SDK has loaded and initialized           |
| `realtime`    | Real-time cohort data has been processed |

### Ready Patterns

<Tabs>
  <Tab title="Wait for Cohorts">
    ```javascript theme={"dark"}
    // Ensure cohort data is available
    permutive.ready(function() {
      permutive.segments(function(segments) {
        initializeTargeting(segments);
      });
    }, 'realtime');
    ```
  </Tab>

  <Tab title="Safe Initialization">
    ```javascript theme={"dark"}
    // Initialize components after SDK ready
    permutive.ready(function() {
      setupPersonalization();
      initializeAnalytics();
      loadAdTargeting();
    });
    ```
  </Tab>
</Tabs>

## readyWithTimeout()

If you need to delay critical actions (like ad requests) until Permutive is ready, use `readyWithTimeout` to set a maximum wait time. This ensures your page functions even if the SDK takes longer than expected to load.

### Setup

First, add the `readyWithTimeout` function to your Permutive tag:

```javascript theme={"dark"}
window.permutive.readyWithTimeout = function(e, i, t) {
  var u = !1,
      n = function() {
        u || (e(), u = !0)
      };
  (t = t || 1/0) !== 1/0 && window.setTimeout(n, t),
  permutive.ready(n, i)
};
```

### Usage

```javascript theme={"dark"}
permutive.readyWithTimeout(callback, stage, timeoutMs);
```

### Parameters

| Parameter   | Type     | Description                                                 |
| ----------- | -------- | ----------------------------------------------------------- |
| `callback`  | function | Called when ready or timeout is reached                     |
| `stage`     | string   | 'initialised' or 'realtime'                                 |
| `timeoutMs` | number   | Maximum milliseconds to wait before calling callback anyway |

### Example

```javascript theme={"dark"}
// Wait up to 1500ms for realtime data, then proceed regardless
window.permutive.readyWithTimeout(function() {
  console.log('Permutive is ready (or timed out)');
  // Proceed with ad requests
  initializeAdRequests();
}, 'realtime', 1500);
```

<Info>
  Using `readyWithTimeout` is strongly recommended when delaying ad requests, as it ensures ads will still load even if there's a network issue with the Permutive SDK.
</Info>

## Combining Methods

### Check Multiple Cohorts

```javascript theme={"dark"}
function checkUserStatus() {
  var status = {
    isPremium: false,
    isEngaged: false,
    isNewUser: false
  };

  var checks = 3;
  var complete = function() {
    checks--;
    if (checks === 0) {
      applyPersonalization(status);
    }
  };

  permutive.segment(12345, function(result) {
    status.isPremium = result;
    complete();
  });

  permutive.segment(67890, function(result) {
    status.isEngaged = result;
    complete();
  });

  permutive.segment(11111, function(result) {
    status.isNewUser = result;
    complete();
  });
}
```

### Watch and Initial Check

```javascript theme={"dark"}
// Check initial state AND watch for when segment becomes true
function setupCohortTracking(cohortId, onEnter) {
  // Initial check
  permutive.segment(cohortId, function(inCohort) {
    if (inCohort) {
      onEnter();
    }
  });

  // Watch for entry (fires once when segment becomes true)
  permutive.trigger(cohortId, 'result', function(obj) {
    if (obj.result) {
      onEnter();
    }
  });
}

// Usage
setupCohortTracking(12345, function() {
  showPremiumContent();
});
```

## Timing Considerations

### Why Use ready()?

```javascript theme={"dark"}
// Without ready() - segments might be empty
permutive.segments(function(segments) {
  console.log(segments);  // Might be []
});

// With ready('realtime') - segments are populated
permutive.ready(function() {
  permutive.segments(function(segments) {
    console.log(segments);  // [12345, 67890, ...]
  });
}, 'realtime');
```

### Trigger Timing

Triggers fire whenever segment membership changes on the current page:

* `{ result: true }` when user **enters** the segment
* `{ result: false }` when user **exits** the segment

```javascript theme={"dark"}
// This fires on segment transitions
permutive.trigger(12345, 'result', function(obj) {
  if (obj.result) {
    // User entered cohort 12345
  } else {
    // User exited cohort 12345
  }
});
```

<Info>
  Triggers only fire for segment transitions caused by events tracked on the current page via the `track` method. For checking a user's current cohort membership at any time, use `permutive.segment()` instead.
</Info>

## Debugging

Enable debug mode to see cohort activity:

```
?__permutive.loggingEnabled=true
```

Console output:

```
[Permutive] Segments: [12345, 67890, 11111]
[Permutive] User entered segment: 12345
[Permutive] User exited segment: 67890
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="segments() returns empty array">
    **Problem:** No cohorts returned even though user should qualify.

    **Solutions:**

    * Use `ready('realtime')` before calling `segments()`
    * Verify events are being tracked
    * Check cohorts are configured and active in dashboard
    * Ensure consent is granted (if `consentRequired: true`)
    * Allow time for cohort processing
  </Accordion>

  <Accordion title="trigger() not firing">
    **Problem:** Trigger callback not being called.

    **Solutions:**

    * Verify cohort ID is correct
    * Check that cohort rules would qualify the user
    * Enable debug mode to see cohort changes
    * Ensure SDK is initialized before setting trigger
  </Accordion>

  <Accordion title="segment() always returns false">
    **Problem:** User should be in cohort but check returns false.

    **Solutions:**

    * Verify cohort ID matches dashboard
    * Check cohort is active (not paused/archived)
    * Ensure user meets cohort criteria
    * Use `ready('realtime')` to ensure data is loaded
  </Accordion>

  <Accordion title="Stale cohort data">
    **Problem:** Cohort membership not updating.

    **Solutions:**

    * Refresh page to trigger re-evaluation
    * Verify new events are being tracked
    * Use `trigger()` with `'result'` parameter for real-time updates
    * Check for SDK errors in console
  </Accordion>
</AccordionGroup>

## Related Documentation

<CardGroup cols={2}>
  <Card title="Cohorts & Activations" icon="users" href="/sdks/web/javascript-sdk/core-concepts/cohorts-and-activations">
    Understanding cohort system
  </Card>

  <Card title="Event Tracking" icon="bolt" href="/sdks/web/javascript-sdk/features/event-tracking">
    Events that power cohorts
  </Card>

  <Card title="Google Ad Manager" icon="rectangle-ad" href="/sdks/web/javascript-sdk/integrations/google-ad-manager">
    Use cohorts for ad targeting
  </Card>

  <Card title="Custom Cohorts" icon="users" href="/products/signals/cohorts/custom">
    Build cohorts in dashboard
  </Card>
</CardGroup>
