How it works
npm install @runbandit/sdk. The server entry keeps a copy of your experiment settings in memory and refreshes it every few seconds in the background, so picking a treatment makes no network call while the page renders. On a cold start it waits at most 300 ms, then renders your fallback.
The visitor lives in the bandit_v cookie and the picks in bandit_d. The browser SDK and the bandit.js script read the same cookies, so a conversion recorded in the browser credits the visitor the server served, and the browser never picks again.
Keep your current copy in the code as the fallback, and make it the experiment's Control. If Bandit is slow or unreachable, visitors see the page as it is today.
Next.js App Router
Create the helpers once.
// lib/bandit.ts
import { createBandit } from '@runbandit/sdk/next'
export const bandit = createBandit({
apiUrl: 'https://runbandit.com',
publishableKey: process.env.BANDIT_PUBLISHABLE_KEY!,
})Pick in middleware. Only middleware can set cookies before a server component renders, so this is where the visitor gets their treatment. List the experiments each path shows; a path that shows none costs nothing.
// middleware.ts (proxy.ts on Next 16)
import { bandit } from './lib/bandit'
const EXPERIMENTS_BY_PATH: Record<string, string[]> = {
'/': ['home-hero', 'home-cta'],
'/pricing': ['pricing-headline'],
}
export default bandit.middleware((request) => EXPERIMENTS_BY_PATH[request.nextUrl.pathname] ?? [])
export const config = { matcher: ['/((?!_next|api|.*\\..*).*)'] }Already have a middleware? Call Bandit's and keep working on its response.
export default async function middleware(request: NextRequest, event: NextFetchEvent) {
const response = await bandit.middleware(['home-hero'])(request, event)
response.headers.set('x-frame-options', 'DENY')
return response
}Render it in any server component. The fallback is what visitors see when they have no treatment.
// app/page.tsx
import { bandit } from '@/lib/bandit'
const HEADLINE = 'Ship faster with fewer meetings'
export default function Home() {
return (
<bandit.Experiment name="home-hero" fallback={<h1>{HEADLINE}</h1>}>
{(config) => <h1>{(config as { value?: string }).value ?? HEADLINE}</h1>}
</bandit.Experiment>
)
}Or read the assignment yourself. treatment() never picks; it returns what middleware picked, or null.
const hero = await bandit.treatment('home-hero')
const headline = (hero?.config as { value?: string } | undefined)?.value ?? HEADLINERecord the conversion where it happens, in a server action, route handler or server component.
'use server'
import { bandit } from '@/lib/bandit'
export async function placeOrder(form: FormData) {
const order = await createOrder(form)
await bandit.convert('YOUR_FUNNEL_ID', order.total)
}React in the browser
BanditProvider creates one browser client for your app and sends the check that tells the Setup page your site is live. Add it once in the root layout.
// app/layout.tsx
import { BanditProvider } from '@runbandit/sdk/react'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<BanditProvider apiUrl="https://runbandit.com" publishableKey={process.env.NEXT_PUBLIC_BANDIT_PUBLISHABLE_KEY!}>
{children}
</BanditProvider>
</body>
</html>
)
}An experiment created to count a trial when it is seen (trialOn: "exposure") needs to know the visitor saw it. useExposure reports that once half the element has been on screen for a second. Pass it the clientAssignmentId from the server assignment.
'use client'
import { useExposure } from '@runbandit/sdk/react'
export function Pricing({ clientAssignmentId, children }: { clientAssignmentId: string; children: React.ReactNode }) {
return <section ref={useExposure(clientAssignmentId)}>{children}</section>
}For pages that only render in the browser, useTreatment('home-hero') fetches the assignment and returns undefined while it loads. Prefer the server for copy above the fold.
Express and Node
banditMiddleware picks the listed experiments, writes the cookies on the response, puts the decisions on res.locals.bandit and reports new picks after the response is sent. It works with any connect-style server.
import express from 'express'
import { BanditServer, banditMiddleware } from '@runbandit/sdk/express'
const bandit = new BanditServer({
apiUrl: 'https://runbandit.com',
publishableKey: process.env.BANDIT_PUBLISHABLE_KEY!,
})
const app = express()
app.get('/', banditMiddleware(bandit, ['home-hero']), (req, res) => {
const hero = res.locals.bandit.assignments['home-hero']
res.render('home', { headline: hero?.config.value ?? 'Ship faster with fewer meetings' })
})
app.post('/orders', async (req, res) => {
const order = await createOrder(req.body)
await bandit.convert('YOUR_FUNNEL_ID', req.headers.cookie, order.total)
res.redirect('/thanks')
})Any other server
On Cloudflare Workers, Hono, Remix, Deno or Bun, call decide with the request's cookie header, append its setCookies to the response, and hand flush() to waitUntil.
import { BanditServer } from '@runbandit/sdk/server'
const bandit = new BanditServer({ apiUrl: 'https://runbandit.com', publishableKey: env.BANDIT_PUBLISHABLE_KEY })
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const decisions = await bandit.decide(request.headers.get('cookie'), ['home-hero'])
const hero = decisions.assignments['home-hero']
const response = new Response(renderHome(hero?.config), { headers: { 'content-type': 'text/html' } })
for (const cookie of decisions.setCookies) response.headers.append('set-cookie', cookie)
ctx.waitUntil(decisions.flush())
return response
},
}Good to know
- Experiments that serve from the settings copy, which is the default, are picked on the server. An experiment that needs a live decision for each visitor returns
null, and the page renders its fallback. - A publishable key restricted to certain origins needs
origin: 'https://your-site.com'in the config, since server requests carry no browser origin. - Use the publishable key. A server can hold a secret key, but nothing here needs one.
- See the SDK guide for the browser client.