@flash-analytics/web
v2.2.0
Published
## Experiment Auto-Assignment
Downloads
1,427
Readme
Flash Analytics Web SDK
Experiment Auto-Assignment
Enable captureVariants to automatically keep a local cache of experiment assignments in sync throughout the session lifecycle.
import { FlashAnalytics } from '@flash-analytics/web';
const analytics = new FlashAnalytics({
appId: 'your-app-id',
captureVariants: true,
// or with options:
// captureVariants: {
// includeInternalProperties: true,
// onAssignmentsChanged: (assignments) => {},
// },
});How the local cache is maintained
Session start (new session ID received from /track):
Fetches ALL experiments — profile, session, and event-triggered — and replaces the entire local store. Only fires when the session ID actually changes; repeated track() calls on the same session do not re-fetch.
After identify():
Fetches only profile-mode experiments (user identity just changed) and replaces only the profile-mode entries in the store. Session and event assignments are left untouched.
Session expiry: Removes only session-mode assignments from the store when the cached session TTL runs out. Profile and event assignments survive.
Reading assignments
// All cached assignments — no API call
const all = analytics.getAllExperiments();
// Single experiment — checks cache first, falls back to API if not found
const assignment = await analytics.getExperimentById('checkout-cta');
console.log(assignment?.variantName);Local store state at each lifecycle point
| Moment | Profile assignments | Session assignments | Event assignments |
|---|---|---|---|
| After first track() (new session) | fetched | fetched | fetched |
| After identify() | re-fetched | unchanged | unchanged |
| After session expiry | unchanged | removed | unchanged |
| After next track() (new session) | re-fetched | re-fetched | re-fetched |
Manual assignment
const assignments = await analytics.autoAssignExperiments();
const variant = await analytics.assignExperiment('checkout-cta');Auto Error Capture
Enable captureErrors to automatically capture uncaught exceptions and unhandled promise rejections and send them as js_error / unhandled_promise_rejection events:
import { FlashAnalytics } from '@flash-analytics/web';
const analytics = new FlashAnalytics({
appId: 'your-app-id',
captureErrors: true, // js_error + unhandled_promise_rejection
capturePageViews: true, // page_view
});No extra credentials needed — the SDK uses its own appId / secretKey / endpoint.
Session access
After a track(...) call, read the current session from the SDK with a single method:
import { FlashAnalytics } from '@flash-analytics/web';
const analytics = new FlashAnalytics({
appId: 'your-app-id',
});
await analytics.track('page_view');
const session = analytics.getSession();
console.log(session?.id);
console.log(session?.estimatedExpiresAt);
console.log(session?.estimatedTtlMs);getSessionId() still works, but getSession() is the preferred API when you also need expiry information.
