@embeddables/experiments
v0.4.2
Published
Experiment assignment SDK for Embeddables funnels.
Keywords
Readme
@embeddables/experiments
TypeScript-first client for sticky experiment assignment before render. Composes
on @embeddables/core and
calls the Embeddables experiments API when a configured experiment has no stored
assignment yet.
Install
npm install @embeddables/experiments @embeddables/coreQuick start
import { initEmbeddables } from '@embeddables/core'
import { initExperiments } from '@embeddables/experiments'
const experimentsConfig = [
{
id: '00000000-0000-4000-8000-000000000099',
key: 'hero_test',
variants: ['control', 'variant_b'] as const,
},
] as const
const embeddables = initEmbeddables({
projectId: '00000000-0000-4000-8000-000000000001',
publishableKey: 'pk_live_…',
forms: [],
experiments: experimentsConfig,
})
const experiments = initExperiments({ core: embeddables })
const hero = experiments.initExperiment({
experimentId: '00000000-0000-4000-8000-000000000099',
})
const variantKey = await hero.getAssignedVariantKey()
const variantTitle = await hero.getAssignedVariantTitle()getAssignedVariantKey() is typed from the configured variant list for that
experiment id, so invalid variant keys fail at compile time. The first call for a missing
assignment fetches from the API, persists locally, and returns the variant key;
later calls read the sticky value without another network round-trip.
Server (SSR)
import { initEmbeddablesServer } from '@embeddables/core/server'
import { initExperimentsServer } from '@embeddables/experiments/server'
const server = initEmbeddablesServer({
...config,
cookies: { get: (key) => req.cookies[key] ?? null },
})
const experiments = initExperimentsServer({ server })
const hero = experiments.initExperiment({
experimentId: '00000000-0000-4000-8000-000000000099',
})
const variantKey = await hero.getAssignedVariantKey()Sticky assignments are read from request cookies. To pre-seed the client with the
variant the server resolved (so the first client render is synchronous and
hydration doesn't flash), pass it as serverAssignments to initExperiments or
experiments({ serverAssignments }) on the client.
React
Install the peer dependency:
npm install reactRegister experiments through EmbeddablesProvider's modules prop, then use
read-only hooks in the same tree.
Example:
import { EmbeddablesProvider } from '@embeddables/core/react'
import {
experiments,
useExperiment,
} from '@embeddables/experiments/react'
import { config } from './embeddables/_dist/config.ts'
function Hero() {
// No type arguments: `em build` registers the experiment list for you.
const { assignedVariantKey, assignedVariantTitle, status } = useExperiment({
experimentId: '00000000-0000-4000-8000-000000000099',
})
if (status === 'pending') return <p>Loading…</p>
return <h1>{assignedVariantTitle ?? assignedVariantKey}</h1>
}
function App() {
return <Hero />
}
export function Root() {
return (
<EmbeddablesProvider
config={config}
modules={[experiments()]}
experiments={{
serverAssignments: { '00000000-0000-4000-8000-000000000099': 'control' },
}}
>
<App />
</EmbeddablesProvider>
)
}Example (CLI-generated modules):
import { modules } from './embeddables/_dist/modules.ts'
<EmbeddablesProvider
config={config}
modules={modules}
experiments={{ serverAssignments }}
>
<App />
</EmbeddablesProvider>- Pass
serverAssignmentsthrough the provider'sexperimentsprop for SSR hydration. - When
analytics()is enabled, exposure is tracked automatically. SetexcludeAnalyticsInModules={['experiments']}to keep assignment working while turning that tracking off. useExperimentreturns{ assignedVariantKey, assignedVariantTitle, status, error }, withstatusinpending | ready | error. Passing the sameserverAssignmentsused on the server makes the hook resolve synchronously on the first render — no variant flash across SSR hydration.
The order of modules does not matter: the provider initializes Analytics before Experiments
on its own.
Which experiments are configured and which the page renders
Tools that sit on top of a page (such as @embeddables/workbench) read these from the client:
listExperiments()returns every configured experiment as{ id, key, title, variants: [{ key, title }] }.readRenderedExperimentIds()returns the ids a mounteduseExperimentrenders right now. An id leaves when its last hook unmounts.initExperimentalone does not add one.subscribeRenderedExperiments(listener)callslistenerwhenever that set changes and returns an unsubscribe function.
Storage
Assignments are keyed by experiment id, not experiment key.
| Store | Key pattern | Value |
| ----- | ----------- | ----- |
| localStorage | EMBEDDABLES--{projectId}--EXPERIMENT-DATA | JSON { [experimentId]: variantKey } |
| Cookie (each) | EMBEDDABLES--{projectId}--EXP--{experimentId} | variant key string |
Cookie values win over localStorage for the same experiment id.
Analytics
To track assignment events, install @embeddables/analytics and pass initAnalytics({ core }) as analytics on initExperiments.
import { initAnalytics } from '@embeddables/analytics'
const analytics = initAnalytics({ core: embeddables })
const experiments = initExperiments({
core: embeddables,
analytics,
})When analytics is present, each newly fetched assignment emits one
experiment:assigned event. Sticky assignments already in storage are not
tracked again. A rejected trackEvent() never fails getAssignedVariantKey()
— the assignment is persisted before tracking runs.
Options
initExperiments
| Option | Purpose |
| ------ | ------- |
| core | Initialized @embeddables/core instance (required) |
| analytics | Optional analytics client for event tracking only |
| serverAssignments | Pre-seed { [experimentId]: variantKey } for SSR (React: pass via experiments({ serverAssignments })) |
initExperimentsServer
| Option | Purpose |
| ------ | ------- |
| server | Initialized @embeddables/core/server instance (required) |
| analytics | Optional analytics client for event tracking only |
| cookieStorage | Optional override to read sticky assignments from a source other than request cookies |
Assigning on demand
useExperiment assigns as soon as it renders. When the exposure should be booked
at a specific step instead, use useAssignExperiment:
import { useAssignExperiment } from '@embeddables/experiments/react'
function StartTrial() {
const { assignExperiment, isPending } = useAssignExperiment()
return (
<button
disabled={isPending}
onClick={() => {
void assignExperiment({ experimentId: 'exp-hero' }).then((assigned) => {
if (assigned) console.log(assigned.variantKey, assigned.variantTitle)
})
}}
>
Start
</button>
)
}The assignment is sticky, so a later useExperiment({ experimentId: 'exp-hero' }) reads it back
without another request. assignExperiment resolves to undefined while the
experiments module is not registered, and rejects when the request fails.
