Skip to main content

A/B Testing & Experiments

The SDK ships with a built-in A/B testing client that requests group assignments from the B2Metric experiments service, caches them on the client, and automatically emits exposure events so downstream behaviour can be attributed to the assigned variant.

How It Works

  1. The site calls b2mAssignExperiment([...experimentIds]) with the experiments it wants the current user evaluated for.
  2. The SDK first checks localStorage for a fresh assignment (within the configured TTL — default 24 h).
  3. For any experiment with a missing or expired assignment, a single batched POST is sent to the experiments endpoint.
  4. The response is cached and the variants are returned to the caller so the page can render the matching UI.
  5. The first time a user is exposed to an experiment in a given browser session, an ab_test_view event is emitted automatically.
  6. If the API call fails, the SDK falls back to whatever cached assignments exist (fail-soft) — the experience never breaks because the experiments backend is unreachable.
PropertyStorageKeyLifetime
Group assignmentslocalStorageb2m_experiment_assignmentsUntil TTL expiry
Per-session exposuresessionStorageb2m_experiment_exposed_in_sessionUntil tab is closed

Quick Start

// Wait until the SDK is ready (fingerprint resolved)
await window.b2mReady;

// Resolve assignments for one or more experiments
const assignments = await b2mAssignExperiment(
['exp-checkout-v2', 'exp-pricing-banner'],
{ country: 'TR', device: 'mobile', tier: 'premium' }
);

// assignments → [
// { ExperimentId: 'exp-checkout-v2', GroupId: 'g_2', GroupName: 'variant_a' },
// { ExperimentId: 'exp-pricing-banner', GroupId: 'g_1', GroupName: 'control' }
// ]

if (b2mGetExperimentGroup('exp-checkout-v2') === 'variant_a') {
renderNewCheckout();
} else {
renderClassicCheckout();
}

For experiments evaluated on every page load, call b2mAssignExperiment once after b2mReady resolves; subsequent reads use the synchronous b2mGetExperimentGroup / b2mGetExperimentAssignment helpers and never hit the network.

API Reference

MethodTypeDescription
b2mAssignExperiment(experimentIds, properties?, options?)asyncResolve group assignments. Returns Promise<Array<{ ExperimentId, GroupId, GroupName }>>. Pass { forceRefresh: true } in options to bypass the cache.
b2mGetExperimentGroup(experimentId)syncReturn the cached group name (e.g. 'variant_a') or null if the user has not been assigned yet.
b2mGetExperimentAssignment(experimentId)syncReturn the full cached assignment { ExperimentId, GroupId, GroupName } or null.
b2mSetUserId(externalId)syncSet the customer-supplied user identifier (e.g. CRM PK). Clears experiment cache so the new identity gets re-evaluated.
// Force a re-fetch (e.g. after a user signs in and targeting changes)
await b2mAssignExperiment(['exp-pricing-banner'], { tier: 'premium' }, { forceRefresh: true });

Targeting Properties

The second argument to b2mAssignExperiment is a free-form object that the experiments backend uses to evaluate targeting rules. Common properties:

PropertyExampleUse case
country'TR'Geo targeting
device'mobile'Form factor segmentation
tier'premium'Plan / loyalty segmentation
is_new_usertrueFirst-session vs returning users
language'tr-TR'Locale-specific variants

Properties are passed through verbatim to the experiments service; you can send any custom key your experiment rules expect.

Identity & User Switching

Group assignments are keyed on the user identifier. By default the SDK uses the device fingerprint, which means the same browser keeps the same group across sessions. When a user signs in or out, call b2mSetUserId:

// On login — promote the customer's internal user ID to the canonical identity
b2mSetUserId('user_482910');

// On logout — wipe the customer-supplied identity (returns to fingerprint-based ID)
b2mSetUserId(null);

b2mSetUserId automatically clears the experiment cache so the next b2mAssignExperiment call re-evaluates the user under the new identity rather than inheriting the previous user's groups.

Exposure Tracking (ab_test_view)

The first time the SDK returns an assignment for an experiment in a browser session, it emits an ab_test_view event automatically. This is the event analytics dashboards should join against to compute per-variant conversion.

{
"event_name": "ab_test_view",
"event_params": [
{ "key": "experiment_id", "value": "exp-checkout-v2" },
{ "key": "group_id", "value": "g_2" },
{ "key": "group_name", "value": "variant_a" }
]
}

Deduplication: each (session, experiment) pair fires ab_test_view exactly once. Subsequent b2mGetExperimentGroup calls in the same tab do not re-emit. When the tab is closed and reopened, a fresh exposure is recorded — this lets the backend distinguish unique sessions exposed to a variant from raw assignment lookups.

Configuration

ParameterTypeDefaultDescription
experimentApiUrlstringhttps://tracker.b2metric.com/experiments/assignA/B test assignment endpoint. Override only when self-hosting the experiments service.
experimentCacheTtlnumber86400000 (24 h, in ms)Time before a cached assignment is considered stale and a fresh fetch is triggered. Lower this if you flip winner groups frequently.

The experimentCacheTtl and experimentApiUrl options are configured via b2mInit() only; they are not exposed as data-* attributes on the script tag.

window.b2mInit({
apiKey: 'YOUR_API_KEY',
experimentApiUrl: 'https://tracker.b2metric.com/experiments/assign',
experimentCacheTtl: 60 * 60 * 1000 // 1 hour
});