Skip to content

JavaScript SDK

@controlvar/js-sdk (v0.3.0) is the JavaScript/TypeScript client for the Controlvar public API: experiment assignment, feature flag evaluation and event tracking for Node >= 18 and browsers. Zero runtime dependencies — it uses the global fetch.

By default, flag evaluation and experiment assignment are decided by the server: every call goes to the public API with your X-API-Key, the server buckets the user (sticky per user + experiment), and the SDK caches the answer per user + key. In server-side code you can opt in to local evaluation (evaluation: 'local'): flags are then answered in-process from the server's ruleset, with the server's answers, and experiments stay on the server.

Source: sdk/js. For React apps use the React SDK; for edge runtimes the Edge SDK; for the vendor-neutral API the OpenFeature provider, which delegates to this package.

CI runs this SDK's contract smoke against a real API: js is in the sdks: list of the SDK Live Contract job in pr-qa-gate.yml.


Installation

If you installed @getexperimently/js-sdk, the name this package had before the project was renamed, uninstall it and install @controlvar/js-sdk.

The @controlvar/js-sdk package is on npm. 0.3.0 is a beta release.

npm install @controlvar/js-sdk@0.3.0

To work on the SDK itself, build it from a clone of this repository instead. npm pack writes controlvar-js-sdk-0.3.0.tgz:

git clone https://github.com/Controlvar/controlvar.git
cd controlvar/sdk/js
npm ci && npm run build && npm pack

Then, in your app, install the packed tarball:

npm install /path/to/controlvar/sdk/js/controlvar-js-sdk-0.3.0.tgz

CommonJS build (dist/index.js) with type declarations; import/require both work.


Quick start

If you set EXPERIMENTLY_API_KEY or EXPERIMENTLY_API_URL from an earlier version of these pages, set CONTROLVAR_API_KEY and CONTROLVAR_API_URL instead.

import { ExperimentationClient } from '@controlvar/js-sdk';

const client = new ExperimentationClient({
  apiUrl: 'http://localhost:8000',   // origin only; the SDK appends /api/v1/...
  apiKey: process.env.CONTROLVAR_API_KEY!,
});

const user = { userId: 'user-123', attributes: { country: 'US', plan: 'pro' } };

// Sticky experiment assignment (POST /api/v1/tracking/assign); attributes are sent as `context`
const assignment = await client.getAssignment('checkout_button_color', user);
assignment.variantName;     // 'control' | 'treatment'
assignment.configuration;   // the variant's configuration object, or null

// Or just the name — 'control' (defaultVariant) when assignment fails
const variant = await client.getVariant('checkout_button_color', user);

// Feature flag (GET /api/v1/feature-flags/evaluate/{key}?user_id=...&context=<url-encoded attributes>)
const { key, enabled, config, reason } = await client.evaluateFlag('dark_mode', user);
const isEnabled = await client.isFeatureEnabled('dark_mode', user);   // false on failure

// Track a conversion for one experiment (POST /api/v1/tracking/track)
await client.track('user-123', 'purchase', { value: 49.99, experimentKey: 'checkout_button_color' });

// Track without a key: sent to every experiment and flag answered for the user (see below)
await client.track('user-123', 'page_view', { properties: { page: '/checkout' } });

The block is TypeScript and uses top-level await, so it runs as an ES module. To run it as it is, save it as quick-start.mts in the project where you installed the package, set CONTROLVAR_API_KEY, and run it with node --experimental-strip-types quick-start.mts (Node 22.6 or later; it may print an ExperimentalWarning). As plain JavaScript, delete the ! after process.env.CONTROLVAR_API_KEY, save it as quick-start.mjs and run node quick-start.mjs.


Configuration (ClientConfig)

const client = new ExperimentationClient({
  apiUrl: 'https://api.example.com', // Required. Backend origin; trailing slashes are stripped.
  apiKey: 'eptk_...',                // Required. Sent as X-API-Key.
  timeoutMs: 5000,                   // Per-request timeout (default 5000)
  cacheTtlMs: 300_000,               // Successful evaluations/assignments reused per user + key (default 5 min)
  defaultVariant: 'control',         // Returned by getVariant when assignment fails (default 'control')
  fetch: customFetch,                // Optional custom fetch (tests, polyfills); defaults to globalThis.fetch
  onError: (err, operation) => {},   // Optional; called when track / trackBatch (or, in local mode, refresh / flush / evaluate) swallow a failure
  onExposure: (exposure) => {},      // Optional; called once per experiment exposure the server recorded (see Exposure hook)
  evaluation: 'server',              // 'server' (default) or 'local' (server-side only; see Local evaluation)
});
Field Type Default Description
apiUrl string — Backend origin, e.g. https://api.example.com; the SDK appends /api/v1/...
apiKey string — API key, sent as X-API-Key
timeoutMs number 5000 Per-request timeout (AbortController); also caps the 429 retry delay
cacheTtlMs number 300000 TTL of successful evaluations/assignments, per user + key; 0 caches nothing
defaultVariant string 'control' Variant name getVariant returns on failure
fetch typeof fetch global fetch Custom fetch implementation
onError (error: ExperimentationError, op: 'track' \| 'trackBatch' \| 'refresh' \| 'flush' \| 'evaluate' \| 'reportError' \| 'value' \| 'exposure') => void — Only way to observe swallowed failures; a throwing handler is itself swallowed. 'refresh', 'flush' and 'evaluate' occur only in local mode
onExposure (exposure: Exposure) => void — Called once each time the server enrols the user and the answer is not cached; see Exposure hook
evaluation 'server' \| 'local' 'server' 'local': answer flags in-process from GET /api/v1/sdk/ruleset; needs a key with the sdk:ruleset scope; throws in a browser
refreshIntervalMs number 30000 Local mode: ruleset refresh interval (minimum 5000, ±10% jitter)
maxStaleMs number none Local mode: evaluate on the server once the ruleset has not been refreshed for this long

The constructor throws a plain Error (apiKey is required / apiUrl is required) when either required field is missing, when evaluation is not 'server' or 'local', and when evaluation: 'local' is used in a browser.

UserContext

interface UserContext {
  userId: string;                       // stable id; the server buckets on it
  attributes?: Record<string, unknown>; // sent as `context` on assignment and on flag evaluation (targeting rules)
}

Keep userId the same for one person: the server buckets on it, and an id it has not seen is a new user to every experiment. If a visitor is anonymous until they sign in, give them an anonymous id of their own, and when they sign in, link it to their known id from your backend with alias: a known id with no assignment of its own is then answered the variant the anonymous id holds.

Targeting context

attributes is what the platform's targeting rules evaluate against, and what sets the user's segment in a breakdown. It is sent as context in the POST /api/v1/tracking/assign body and, when it is a non-empty object, as context=<url-encoded JSON> on GET /api/v1/feature-flags/evaluate/{flagKey} (and on getAllFlags(userId, attributes)), so a flag whose dashboard rule says os_version semver_gte 17.0.0 AND tier equals premium turns on only for matching users. Top-level keys are also reachable under user. / device. / app. aliases in rules (country matches user.country), and nested objects flatten to dotted keys ({ app: { version: '3.2.1' } } answers app.version).

Attributes are assumed stable per user: evaluations and assignments are cached by user + key only, so call clearCache() after changing a user's attributes.

An experiment that balances its split within groups reads its attribute from the top level of attributes only: { tier: 'gold' }, not { user: { tier: 'gold' } }.

getAssignment and evaluateFlag reject with ExperimentationError (code: 'INVALID_RESPONSE', user.userId is required) when userId is missing or empty; getVariant / isFeatureEnabled turn that into their safe default.


API

Method Signature Returns On failure
getAssignment (experimentKey, user: UserContext) => Promise<Assignment> { experimentKey, userId, variantId, variantName, isControl, configuration, assigned?, reason? } Rejects with ExperimentationError (404 when no experiment has the key, or for a draft with no control variant); an experiment that is not ACTIVE resolves to its control variant with assigned: false and reason its status
getVariant (experimentKey, user) => Promise<string> assignment.variantName defaultVariant ('control'); never rejects
evaluateFlag (flagKey, user) => Promise<FlagEvaluation> { key, enabled, config, reason?, value?, valueType? } (user.attributes sent as context) Rejects with ExperimentationError (404 for an unknown key); a flag that exists but is not ACTIVE resolves enabled: false, reason: "inactive"
isFeatureEnabled (flagKey, user) => Promise<boolean> evaluation.enabled false; never rejects
getStringValue (flagKey, user, defaultValue: string) => Promise<string> The string a string flag serves this user; see Flag values defaultValue; never rejects; onError(err, 'value')
getNumberValue (flagKey, user, defaultValue: number) => Promise<number> The number a number flag serves this user defaultValue; never rejects; onError(err, 'value')
getJsonValue <T>(flagKey, user, defaultValue: T) => Promise<T> A new copy of the object or array a json flag serves this user defaultValue; never rejects; onError(err, 'value')
getAllFlags (userId, attributes?) => Promise<Record<string, boolean>> { flagKey: enabled }; attributes sent as context; not cached, not part of the fan-out Rejects
track (userId, eventName, options?: TrackOptions) => Promise<void> — Never rejects; onError(err, 'track') when a request fails (network error or non-2xx). A 2xx answer is not inspected, so an entry the server refuses inside a 200 does not reach onError; trackBatch returns those
trackBatch (events: TrackEvent[]) => Promise<BatchResult> { successCount, failureCount, errors } Never rejects; a failed chunk counts all its events as failures and calls onError(err, 'trackBatch')
reportError (report: ErrorReport) => Promise<boolean> true when the server stored the report (201); see Reporting errors false; never rejects; onError(err, 'reportError')
fetchAssignments (userId, { activeOnly?: boolean } = { activeOnly: true }) => Promise<AssignmentRecord[]> Server-side assignment rows (raw objects); not cached Rejects
alias (anonymousId, userId) => Promise<boolean> true when this call stored the link, false when it was already stored; in the source tree only, see Linking an anonymous id to a known user id Rejects with ExperimentationError, with the server's status and body
getAssignments (userId) => Assignment[] Cached, unexpired assignments in assignment order (no network) —
getEvaluatedFlags (userId) => string[] Keys of cached, successfully evaluated flags (no network) —
getCachedFlags (userId) => FlagEvaluation[] Cached, unexpired flag evaluations for the user (no network); in local mode each carries source ('local' or 'server') —
clearCache () => void Drops both caches; keeps the keys a key-less track is sent to —
ready ({ timeoutMs? }?) => Promise<ReadyResult> { ok: true, rulesetVersion } or { ok: false, error }; { ok: true, rulesetVersion: null } at once in server mode Never rejects
status () => LocalEvaluationStatus { evaluation, ready, rulesetVersion, lastRefreshAt, lastError, serverEvaluatedFlags } —
close () => Promise<void> Local mode: stops the ruleset refresh and sends the remaining evaluation counts; later calls are evaluated by the server. A no-op in server mode Never rejects

Enrolment: assigned and reason

An Assignment also carries assigned and reason. assigned: false means the server did not enrol the user (reason is 'holdout', 'mutual_exclusion' or 'targeting') and returned the control variant so you render the default experience; no exposure was recorded. When you export exposures to a warehouse, exclude assignments with assigned: false: the user was not enrolled, and reason says why. A server that predates the fields sends neither, so assigned is undefined (never false). Decide deliberately how to treat those rows rather than dropping them with an assigned === true filter.

An experiment that is not ACTIVE answers every user with its control variant, assigned: false and reason set to its status ('draft', 'paused', 'completed' or 'archived').

TrackOptions: value? (number), properties? (sent as metadata), experimentKey?, featureFlagKey?, eventType? (defaults to the event name), timestamp? (Date or string, sent as ISO-8601), eventId? (sent as event_id, see Event ids). TrackEvent = TrackOptions & { userId, eventName }.

Tracking and the fan-out rule

  • With experimentKey and/or featureFlagKey: exactly one POST /api/v1/tracking/track.
  • Without a key: one POST /api/v1/tracking/batch (chunked at 100) containing one entry per experiment (experiment_key) and one per flag (feature_flag_key) this client answered for the user in the last 24 hours, whether or not the answer is still cached. This is what makes a single track(userId, 'purchase', …) count as a conversion for every experiment the user is in.
  • An experiment that is not running (its latest answer has reason draft, paused, completed or archived) gets no entry. An answer with assigned: false for holdout, mutual_exclusion or targeting keeps its entry: holdout results count those users' events.
  • An experiment whose assignment is later answered 404 loses its entry at once, so key-less events stop reaching it; any other failure (a 5xx, a network error) keeps it.
  • With nothing to attribute it to, the event is still sent: one POST /api/v1/tracking/track with no key. The server stores it as history, which counts in holdout results and as CUPED history, never in an experiment's results.
  • The keys live in this client's memory, for up to 10,000 users (the user answered least recently is dropped first). clearCache() keeps them, and another process does not have them. On a server, the process that records a purchase is often not the one that assigned the user, so pass experimentKey on conversions there.
  • trackBatch applies the same expansion to keyless entries (one with nothing to attribute it to is sent with no key), then sends everything in chunks of 100 and sums the server's success_count / failure_count / errors.

Conversions are matched to metrics by event name.

Event ids

eventId is your id for one event. The server stores an event sent again with the same event_id, user, experiment, flag and event name only once (see How events count). It needs a Controlvar server that includes the event_id change (#1640), which the platform release after 0.39.0 is to carry; an older server ignores the field and stores an event sent again a second time.

  • The SDK makes no id. An event without an eventId is sent without an event_id, and one sent again is stored and counted again. Make the id once, when the event happens, for example with crypto.randomUUID(), and give the same one each time you send that event.
  • eventId: undefined, null and '' send no event_id. The SDK does not check the id: the server refuses (422) one of more than 255 characters or one holding NUL, and in a batch one such event refuses the whole request.
  • An event fanned out to several experiments and flags carries the same event_id in every entry, so it counts once in each of them. In trackBatch, each event keeps its own eventId.
  • A 429 that is retried sends the same request again, so the same event_id.
  • A request that times out is not sent again by the SDK, and the server may have stored it. Send it again with the same eventId and it is stored once.

Reporting errors

reportError(report) sends one POST /api/v1/tracking/errors for an error that happened while a flag or experiment was active, in either evaluation mode. report is an ErrorReport: errorType and message, and optionally featureFlagKey, experimentKey, userId, stackTrace, metadata and timestamp. The server needs featureFlagKey or experimentKey, and the SDK sends the report without checking it.

  • true means the server stored the report: it answered 201. false means it did not: any other answer (401, 404, 422, a 429 after its one retry, 5xx) or a network failure, which is also passed to onError(err, 'reportError'). reportError never rejects.
  • A stored report counts toward the flag's error rate and automatic rollback only when it names that flag in featureFlagKey (a report with only experimentKey is stored, but counts toward no flag's rate) and the client's key is a server-side key: one with the sdk:ruleset scope, created by a user who can change feature flags. A report sent with any other production key is stored too and still resolves true; the flag's safety check shows those reports as uncounted_error_count. See Which errors count.
  • The error rate divides the counted errors by the flag's evaluations in the check's 15-minute window. With no evaluations in the window it reads 0, so an error-rate threshold cannot fire: in local mode the counts reach the server every 60 seconds and on close().

Linking an anonymous id to a known user id: alias

alias is in the source tree only: it is not in the published @controlvar/js-sdk 0.3.0, and arrives with the package's next release. Until then, call POST /api/v1/tracking/alias from your backend, or install the SDK from a clone of this repository (see Installation).

alias(anonymousId, userId) sends one POST /api/v1/tracking/alias (beta): the anonymous id a visitor was assigned under and the user id they signed in with are one person. From then on, in each experiment, the assignment stored first among the two ids answers for both, so a user id with no assignment of its own is answered the variant the anonymous id holds, and its events for that experiment count toward it. The rules and every answer are in Link an anonymous id to a known user id.

// In your backend, when the visitor signs in:
const server = new ExperimentationClient({
  apiUrl: process.env.CONTROLVAR_API_URL!,
  apiKey: process.env.CONTROLVAR_SERVER_KEY!, // sdk:ruleset scope
});
const created = await server.alias(visitorId, customerId); // false: the link was already stored
  • It needs a server-side key: one with the sdk:ruleset scope, created by a user who can change feature flags. Call it from your backend.
  • It resolves true when this call stored the link and false when the link was already stored.
  • Any other answer rejects with ExperimentationError, as getAssignment does, with the server's status and body: 404 from a server without the route, 403 for a key that is not a server-side key, 409 when a rule refuses the link (the anonymous id is already linked to another user id, for one), and 422 for an id the server refuses (the two ids equal, for one). A network failure or a timeout rejects with no status. A 429 is retried once, as for every call.
  • A failed alias is yours to call again: the client keeps nothing of it. Until it succeeds, the server may give the user id an assignment of its own.
  • On success the client sends a key-less track(userId, …) to each experiment a key-less track(anonymousId, …) would reach (see the fan-out rule), for 24 hours from the alias, and not to the anonymous id's flags: flags are not linked. It also drops the user id's cached assignments, so its next getAssignment asks the server.
  • The anonymous id's own events keep the anonymous id: nothing already sent, or sent later under it, is changed.
  • The copy helps only on the client that assigned the anonymous id. After a browser assigned it and your backend called alias, the backend's client holds nothing for the anonymous id: call getAssignment(experimentKey, { userId }) there before a key-less track(userId, …).

Caching, shared requests and retries

  • Successful assignments and evaluations are cached per user + key for cacheTtlMs; failures are never cached, so the next call retries.
  • Concurrent calls for the same user + key share one in-flight request (one assignment, one exposure event).
  • A 429 is retried once after the server's Retry-After (seconds or HTTP date; default 1 s, capped at timeoutMs).

Errors

getAssignment, evaluateFlag, getAllFlags, fetchAssignments and alias reject with ExperimentationError (name === 'ExperimentationError'):

code Meaning status
HTTP_ERROR Non-2xx response; body holds the parsed JSON error (e.g. {detail}) HTTP status (401 bad key, 404 an unknown experiment or flag key, or a draft experiment with no control variant, 422, 429 after the retry)
NETWORK_ERROR fetch rejected (DNS, connection refused, CORS, no fetch available) undefined
TIMEOUT The request exceeded timeoutMs undefined
INVALID_RESPONSE 2xx but the body is not what the SDK expects (or userId missing) HTTP status or undefined
TYPE_MISMATCH Only passed to onError, with the operation 'value': a typed getter was called for a flag that serves another type undefined
HOOK_ERROR Only passed to onError, with the operation 'exposure': your onExposure threw, or its Promise rejected; cause is what it threw undefined
import { ExperimentationClient, ExperimentationError } from '@controlvar/js-sdk';

try {
  const a = await client.getAssignment('checkout_flow', user);
} catch (err) {
  if (err instanceof ExperimentationError && err.status === 404) {
    // no experiment has the key — fall back to control
  }
}

Flag values

A flag serves its on value to the users it is on for, and its off value to everyone else, and to everyone while it is turned off; a string, number or json flag with a split, or a matched rule with a value of its own, serves those users that value instead. Who the flag is on for, and the reason the server gives (targeting_rule or rollout), are decided as for any flag: see Multi-way flags. For a string, number or json flag, read the value with the getter of its type: getStringValue, getNumberValue or getJsonValue.

const label = await client.getStringValue('checkout-button-label', user, 'Buy now');
const limit = await client.getNumberValue('free-shipping-threshold', user, 50);
const theme = await client.getJsonValue('checkout-theme', user, { color: 'gray' });

Pass the flag's off value as your default, so that a flag your code cannot reach behaves as off. Each getter takes the user before the default, as every method of this client does. OpenFeature's getStringValue takes the default first; a call written in that order is a TypeScript error here.

A getter never rejects. It returns your default, and passes the reason to onError(err, 'value'), when the request fails (including a 404 for a flag the server does not know), when the server's answer carries no value (in server mode, from a server from before flag values, err.code 'INVALID_RESPONSE'; in local mode, every flag the client answers locally from such a server's ruleset reads as boolean, so the getter reports 'TYPE_MISMATCH'), or when the flag serves another type (err.code 'TYPE_MISMATCH', with a message such as Flag "checkout-button-label" serves a string; getNumberValue returned your default). A boolean flag is another type; read it with isFeatureEnabled. Nothing is coerced: "10" is not a number.

getJsonValue checks that the value is an object or an array, not that it matches your type parameter, and returns a new copy on every call.

A getter is evaluated as evaluateFlag is: cached per user and flag for cacheTtlMs, and in local mode answered from the ruleset. evaluateFlag returns the same answer with value and valueType; in server mode both are undefined from a server without flag values.


Exposure hook

onExposure is a function you give the client when you create it. The client calls it once each time the server enrols the user in an experiment and the answer did not come from the client's cache: the moment the server records the exposure. Use it to send the exposure to your analytics tool or warehouse.

const client = new ExperimentationClient({
  apiUrl: 'http://localhost:8000',
  apiKey: process.env.CONTROLVAR_API_KEY!,
  onExposure: (exposure) => {
    // your analytics tool's call goes here
    console.log('exposure', exposure.experimentKey, exposure.variantName, exposure.userId);
  },
  onError: (error, operation) => {
    if (operation === 'exposure') console.warn('onExposure failed', error.cause);
  },
});

It receives an Exposure: experimentKey, userId, variantId (null when the server sends none) and variantName, in a new object for each call. Nothing else: not the user's attributes and not the variant's configuration.

It is not called for:

  • an answer from the client's cache, or a call that shares a request already in flight;
  • a user the experiment did not enrol (assigned: false, with reason 'holdout', 'mutual_exclusion' or 'targeting'), or an experiment that is not running ('draft', 'paused', 'completed' or 'archived'): the server records no exposure for them, and the client returns the control variant;
  • a call that fails, including one that times out after the server recorded the exposure;
  • a feature flag, in either evaluation mode.

It is not called when the server does not send assigned; every Controlvar server release sends it.

It is called again, and the server records another exposure, after the cache lifetime (cacheTtlMs, 5 minutes by default; with cacheTtlMs: 0, on every call), after clearCache(), and in every new client: each page load in a browser, each process on a server. So your tool can receive several exposures for one user and experiment: count users, not events. It never receives one the server did not record.

It is called when your code asks for the assignment, whether or not you then show the variant, so ask for it where the variant is shown.

It runs before getAssignment resolves, and before every call that is waiting on the same request, so keep it quick: hand the exposure to your analytics library, which sends it later. The client does not wait for a Promise it returns.

If it throws, or returns a Promise that rejects, the answer is unchanged, and the error goes to onError with the operation 'exposure': an ExperimentationError whose code is 'HOOK_ERROR', whose message starts with onExposure failed:, and whose cause is what your function threw.

The constructor throws onExposure must be a function for any other value; null and undefined set none.

In a test, a faked /assign answer must include "assigned": true, or the hook is not called.


Backend endpoints used

Every request carries X-API-Key, Content-Type: application/json and Accept: application/json. apiUrl is the origin only; the SDK appends the paths below.

SDK call Method and path Body / query 200 response
getAssignment, getVariant POST /api/v1/tracking/assign {"experiment_key","user_id","context"?: object} {"experiment_key","user_id","variant_id","variant_name","is_control","configuration","assigned","reason"}
evaluateFlag, isFeatureEnabled GET /api/v1/feature-flags/evaluate/{flag_key}?user_id=<id>&context=<url-encoded JSON> context = user.attributes (omitted when empty) {"key","enabled","config","reason"}
getAllFlags GET /api/v1/feature-flags/user/{user_id}?context=<url-encoded JSON> context = attributes (omitted when empty) {"<flag_key>": bool, ...}
track with a key POST /api/v1/tracking/track {"event_type","event_name","user_id","experiment_key"?,"feature_flag_key"?,"value"?,"metadata"?,"timestamp"?,"event_id"?} stored event (ignored)
track without a key POST /api/v1/tracking/batch, one entry per experiment and flag it reaches; with none, POST /api/v1/tracking/track {"events":[<track body>...]} (max 100); with none, the track body with no key ignored
trackBatch POST /api/v1/tracking/batch {"events":[<track body>...]} (max 100) {"success_count","failure_count","errors"}
fetchAssignments GET /api/v1/tracking/assignments/{user_id}?active_only=true — list of assignment rows
alias POST /api/v1/tracking/alias (beta; a server-side key) {"anonymous_id","user_id"} {"anonymous_id","user_id","created"}
local mode: ruleset refresh GET /api/v1/sdk/ruleset (beta) If-None-Match: "<version>" the ruleset, ETag; 304 when unchanged
local mode: evaluation counts POST /api/v1/tracking/evaluations (beta) {"evaluations":[{"flag_key","count","enabled_count","window_start","window_end"}]} {"accepted","errors"}
reportError POST /api/v1/tracking/errors {"error_type","message","feature_flag_key"?,"experiment_key"?,"user_id"?,"stack_trace"?,"metadata"?,"timestamp"?} 201 and the stored report (only the status is read)

Errors: 401 bad key; 404 an unknown experiment or flag key, or a draft experiment with no control variant; 422 invalid event; 429 rate limited (Retry-After header, retried once).


TypeScript types

import type {
  ClientConfig, UserContext, Assignment, FlagEvaluation,
  TrackOptions, TrackEvent, BatchResult, AssignmentRecord, ErrorReport,
  Exposure, SwallowedOperation,
} from '@controlvar/js-sdk';

interface Exposure {
  readonly experimentKey: string;
  readonly userId: string;
  readonly variantId: string | null;
  readonly variantName: string;
}

interface Assignment {
  experimentKey: string;
  userId: string;
  variantId: string | null;
  variantName: string;
  isControl: boolean;
  configuration: Record<string, unknown> | null;
}

interface FlagEvaluation {
  key: string;
  enabled: boolean;
  config: unknown | null;
  reason?: string;     // 'targeting_rule' | 'rollout' | 'inactive' | 'error'; undefined when the server does not send it
  value?: unknown;     // what the flag serves this user (see Flag values); undefined when the server does not send it
  valueType?: string;  // 'boolean' | 'string' | 'number' | 'json'; undefined when the server does not send it
  source?: 'server' | 'local'; // local mode only: answered in-process, or by the server
}

interface BatchResult {
  successCount: number;
  failureCount: number;
  errors: unknown[];   // server-reported per-event errors plus {message, status?} per failed chunk
}

The raw wire shapes (AssignResponse, FlagEvaluateResponse, BatchResponse, TrackBody) are exported too.


Hash utilities (compatibility only)

consistentHash(userId, flagKey), md5Hex(input) and md5Bytes(input) are exported so the cross-SDK golden-vector tests and custom integrations can verify parity:

MD5("{userId}:{flagKey}") → first 4 bytes as little-endian uint32 → ÷ 2^32 (4294967296)
consistentHash('user-123', 'my-flag') ≈ 0.6927449859

Nothing in the SDK calls consistentHash to pick a variant or decide a flag. It is not the function the server buckets flag rollouts with: that is md5-mod100-v1, the whole MD5 digest of "{userId}:{flagKey}" read as a big-endian integer, mod 100, which local evaluation reproduces internally (consistentHash('user-123', 'my-flag') is bucket 69; the server puts that user in bucket 79).


Local evaluation (server-side, beta)

With evaluation: 'local' the client downloads the flag ruleset (GET /api/v1/sdk/ruleset), refreshes it every refreshIntervalMs (30 s by default, 5 s minimum), and answers evaluateFlag, isFeatureEnabled and getAllFlags in-process whenever it can give exactly the server's answer; otherwise it makes the usual request. Experiments are always assigned by the server. It needs an Controlvar server at 0.11.0 or later and a key with the sdk:ruleset scope, and it is for server-side code only: the constructor throws in a browser.

const client = new ExperimentationClient({
  apiUrl: process.env.CONTROLVAR_API_URL!,
  apiKey: process.env.CONTROLVAR_SERVER_KEY!, // sdk:ruleset scope
  evaluation: 'local',
});
await client.ready({ timeoutMs: 5_000 });        // optional; never rejects
const { enabled, reason, source } = await client.evaluateFlag('new_search', user); // source: 'local' | 'server'
await client.close();                            // on shutdown: sends the evaluation counts

A value flag's value is answered locally too, unless it has a split or a rule with a value of its own: its on value when the flag is on for the user, its off value otherwise, and its off value to everyone while it is turned off. A flag with a split or a rule's own value is evaluated by the server while it is on, and answered locally, its off value to everyone, once it is turned off (see Local evaluation). A flag entry this SDK cannot read (an evaluation or value_type from a newer server, or a value of the wrong type) is evaluated by the server, the rest of the ruleset is still answered locally, and, while the flag is active, status().serverEvaluatedFlags lists it.

A flag whose stored values the server cannot serve reaches every local client as a server-evaluated flag, whatever its status (only a direct database write, or a rollback past a release with wider value limits, produces one). Turning such a flag off does not change the ruleset. So a local client of any version keeps the server's answer it cached for that user and flag for up to cacheTtlMs (5 minutes by default) before it sees the flag off, and while the flag exists getAllFlags asks the server on every call.

A change made in the dashboard reaches the process at its next successful refresh. For a flag with a split or a rule's own value, a change other than turning it off reaches a user the client has already cached once that answer expires, cacheTtlMs (5 minutes by default). While the API is unreachable the last ruleset keeps being served (set maxStaleMs to bound that); a 401 or 403 on refresh discards it. What is answered locally, the refresh failure table, safety monitoring and troubleshooting: Local evaluation.


Browser vs Node.js

The SDK is isomorphic. In the browser the API key is visible to end users, and keys are not scoped for browser use: every active key, including one shipped to a browser, can evaluate flags and track events as the user who created it. Such a key answers for whichever user id it is sent: what that id is served, whether it is in a segment, and which experiments it is assigned to. Where that matters, use user ids that do not identify a person (not email addresses), in ID lists too, and read assignments from your server. Use a dedicated key for browser traffic so it can be revoked on its own, and never give it the sdk:ruleset scope, which lets a key download every flag's targeting rules. The two routes the visual editor's browser script calls refuse a key with any scope (Refused in a web page); the routes this SDK calls do not. Server-side, lower timeoutMs if the SDK sits on a request path:

const client = new ExperimentationClient({
  apiUrl: process.env.CONTROLVAR_API_URL!,
  apiKey: process.env.CONTROLVAR_API_KEY!,
  timeoutMs: 1000,
});

Contract smoke

cd sdk/js && npm run build --silent && node examples/contract_smoke.mjs

It prints one line:

{"sdk":"js","assign":{"variant_name":"control","is_control":true,"sticky":true},"flag":{"enabled":true},"track":{"ok":true},"fanout":{"ok":true}}

Env: CONTROLVAR_API_URL (default http://localhost:8000), CONTROLVAR_API_KEY (required), CONTRACT_EXPERIMENT_KEY (default sdk_contract_ab), CONTRACT_FLAG_KEY (default sdk_contract_flag), CONTRACT_USER_ID (default random smoke-<uuid>). The script assigns twice (sticky), evaluates the flag, tracks purchase with a key, tracks page_view without a key (fan-out) and sends a 2-event trackBatch. npm run smoke is a shortcut.

With a seeded backend (python backend/scripts/seed_sdk_contract.py): python tests/sdk-contract/live/run_live_contract.py --sdk js --strict. That also runs examples/local_eval_smoke.mjs with the seed's sdk:ruleset key (the js (local) row): 40 evaluations answered locally, the counts sent on close(), then two error reports sent with reportError and the same key, and the runner checks in the database that no evaluate call was made, that the safety monitor's denominator grew by exactly 40 and that both reports were counted.

The runner gives the smoke the seed's sdk:ruleset key as CONTROLVAR_LOCAL_API_KEY. With it the smoke also links a new anonymous id to a new known id with alias and reports them as alias, and the runner checks in the database that the two ids hold one assignment row, the anonymous id's, and that the key-less event the smoke sent under the known id is stored under the anonymous id with the experiment and its variant.


Development

npx jest runs the unit tests, with fetch mocked; npm run build runs tsc into dist/ (CommonJS and .d.ts):

cd sdk/js && npm install
npx jest
npm run build