Installation
Install the SDK with your preferred package manager:
npm
npm install @runbandit/sdk
yarn
yarn add @runbandit/sdk
pnpm
pnpm add @runbandit/sdk
Quick Start
Get up and running with just a few lines of code. The example below initializes the client, requests an assignment, renders the variant, and tracks a conversion event.
import { BanditClient } from '@runbandit/sdk'
const bandit = new BanditClient({
apiUrl: 'https://runbandit.com',
apiKey: 'your-api-key'
})
// Get the best variant for a user
const assignment = await bandit.getAssignment('experiment-id', 'user-123')
// Show the variant content
document.querySelector('#headline').textContent = assignment.config.content
// Report a conversion on the experiment's funnel
bandit.convert('funnel-id')
// Track a named event for your reports
bandit.trackNamedEvent({
name: 'purchase',
value: 29.99
})Configuration
The Bandit client. It assigns treatments, records events and exposures, and reports conversions. It batches events and exposures and flushes them on a timer, so call `destroy()` when you are done with it. Pass a configuration object when creating a new BanditsClient instance. Only apiUrl and apiKey are required.
| Option | Type | Default | Description |
|---|---|---|---|
| apiUrl | string | required | Your API base URL. |
| apiKey | string | required | Your API key, from the dashboard. A publishable key is safe in the browser; keep a secret key on your server. |
| timeout | number | 5000 | Request timeout in milliseconds. |
| batchSize | number | 100 | Events or exposures queued before the client sends a batch on its own. |
| flushInterval | number | 10000 | How often the client flushes its queues, in milliseconds. |
| sessionTtl | number | 86400000 | How long a session id lives, in milliseconds. |
| visitorId | string | none | Visitor id to use instead of the one kept in `localStorage`. Set it on a server that handles one visitor per request. |
| captureArrival | boolean | true | Report how the visitor arrived (UTM tags, ad click ID, referrer host) when the client is constructed in a browser. Pass `false` to turn it off. |
| captureCdpAliases | boolean | true | Join the visitor to the anonymous ID a CDP (Segment, RudderStack, PostHog) set in this browser, when the client is constructed. Pass `false` to turn it off. |
Properties
| Property | Type | Description |
|---|---|---|
| sessionId | string | The session id the client attributes events to. It expires after `sessionTtl`. |
| visitorId | string | The visitor id. It is the `bandit_v` cookie when a server render or `bandit.js` set one, else an id kept in `localStorage` with no expiry. `getAssignment()` and `convert()` use it by default. |
Methods
reportCdpAliases()
Read the anonymous ID that a CDP (Segment, RudderStack, PostHog) stored in this browser and join it to the visitor. It sends only IDs it has not sent before. The constructor calls it unless `captureCdpAliases` is `false`.
Returns: Promise<boolean> `true` when it sent at least one new ID.
aliasVisitor(aliases)
Join CDP anonymous IDs you already have to the visitor. The latest visitor wins for each ID.
Returns: Promise<void>
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| aliases | CdpAlias[] | required | Each alias is a CDP `source` and the `externalId` that CDP uses for the visitor. |
await bandit.aliasVisitor([{ source: 'segment', externalId: analytics.user().anonymousId() }])reportArrival()
Report how the visitor arrived on this page: UTM tags, ad click ID and referrer host. It does nothing outside a browser and skips a page that repeats the touch already reported this session. The constructor calls it unless `captureArrival` is `false`. Call it again after a client-side route change that lands on a tagged URL.
Returns: Promise<boolean> `true` when it sent a touch.
getAssignment(experimentId, userId?, context?)
Request a treatment assignment. The bandit picks the variant that has performed best so far, and keeps showing a visitor the treatment it first chose. When you pass `context`, contextual experiments choose with it.
Returns: Promise<Assignment>
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| experimentId | string | required | The experiment to get an assignment for. |
| userId | string | optional | Unique identifier for the visitor. Defaults to `visitorId`. Defaults to this.visitorId. |
| context | ContextualFeatures | optional | Contextual features (device type, location and so on) for contextual experiments. |
// Basic assignment
const assignment = await bandit.getAssignment('exp-headline', 'user-123')
// With contextual features
const assignment = await bandit.getAssignment('exp-headline', 'user-123', {
deviceType: 'mobile',
location: 'US',
timeOfDay: 'evening'
})
// Assignment shape
// {
// assignmentId: "asgn_abc123",
// treatmentId: "treat_xyz",
// experimentId: "exp-headline",
// userId: "user-123",
// config: { content: "Try it free today!", color: "#4f46e5" }
// }trackNamedEvent(event, opts?)
Track a named event. Events are free-form names, and the SDK attaches the session id so the server can attribute them. An event with `cost` or `lineItems` is an order and pays the visitor's funnels and campaigns. Any other event is recorded for your reports and credits nothing. Orders need a client built with your secret key; a publishable key that sends `cost` or `lineItems` gets a 403. Events are queued and sent in batches. On a server, where one client serves many users, pass `opts.userId` (or `opts.assignmentId`) on every call. Pass `opts.immediate` right before a navigation.
Returns: void
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| event.name | string | required | Free-form event name (for example "purchase", "signup", "button_click"). The name does not decide credit. |
| event.category | string | optional | Optional category for grouping (for example "conversion", "engagement"). Defaults to "custom". |
| event.value | number | optional | Numeric value for the event, such as a revenue amount. |
| event.cost | number | optional | What the order cost you. With it the event is an order, and a margin funnel learns from value minus cost. |
| event.lineItems | OrderLineItem[] | optional | The order's lines, each with id, quantity, price, optional discount and optional unitCost. |
| event.metadata | Record<string, any> | optional | Arbitrary key-value metadata to attach to the event. |
| opts.immediate | boolean | optional | Send now with a keepalive request instead of queueing. Use it right before a navigation. |
| opts.userId | string | optional | The user the event belongs to. Required on a server that serves many users. |
| opts.assignmentId | string | optional | Attribute the event to this assignment, from `getAssignment()`. |
// Track a purchase with revenue
bandit.trackNamedEvent({
name: 'purchase',
value: 29.99,
metadata: { product: 'premium-plan' }
})
// Track a signup
bandit.trackNamedEvent({ name: 'signup' })
// Track any custom action with a category
bandit.trackNamedEvent({
name: 'added_to_cart',
category: 'engagement',
metadata: { sku: 'WIDGET-42' }
})
// Track an order with its cost, so a margin funnel learns from profit
bandit.trackNamedEvent({
name: 'purchase',
value: 120.00,
cost: 45.50,
}, { assignmentId })
bandit.trackNamedEvent({
name: 'purchase',
lineItems: [{ id: 'mug', quantity: 2, price: 24.00, discount: 5.00, unitCost: 9.50 }],
}, { assignmentId })flush()
Send every queued event and exposure now. The client flushes on its own at `batchSize` and every `flushInterval`, and on Node it also sends anything still queued when the process is about to exit, so you rarely need this except before a page unload.
Returns: Promise<void>
window.addEventListener('beforeunload', () => {
bandit.flush()
})exposed(assignmentId, opts?)
Report that this visitor actually saw the treatment. The client queues the report, drops repeats for the same `assignmentId`, and sends it to `POST /api/exposures` with the next batch. Only experiments created with `trialOn: 'exposure'` count a trial from it. Every experiment records it beside the trial.
Returns: void
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| assignmentId | string | required | The `assignmentId` that `getAssignment()` returned. |
| opts.immediate | boolean | optional | Send right away instead of with the next batch. Use it right before a navigation. |
const assignment = await bandit.getAssignment('exp-pricing-table', 'user-123')
renderPricing(assignment.config)
bandit.exposed(assignment.assignmentId)observeExposure(assignmentId, element, opts?)
Watch an element and call `exposed()` once at least `threshold` of it has been visible for `dwellMs` without a break. It does nothing outside a browser or where `IntersectionObserver` is missing.
Returns: () => void A function that stops watching.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| assignmentId | string | required | The `assignmentId` that `getAssignment()` returned. |
| element | Element | required | The element that shows the treatment. |
| opts.threshold | number | optional | Share of the element that must be visible, from 0 to 1. Defaults to 0.5. |
| opts.dwellMs | number | optional | How long it must stay visible, in milliseconds. Defaults to 1000. |
const stop = bandit.observeExposure(
assignment.assignmentId,
document.querySelector('#pricing-table')!,
{ threshold: 0.5, dwellMs: 1000 }
)identify(anonymousId, identifiedUserId, mergeReason?, options?)
Link the anonymous ID you passed to `getAssignment()` before sign-in to the durable ID you use afterwards (email, account ID). Past assignments and rewards move to the identified user, and `getAssignment()` with either ID returns the same treatment. Works with your secret key or a publishable key.
Returns: Promise<void>
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| anonymousId | string | required | The ID the visitor had before they were known. |
| identifiedUserId | string | required | The durable ID (email, account ID). |
| mergeReason | 'user_signup' | 'email_verification' | 'social_login' | 'account_recovery' | 'manual' | optional | Why the link happened. Defaults to "manual". |
| options.email | string | optional | The visitor's email address, so email sends can be matched to them. |
// After sign-up, tie the pre-signup visitor to the account await bandit.identify(anonymousId, user.email, 'user_signup')
label(userId, labels)
Record survey answers about a visitor, such as "what brought you here". Audiences use them as traits.
Returns: Promise<void>
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| userId | string | required | The visitor the answers are about. |
| labels | Record<string, string | boolean> | required | Each key is the question and each value the answer. |
await bandit.label(bandit.visitorId, { 'how-did-you-hear': 'podcast', 'first-purchase': true })trackFunnelReward(funnelId, userId, value)
Credit a funnel's conversion to a specific visitor. It first sends any queued exposures, so the treatment counts as seen before the conversion lands. In a browser, `convert()` does this for the current visitor.
Returns: Promise<void>
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| funnelId | string | required | The funnel that converted. |
| userId | string | required | The visitor to credit. It must be the ID the visitor was assigned under. |
| value | number | required | The payout. With payout unit "count" every conversion is 1 whatever you send. |
await bandit.trackFunnelReward('funnel-id', 'user-123', 49.0)convert(funnelId, value?)
Report a conversion on a funnel for the current visitor. It works on a later page than the one that assigned the treatment, such as a thank-you page, because the visitor id persists across pages.
Returns: Promise<void>
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| funnelId | string | required | The funnel that converted. |
| value | unknown | optional | The payout. Defaults to 1. Defaults to 1. |
bandit.convert('funnel-id')
bandit.convert('funnel-id', 49.0)convertOn(funnelId, pathPattern, value?)
Call `convert()` only when the current page's path matches a pattern. Use it on a site-wide script to credit a conversion page. It does nothing outside a browser.
Returns: Promise<boolean> `true` when the page matched and the conversion was sent.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| funnelId | string | required | The funnel that converted. |
| pathPattern | string | required | A path such as "/thank-you". Use "*" for one whole path segment and "**" for any number of segments. |
| value | unknown | optional | The payout. Defaults to 1. Defaults to 1. |
await bandit.convertOn('funnel-id', '/thank-you')destroy()
Stop the flush timer and flush any remaining queued events. Call it when your application unmounts or the client is no longer needed, to prevent memory leaks. It also clears the stored session id.
Returns: void
// React cleanup
useEffect(() => {
const client = new BanditsClient({ apiUrl, apiKey })
return () => client.destroy()
}, [])
// SPA route change cleanup
router.beforeEach(() => {
bandit.destroy()
})Types
Assignment
The treatment the bandit chose for a visitor.
| Field | Type | Required | Description |
|---|---|---|---|
| assignmentId | string | required | Pass this to `trackNamedEvent()` and `exposed()` to attribute them to this assignment. |
| treatmentId | string | required | The treatment that was chosen. |
| experimentId | string | required | The experiment the assignment belongs to. |
| userId | string | required | The visitor the assignment was made for. |
| config | any | required | The treatment's content, as the JSON you saved on it. An empty object when it has none. |
| funnelId | string | optional | The funnel this experiment belongs to, when it has one. Pass it to `convert()`. |
| trialOn | 'served' | 'exposure' | optional | Whether a trial counts when the treatment is served or when it is seen. With `'exposure'`, call `exposed()` once the visitor sees it. |
BanditsRequestError
Thrown when the API rejects a request. `status` is the HTTP status, or `undefined` when the request never got a response (a timeout or a network failure).
| Field | Type | Required | Description |
|---|---|---|---|
| status | number | undefined | required | The HTTP status of the failed response, or `undefined` when there was none. |
Named Events
Events are free-form named strings — use any name that makes sense for your product (e.g. purchase, signup, button_click). A named event is recorded for your reports and credits nothing on its own. The bandit learns from funnel conversions (convert() or the funnel goal) and from orders, events that carry a cost.
// Track any named event
bandit.trackNamedEvent({
name: 'purchase', // any string you choose
value: 29.99, // optional numeric value
metadata: { sku: 'WIDGET-42' }
})Margin and Orders
A deeper discount can win on conversions and still lose money. Create the funnel with payout unit margin and send what each order cost you; the bandit then learns from revenue minus cost, and an order sold below cost counts against its treatment. An order sent without a cost credits nothing until you send the cost, because a guessed cost would make every discount look free.
bandit.trackNamedEvent({
name: 'purchase',
value: 120.00,
cost: 45.50,
}, { assignmentId })
bandit.trackNamedEvent({
name: 'purchase',
lineItems: [{ id: 'mug', quantity: 2, price: 24.00, discount: 5.00, unitCost: 9.50 }],
}, { assignmentId })For refunds, shipping, or costs that arrive after the order, send orders from your server with a secret key. The order id makes every call safe to retry: sending the same order again does nothing, unless it was stored without a cost, in which case the costed copy is credited once. A refund lowers that order's payout by the refunded share, never below what was left, and a repeated refund id is ignored.
curl -X POST https://runbandit.com/api/orders \
-H "Authorization: Bearer $BANDIT_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"orderId":"1042","assignmentId":"<assignmentId>",
"lines":[{"id":"mug","quantity":2,"price":24,"unitCost":9.5}],
"shipping":6,"shippingCost":4.25}'
curl -X POST https://runbandit.com/api/orders/1042/refunds \
-H "Authorization: Bearer $BANDIT_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"refundId":"r-77","amount":24}'Served or seen: when a trial counts
Bandit records three things for every visitor: the treatment was served, the visitor saw it, and the visitor converted. Each experiment picks one rule for when the bandit counts a trial, so its conversion rate divides by visitors who were served the treatment or by visitors who saw it. The dashboard charts visitors and conversions.
| Experiment kind | Trial counts on | Why |
|---|---|---|
| Picker element (Bandit has the selector) | Exposure | Bandit watches the element |
| Global change (theme, layout, pricing logic) | Served | Seen at page load, or not visibly "seen" at all |
| Backend only (ranking, emails, server logic) | Served | No element to watch |
| SDK, your choice | Served unless you set trialOn: "exposure" and call exposed() | You decide at creation |
- The rule is fixed when the experiment is created. Pass
trialOntoPOST /api/experiments, tobandit experiments create --trial-on exposure, or to the MCP create_experiment tool. Changing it later is rejected. Each assignment response carriestrialOnso your code knows whether to report. - For a point-and-click experiment, bandit.js watches the element for you. It reports an exposure when half of it has been visible for one second.
- A conversion belongs to the visitor's funnel or campaign and does not mark any single step as seen, so an unseen step in exposure mode gets no credit.
- Data pipes such as Segment cannot report exposure. Report it with the SDK or the endpoints below.
Without the SDK, send exposures to POST /api/exposures (1 to 1000 per request), or send an event named $exposure with the assignmentId to /api/events or /api/events/batch. Reporting the same assignment again changes nothing.
curl -X POST https://runbandit.com/api/exposures \
-H "Authorization: Bearer $BANDIT_PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"exposures":[{"assignmentId":"<assignmentId>"}]}'
curl -X POST https://runbandit.com/api/events \
-H "Authorization: Bearer $BANDIT_PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"$exposure","sessionId":"sess_1","assignmentId":"<assignmentId>"}'Best Practices
Use session-based tracking
Call trackNamedEvent() and let the session ID attribute the event. On a server, pass the user's userId on every call, since one client serves every user.
Clean up on unmount
Call destroy() when your component or application unmounts. This stops the auto-flush timer and sends any remaining queued events.
Let auto-batching work
The SDK automatically batches events and flushes them at the configured interval. Avoid calling flush() after every event -- let the batch system handle it for better performance and fewer network requests.
Session-based attribution
The SDK automatically handles event attribution via session tracking. Events are matched to assignments based on the user's session, so you don't need to manually store or pass assignment IDs. This works even across page reloads within the same session.