# Experiments and variants
Source: https://docs.trevosdk.com/concepts/experiments-and-variants
How assignment works, why it's deterministic, and what that means for your users.
An **experiment** is one question. A **variant** is one answer being tested. Every experiment
has a `control` — your current behaviour — and one or more variants proposing a change.
Both ship in the same build, deploy at the same time, and run simultaneously. Different users
get different ones, and nobody sees more than one.
## Assignment is a hash, not a lottery
When you call `getVariant()`, no network request happens. The SDK computes:
```
bucket = hash(identity + ":" + experimentKey) % 10000
```
then walks the variants, accumulating their traffic splits as basis points, and returns the
one whose range contains the bucket.
Three consequences follow, and they're the reason it works this way:
**It's stable.** The same identity and key always produce the same variant — on every page
load, every device, every session, forever. A user never sees the interface change under
them.
**It's fast.** No network call on the hot path. `getVariant()` is synchronous and returns in
under a millisecond, so it's safe in a render path.
**It's reproducible.** Given a user id and an experiment key, you can compute which variant
they'll get without asking Trevo anything — useful when debugging a report of "this user says
the button is missing".
The hash is FNV-1a over UTF-16 code units, and it's a frozen contract shared by every Trevo
SDK. The browser, Node, and any future client all bucket identically, which is what lets a
user get the same variant on the web and from your backend. See the
[bucketing spec](/reference/bucketing-spec) if you need the normative details.
## Identity decides everything
Assignment is a function of identity, so the question "which variant does this user get?"
reduces to "who does Trevo think this user is?"
* Before `identify()`, that's an **anonymous id** stored in browser local storage and
mirrored to a `trevo_id` cookie so the server can resolve the same variant during SSR
* After `identify(userId)`, it's **your user id**
Which leads to the single most common surprise: **calling `identify()` can move a user from
one variant to another**, because the input to the hash changed. If they were mid-session and
looking at the treatment, they may see the control after logging in.
The fix is to identify early — before rendering anything under test. See
[Variant mismatch](/troubleshooting/variant-mismatch).
Anonymous ids are also **per browser**. The same person on a laptop and a phone is two
participants until they sign in, and nothing can retroactively merge their pre-login history
on the second device.
## Traffic splits
Splits are whole percentages that must sum to 100. The SDK warns in the console if a
misconfigured experiment doesn't add up, and assigns as best it can rather than failing.
50/50 is the default and usually right — equal groups reach significance fastest. Uneven
splits make sense when you're being cautious about a risky change, at the cost of needing
more total traffic to reach the same confidence.
## More than two variants
Nothing stops you testing three or four arms, and `defineExperiment()` gives you a typed
union so an unhandled arm is a compile error rather than a silent fallthrough:
```ts theme={null}
const emailTiming = defineExperiment('email-capture-timing', [
'control',
'before-checkout',
'after-payment',
]);
```
But be deliberate. Every extra arm splits your traffic, so four arms at equal weight means
each gets 25% and you wait roughly twice as long as a two-arm test to reach the same
certainty. Most mature teams run two or three arms and more experiments, rather than fewer
experiments with more arms.
## Unknown keys return control
`getVariant()` returns `'control'` for an experiment key that isn't in the SDK's config —
one that doesn't exist yet, was rejected, or is paused — and it never throws. That includes
users who were already assigned: they return to control on the SDK's next config refresh
(about a minute in the browser, up to five minutes in a mobile app), and get the same
variant back if the experiment resumes, as long as they keep the same identity and storage
(`identify()` switches bucketing to their user id, and `reset()` clears stored assignments).
Until the SDK has loaded a config, a returning visitor keeps their last assignment.
That's deliberate: it means you can merge experiment code before the experiment exists in
Trevo, and a stopped experiment degrades to your current behaviour rather than breaking the
page.
One caveat: a **shipped** experiment stays in the config for 30 days after it ends, or a year
for an app using a Mobile key, whether or not a cleanup PR exists. New visitors get the
winning variant. In mobile apps a device already assigned a losing variant gets the winner
too, but in the browser a visitor already assigned a losing variant keeps it, because it
stays listed at 0%. When the experiment leaves the config, every bucketed visitor reverts to
control, which is the variant you shipped against unless control won. Merge the cleanup PR,
or remove the `getVariant()` call yourself, before then.
## Experiments end
When a winner is called, a cleanup PR promotes the winning code and deletes the losing branch
along with the `getVariant()` call. The flag is temporary by design — you end with plain code,
not an accumulating pile of dead conditionals.
# Exposure vs conversion
Source: https://docs.trevosdk.com/concepts/exposure-vs-conversion
The two events Trevo records, and why the distinction decides whether your results mean anything.
Trevo records two kinds of event that matter to your results. (It also emits `$`-prefixed
internal events such as `$sdk_error` for health monitoring; those never appear in your
metrics.) Getting the difference right is most of what
separates a trustworthy experiment from a misleading one.
| | Exposure | Conversion |
| - | - | - |
| Means | "This user saw this variant" | "This user did the thing that counts" |
| Fires | Automatically, inside `getVariant()` | Only where you call `track()` |
| Role | The denominator | The numerator |
```
conversion rate = conversions ÷ exposures
```
Both halves have to be right. A wrong denominator is harder to notice than a wrong numerator,
and does just as much damage.
## Exposure
Recorded when `getVariant()` resolves:
```ts theme={null}
const variant = trevo.getVariant('checkout-cta'); // exposure recorded here
```
Deduplicated per identity, experiment and variant within a rolling 10-minute window, so
calling it repeatedly in a render loop doesn't inflate anything.
### Only where the user genuinely sees it
This is the trap. Exposure means *saw*, not *was assigned*. Resolve a variant in a component
that renders off-screen, or on a page where the tested element is below the fold and never
scrolled to, and you've added people to the denominator who never had the chance to convert.
The effect is always the same: your measured lift shrinks toward zero, because you've diluted
both arms with users who couldn't have responded. A real winner can be buried this way.
Two tools:
```ts theme={null}
// read the assignment without recording an exposure
const variant = trevo.getVariant('checkout-cta', { trackExposure: false });
// record it later, when the thing is actually visible
trevo.trackExposure('checkout-cta', variant);
```
Use that pair when you need the variant early — to fetch data, to decide a layout — but the
user won't see the result until later.
## Conversion
Nothing is captured automatically. There is no autocapture, no click tracking, no implicit
pageviews. A conversion exists only where you write one:
```ts theme={null}
trevo.track('purchase_completed', { value: 49.99, plan: 'pro' });
```
Names may use letters, digits, `_`, `.`, `-` and `$`, up to 500 characters; properties up
to 8KB serialised. An event whose name contains any other character is dropped with a
console warning.
### Pick events that mean something
The best conversion events sit as close to real value as you can get while still happening
often enough to measure.
* `purchase_completed` — unambiguous, but rare, so it needs a lot of traffic
* `checkout_started` — more frequent, and a decent proxy
* `button_clicked` — plentiful and nearly meaningless on its own
A common shape is a frequent event as the decision metric and a rarer, more valuable one as a
[guardrail](/concepts/reading-results), so you can move fast without optimising for a click that
leads nowhere.
### Record them server-side where you can
Browser events are lost to ad blockers, closed tabs, and flaky networks. Anything your
backend knows about — payments especially — is more reliably recorded there:
```ts theme={null}
trevo.track('subscription_started', { userId, anonymousId }, { plan: 'pro' });
```
See [Node](/install/node) or [REST](/install/rest). This improves the numbers for
your browser experiments too, because the denominator stays in the browser while the
numerator becomes reliable.
## How they meet
An exposure and a conversion are joined by **identity**. Trevo counts a conversion toward
whichever variant that identity was exposed to.
Which is why sending both `userId` and `anonymousId` from a backend matters: an event
carrying only `userId` from a user whose exposure was recorded anonymously has nothing to
join on, and that conversion is lost from the results. The SDKs send both automatically when
they can; on REST, it's your job.
## Symptoms of getting this wrong
| What you see | Likely cause |
| - | - |
| Exposures, no conversions | No `track()` call is being reached — or the event name contains an unsupported character; check the console |
| Conversions far exceed exposures | Converting users were never exposed — check where `getVariant()` runs |
| Lift always near zero | Denominator diluted with users who never saw the change |
| Backend conversions don't count | Events sent with only `userId`, no `anonymousId` |
# Funnels
Source: https://docs.trevosdk.com/concepts/funnels
An ordered chain of events that shows where users drop out.
An experiment answers *"did this change help?"*. A funnel answers *"where are we losing
people?"* — which is usually the question you have first.
A funnel is an ordered list of events. Trevo counts how many users reached each step, so the
gaps between steps show you where to look.
```
landing_view 1,000
signup_started 420 ← 58% drop
signup_completed 380
plan_upgraded 44 ← 88% drop
```
Two things stand out immediately: most people never start signing up, and most who complete
signup never upgrade. Those are your two candidate experiments, and you didn't have to guess.
## Building one
**Funnels → New funnel** in your workspace — or let Trevo draft funnels from your live
events with **Generate funnels**. Give the funnel a name, then add each step from the event
picker, in the order visitors reach them. Minimum two steps.
Steps can be events your app already sends — or events that don't exist yet. Type a new
name like `card_entered` and it's saved as a planned event. On its next pass over your
repository, Trevo's agent finds where that moment actually happens (the payment form, the
signup submit, the upgrade button) and opens a single pull request wiring `track()` for
every planned event the workspace is still missing — one tracking PR per repository at a
time. You review it like any teammate's PR; once it merges, the events start flowing and
the funnel starts recording. AI-generated funnels name events the same way and rely on the
same PR.
Until that PR merges, a step whose event never fires shows zero — it isn't an error, just an
empty column, and it's the most common reason a new funnel looks unfinished.
## Ordering and attribution
Steps are ordered. A user counts toward step 3 only if they also reached steps 1 and 2 —
that's what makes the drop-off between steps meaningful rather than a set of unrelated
counters.
Steps are attributed within a fixed 14-day window: a later step counts only if the user
reached it within 14 days of entering the funnel at step 1. (Configurable attribution
windows exist on experiments, not funnels.)
## Funnels and experiments together
This is where they earn their keep. A funnel tells you *where* to experiment; an experiment
tells you *whether* your fix worked.
Concretely: the funnel above says 58% of visitors never start signing up. So you run an
experiment on the landing page CTA, with `signup_started` as the decision metric — the exact
step the funnel identified as leaky.
And the step *after* your target makes a natural [guardrail](/concepts/reading-results). If the
new CTA lifts `signup_started` but `signup_completed` falls, you didn't win — you just
attracted people who bounce one screen later. Without the funnel you'd have shipped it.
## Choosing events
Good funnel steps are the moments that genuinely matter to your product, not every click you
can capture:
* **Entry** — `landing_view`, `app_opened`
* **Intent** — `signup_started`, `checkout_started`
* **Completion** — `signup_completed`, `purchase_completed`
* **Value** — `plan_upgraded`, `first_project_created`
Four to six steps is usually right. Too few and the drop-offs are too coarse to act on; too
many and every step looks fine because the losses are spread thin.
## What Trevo funnels are not
This is a focused conversion view, not a full product-analytics suite. There is no
autocapture, no session replay, no retention curves, no cohort explorer. Trevo collects what
it needs to run and settle experiments.
If you want to explore user behaviour broadly, keep a dedicated analytics tool and use Trevo
for experimentation. The two answer different questions.
# Mobile experiments
Source: https://docs.trevosdk.com/concepts/mobile-experiments
What changes when the experiment ships inside an app binary, for the iOS, Android, Flutter and React Native SDKs.
Every Trevo app SDK ([iOS](/install/ios), [Android](/install/android),
[Flutter](/install/flutter), [React Native](/install/react-native)) assigns the same variant
the web does for the same user and records events the same way. What differs is the platform.
## Read this before you plan your first mobile experiment
Three properties of mobile are not choices we made, and every vendor shares them. Planning
around them is easier than discovering them mid-experiment.
**A mobile cohort ramps over weeks, not days.** Experiment code ships inside an app release,
so your population is whoever has updated. Web reaches full traffic within a day of
activation; mobile climbs as adoption climbs, and both variants coexist across app versions
for as long as old builds stay installed.
**Merged is not live.** After the experiment PR merges, the experiment page reads
**Waiting for app release** until 20 people on a build with the change have entered it, so
store reviewers and test devices don't count. Store review and updates usually take one to
three weeks. The run time, the one-week minimum and the result's validity checks all count
from then, not from the merge. If nobody arrives within four weeks, the page warns that the
experiment is not live. Once it is live, the page shows the first build that has it and the
share of last week's active devices on that build or later.
**An experiment can be switched off without a release, and a later one can change its
values.** Config is re-read on every foreground, so pausing or stopping is immediate. Changing
what a variant *does* is code, and code ships through store review, unless the code reads a
[parameter](/concepts/parameters): `getParameter('paywall.headline', 'Subscribe')` ships once,
and every later experiment just sets new values.
**Anonymous users are per-device.** A visitor who browses on a laptop and then opens the app
is two participants until they sign in. `identify()` links them from that point forward;
nothing can link them retroactively. Identifying a user can change their arm because all SDKs
assign the signed-in user from the same user id. Restore auth and call `identify()` before
showing experiment UI.
Use a **Mobile** key (`tsk_live_…`, created under API Keys). A shipped binary can be unpacked,
so a secret key in an app is a leaked key. With a Mobile key, a shipped experiment stays in
the config for a year, so old builds that still have its code keep getting the winner; a Web
key drops it after 30 days.
## Durability
Phones lose the network constantly, are killed without warning, and have wrong clocks more
often than desktops. Every app SDK is built around that:
* **Events survive a cold start.** The queue is written to device storage and replayed on the
next launch. Delivery is at-least-once, and every event carries an idempotency key so a
replay is recorded once.
* **Timestamps survive a wrong clock.** Each batch is stamped with `sentAt` when it leaves the
device. Ingestion compares that against its own clock to recover the device's offset and
correct every event in the batch, which is what lets a queue drained three days late land on
a real timeline. Nothing is dropped for being out of range.
* **Assignment survives no network at all.** Config is persisted, so a cold start in a lift
assigns the same variant it assigned yesterday instead of falling back to control and
silently switching once the network returns.
* **A signed-in identity survives a relaunch.** `identify()` persists the user id, so the next
cold start assigns from it rather than reverting to the anonymous id and splitting one person
across two identities.
## Gating on app version
An experiment whose variant code only exists from a given build onward should not enrol
devices that cannot render it. Set `minAppVersion` on the experiment:
```json theme={null}
{ "experimentKey": "checkout-v2", "minAppVersion": { "ios": "1.4.0", "android": "1.4.0" } }
```
Builds below the threshold get `control` and record no exposure, so they never appear in the
results. The SDK has to know the build's version for this: iOS and Android read it from the
app, Flutter and React Native take it as `appVersion`. Without one, a gated experiment returns
control for everyone, because the SDK cannot prove the build is new enough and guessing wrong
means a broken screen. Every event also records the version, so each event names the build
that sent it.
## Store compliance
**Apple.** The iOS SDK and the React Native package each ship a privacy manifest
(`PrivacyInfo.xcprivacy`), which Xcode aggregates into the app's. It declares product
interaction and a user id, both linked, neither used for tracking, and no required-reason
APIs. The Flutter SDK is pure Dart with no native code, so it ships none: declare the same two
data types in your app's own manifest.
**Google Play.** Data safety answers you can paste into the Play Console:
| Question | Answer |
| - | - |
| Does your app collect or share user data? | Yes |
| Data type | App activity → App interactions |
| Data type | Device or other IDs → **No**: the id is generated by the SDK, not read from the device |
| Collected or shared? | Collected |
| Is it processed ephemerally? | No |
| Is collection required? | Optional, if you gate initialisation on consent |
| Purpose | Analytics; App functionality |
| Is data encrypted in transit? | Yes |
| Can users request deletion? | Yes, via your Trevo workspace |
The anonymous id is minted on device and is not an advertising or hardware identifier, which
is why "Device or other IDs" is **No**. Declaring it there invites a policy review you do not
need.
# Parameters
Source: https://docs.trevosdk.com/concepts/parameters
Values your app reads by name, so a later experiment can change them without a release.
An experiment usually ships its variants as code: the app branches on `getVariant()`. On
mobile that means every new test waits for store review and for users to update.
A parameter is a named value your app reads instead, with a default it falls back to:
```ts theme={null}
const headline = trevo.getParameter('paywall.headline', 'Subscribe');
const trialDays = trevo.getParameter('paywall.trial_days', 7);
```
The code ships once. After that, any experiment can set different values for each variant,
and the app picks them up from config with no new build.
## Setting values
Open an experiment that hasn't started, choose **Edit**, and add rows under
**Parameters**: a name, a type (text, number or true/false) and a value for each variant.
Leave a variant blank to keep what users get today: the last shipped value for that
parameter, or the app's default if none has shipped. That's how control usually reads, so
a new test measures against the real baseline.
Values lock when the experiment starts, like the traffic split, so one arm never mixes two
treatments.
A values-only experiment needs no pull request: create a custom experiment, set its values,
and start it.
## Lists and translated text
A text value can carry more than one string:
* **JSON**, up to 4,000 characters, for a list of plans, feature bullets or an ordering. Every
value of a parameter must have the shape of the one your app parses today, or Trevo refuses it.
Read it as text with today's JSON written out as the default, so Trevo can read that shape from
your code, and parse it with a fallback:
```ts theme={null}
let plans = DEFAULT_PLANS;
try {
plans = JSON.parse(
trevo.getParameter('paywall.plans', '[{"id":"pro_monthly"},{"id":"pro_yearly"}]'),
);
} catch {
// Keep the app's own list.
}
```
* **Text per language**, for an app that translates its text. Pick **Text per language** as the
type and write `{"en": "Start free", "de": "Kostenlos starten"}`, using only languages your app
ships. Pass your app's own translation as the default, and tell the SDK which language the app
shows:
```ts theme={null}
trevo.setLocale(i18n.language);
const headline = trevo.getParameter('paywall.headline', t('paywall.headline'));
```
The SDK shows the text for that language, falling back from a region to its language (`pt-BR`
to `pt`), and your translation for any language the value lacks. Without `setLocale` it uses the
page's `` or the device's language. In React, call `useTrevo()?.setLocale(tag)`; on a
server, pass `{ locale }` to `getParameter`. Builds from before text per language show your
translation to everyone, so Trevo's pull request notes an SDK that is too old.
## Ideas from Trevo
Trevo's repo scan finds the parameters your app reads. When an idea only changes their values,
the proposal says so: approving it opens no pull request, and you start it straight away. Trevo
won't propose a value another experiment already sets.
On a mobile app, an idea that changes one piece of text, one number or one on/off switch can
set up a new parameter, and on an app that translates its text, the idea writes the new text in
every language it ships. Its pull request makes the app read it, with today's value as the default,
and every later idea on it is values-only. When the experiment ends, the read stays in your code.
## What the app gets
* **The running experiment's value.** `getParameter` assigns the user exactly as
`getVariant` would, records the exposure, and returns that variant's value.
* **The default** when no experiment sets the parameter, before config has loaded, or when
a value's type differs from the default's. A bad value never reaches code typed for
something else.
* **One experiment's value at a time.** A running test takes over a parameter from a
shipped winner; between two shipped winners, the newer one wins.
* **The winner's value after you ship.** A shipped experiment keeps serving its winning
value until a newer experiment takes the parameter, because the default in your code is
still the old value. Updating that default is optional: it matters only if you stop
serving config.
One running or paused experiment can set a given parameter at a time. Starting a second
one on the same parameter is refused until the first ends.
## Supported SDKs
`getParameter` is in the browser, React Native, iOS, Android, Flutter and Node SDKs, and
`useParameter` in `@trevosdk/react`. Python and Ruby don't have it yet.
# Paywall and pricing experiments
Source: https://docs.trevosdk.com/concepts/paywall-experiments
Test paywalls, plans and prices with the billing tool you already use, and judge them by revenue.
Trevo never draws your paywall and never charges anyone. Your billing tool keeps doing both.
Trevo tells your app which version of the paywall to show, and counts what each version earns.
## How it works
1. **One pull request, one release.** Trevo's pull request changes two places in your app:
* the paywall reads what to show from [parameters](/concepts/parameters), such as
`paywall.offering` or `paywall.headline`;
* the code where a purchase succeeds reports it with its amount.
2. **After that, a paywall test is values only.** You approve and start it from the dashboard,
with no pull request and no release.
3. **Your app hands Trevo's value to your billing tool,** which shows the paywall and takes the
payment as it does today.
4. **Results compare revenue per user** for each version, beside the conversion rate.
## Report each purchase
Send a `purchase` event once the purchase has completed, not when it starts, with the amount paid:
```ts theme={null}
trevo.track('purchase', {
value: 49.99, // the price paid in major units, read from your billing SDK
currency: 'USD', // ISO code; leave it out to use your workspace's currency
product: 'pro_annual',
});
```
| Property | Meaning |
| - | - |
| `value` | The amount paid, as a number in major units such as `49.99`: convert amounts in cents or micros, as Stripe and Google Play give them. A numeric string such as `"49.99"` also counts. |
| `currency` | The ISO 4217 code. Trevo converts every amount into your workspace's reporting currency. |
| `product` | Optional. The product, package or price identifier. |
| `kind` | Optional. `trial` for a free trial start (counts as a conversion worth nothing), `refund` to subtract an amount. Anything else counts as a purchase. |
| `trial_days` | On a trial start: how many days the trial lasts. Trevo uses it to count every person over the same number of days. |
## Report from your server too
Your app sees a purchase while it is open. A trial that turns paid, a renewal or a refund happens
later, and only your billing tool and your server learn about it. Report those from the server,
where it already receives your billing tool's events or runs its own billing, with a server key:
```ts theme={null}
trevo.track(
'purchase',
{ anonymousId: customer.metadata.trevo_id }, // or { userId } for a signed-in user
{ value: toMajorUnits(amount, currency), currency, product: plan.id }, // whole units, not cents
{ insertId: event.id }, // the billing event's own id, so a repeated delivery counts once
);
```
* **Name the person who saw the paywall.** Save the user's Trevo id on your billing customer as
`trevo_id` (in its metadata or attributes) where you create the checkout or set up the billing
SDK, and report with it. Never use the billing tool's own customer id.
* **The server's word wins.** For anyone your server reported, Trevo counts the server's amounts
and ignores the app's copy of the same purchase. Keep the app's report for everyone else.
* **Send test-mode and sandbox events only with a development key,** never the production one.
* **No Trevo server SDK?** Send the same event with one HTTPS request to
`https://ingest.trevosdk.com/v1/events` and your secret key. See [REST](/install/rest).
Trevo's pull request adds both, where it finds the code that learns about payments.
Trevo reads amounts on an experiment's primary event when that event is `purchase`, or when the
experiment is decided by revenue per user. An event without `value` still counts as a conversion
and adds nothing to revenue.
## Hand the value to your billing tool
Trevo works with any billing tool, and with billing you built yourself: it reads what your code
does, not a list of providers. For example:
| Billing | What your app does with Trevo's value |
| - | - |
| RevenueCat | Fetches the offering with that name |
| Superwall | Sets it as a user attribute, or picks the placement to register. A rule in Superwall maps it to a paywall. |
| Stripe | Uses it as the Price ID when it creates the checkout |
| Your own billing | Reads it wherever it decides the plan, price or copy |
When a tool draws the paywall from its own dashboard, you design it in that tool's editor and
Trevo only tests it. The parameter that picks which paywall shows ends in the name your code passes
the paywall's id under, such as `paywall.offering` for code that passes `offering`, or
`paywall.choice` when the code passes the id without a name. Trevo's pull request passes every
other parameter to the paywall as a variable before it opens, through whatever the tool offers,
such as custom variables or user attributes. The pull request lists the variables to add; add them
in the tool's editor, then publish.
### A new design in your paywall tool
To test a new layout of a paywall your tool draws, Trevo writes a **brief**: the layout, every line
of copy, the products it offers and the values it shows. Your team builds that paywall in the
tool's editor, then enters its id on the experiment's **Edit** page as the value of the parameter
that picks the paywall. Trevo never creates or edits anything in your tool's account, and it won't
start the experiment until the id is in, since both versions would otherwise show today's paywall.
### When your tool picks the paywall
If your code shows whichever paywall the tool picks (its current offering, or the paywall a
campaign rule matches), the tool may be running its own test there. The idea, the experiment page
and the pull request say so. Pause the tool's test while Trevo's runs, or each result includes the
other's change. It is a caution, never a block.
## Real plans and prices
Trevo proposes only plans and prices you sell. It reads the plan, offering, product and price ids
your code uses, and what people really paid per `product` in the last 90 days from your `purchase`
events, with no billing tool's API and no key to paste. A paywall idea that names an id found in
neither place is sent back, unless your team fills it in from a brief.
## How a change goes live
Every idea, every experiment page and every pull request says how the change reaches users:
| Route | When | You |
| - | - | - |
| Values only | Your app already reads every value the test changes | Start the experiment. No pull request, no release. |
| Merge and deploy | Code in a web app or a server | Merge the pull request: the experiment starts when it merges. |
| Over the air | Code in a mobile app that downloads updates itself (such as EAS Update or Shorebird) | Merge, and push an over-the-air update. No store review. |
| Built in your paywall tool | A new design of a paywall your tool draws | Build it from the brief, enter its id, start the experiment. |
| App release | Code in a mobile app | Merge and ship a release. The test measures people on builds with it. |
## Lists, orderings and translated text
* **JSON in a text parameter.** A text value may hold JSON of up to 4,000 characters: a list of
plans, feature bullets or an ordering. Every version must have the shape your app reads today,
the same keys and the same kinds of values, or Trevo refuses it, since your app would fall back
to its default and that version would equal control. Your app parses the value and keeps its
default when parsing fails.
* **Text per language.** In an app that translates its text, a headline or other copy can carry one
text per language your app ships. Trevo reads your languages from your translation files, and the
idea writes the new text in each for your team to check. The SDK shows the text for the app's
language and falls back to your app's own translation for any other. Call `setLocale` where your
app picks or changes its language, so the SDK matches what users see; Trevo's pull request adds
it. Text per language needs @trevosdk/browser 0.3.8, @trevosdk/react-native 0.1.6,
@trevosdk/node 0.1.4, or 0.1.1 of the iOS, Android and Flutter SDKs. An older build shows your
own text to everyone, and still counts in the results.
## How revenue is judged
* **Revenue per user** is each arm's revenue divided by everyone in that arm, buyers or not. It
is tested with the same always-valid sequential method as conversion rates, so you can check
whenever you like.
* **One big spender can't decide a test.** A revenue result needs at least 10 buyers in each arm
before it can be called, and one large purchase can't make it significant on its own. Each
person's revenue also counts only up to the 99th percentile of buyers, which starts trimming the
largest purchases once a test has more than about 100 buyers.
* **Refunds subtract,** and a person's revenue never goes below zero.
* **Trials are counted fairly.** Once people in a test start trials, revenue counts every person
over the same number of days (how long the trials last, plus 3), and only people who entered at
least that long ago, so a version that charges at once can't win just because the other's trials
haven't ended. While trials have started and no payment reported by your server has followed
any, revenue decides nothing and the results say so.
* **Which measure decides** is set per experiment: conversion rate or revenue per user. Paywall
ideas from Trevo are decided by revenue per user when a server reports your payments, and by how
many people buy otherwise, with revenue shown beside it. In an experiment decided by conversion rate, any
version that earns significantly less per user than the original is treated like a harmed
guardrail: the experiment isn't shipped on its own.
* **Currency.** Choose the reporting currency in **Settings → General**. Amounts are converted
with the European Central Bank's latest daily reference rates; an amount in a currency the ECB
doesn't publish is left out and counted in the results' notes.
## Limits
* A new paywall layout drawn in your app's native code needs a release, unless your app ships over
the air or a tool draws it from its own dashboard.
* Without a server report, Trevo sees only what happens while your app is open: a purchase or a
trial start, not a trial turning paid, a renewal or a refund made later. Trevo then doesn't
propose a test that changes the trial itself.
* Amounts are what the buyer paid, before store commission and tax. They are right for comparing
versions, not for accounting.
* Prices must already exist in your billing tool or store. A price test chooses among products you
already sell.
# Reading results
Source: https://docs.trevosdk.com/concepts/reading-results
Conversion rate, lift, guardrails, and why you can check whenever you like.
An experiment produces one number per arm — the conversion rate — and one judgement: whether
the difference between them is real.
## Conversion rate
```
conversion rate = conversions ÷ exposures
```
Per arm. Raw counts are not the comparison, because arms rarely receive identical traffic and
splits are not always even.
| | Control | Variant |
| - | - | - |
| Exposures | 500 | 500 |
| Conversions | 90 | 130 |
| **Rate** | **18.0%** | **26.0%** |
## Lift
Two ways to express the same movement:
* **Absolute** — subtract the rates: `26.0% − 18.0%` = **+8.0 points**
* **Relative** — the proportional change: `8.0 ÷ 18.0` = **+44%**
Both are correct. Relative is the larger, more quotable number; absolute tells you how many
additional humans actually converted. When someone reports a big win, check which one they
mean — a lift from 0.2% to 0.3% is "+50%" and also almost nothing.
## Significance, and why you can peek
A gap between two rates might be a real effect or ordinary randomness. Flip 500 coins twice
and you won't get 250 both times.
Classical A/B testing handles this by making you fix a sample size in advance and look only
once at the end. Checking early inflates your false-positive rate badly — a dashboard you
refresh daily will show you "winners" that evaporate.
Trevo uses **mSPRT**, a sequential test. Its results are *always valid*: you can look as often
as you like, stop as soon as it declares a winner, and the error rate still holds. That fits
how people actually use these tools, rather than requiring a discipline nobody sustains.
Practically: check whenever you want, and act when Trevo says the result is conclusive rather
than when the numbers first look good.
## Revenue per user
When the primary event is a `purchase` carrying `value` and `currency`, or the experiment is
decided by revenue per user, each arm also shows **revenue per user**: its revenue divided by
everyone in the arm, buyers or not, and **paid conversion**, the share who paid anything.
```
revenue per user = revenue ÷ exposures
```
An experiment is decided either by conversion rate or by revenue per user, and the choice locks
with its conversion events once the experiment moves past approval, when its pull request is
generated or it launches. Revenue matters whenever a version could sell more at a lower price: a
cheaper plan can win on conversion rate and still earn less. That is why any version that earns
significantly less per user is treated like a harmed guardrail. See
[Paywall and pricing experiments](/concepts/paywall-experiments) for how amounts are reported,
converted and capped.
Once people in a test start free trials, revenue counts each person over the same number of days
(how long the trials last, plus 3) and only people who entered at least that long ago, and the
results say which people that is. While trials have started and no payment reported by your server
has followed any, revenue calls no winner: the payment from a trial may simply not be reported yet.
In a test of text per language, everyone who reaches the screen counts, including people whose
language the new text doesn't cover and people on builds too old to read it: they see your app's
own text, the same as control. That can only shrink the measured difference, never fake one, and
Trevo writes the text in every language it finds in your app so the gap stays small.
## Guardrails
The decision metric decides the winner. A **guardrail** catches the case where winning that
metric broke something downstream.
Say a more aggressive CTA lifts `signup_started` by 40%. Real win — unless
`signup_completed` fell, in which case you pulled in people who bounce a screen later and
your funnel is worse overall.
Pick a guardrail one step *after* your decision metric, or one that represents quality rather
than volume. A result that moves the decision metric and damages the guardrail is not a win,
regardless of how good the headline looks.
## Inconclusive results are results
Many experiments end with no detectable difference, and that's normal — it means your change
didn't matter as much as you hoped, which is worth knowing cheaply.
Two different endings look similar and aren't:
* **No effect detected, enough traffic** — the change genuinely doesn't move this metric. Ship
whichever version you prefer for other reasons, and move on.
* **Not enough traffic yet** — the test cannot yet distinguish a real effect from noise. Keep
running, or accept that an effect this small needs more traffic than you have.
Small effects need a lot of users. If your conversion rate is 2% and you're hoping to find a
10% relative improvement, that's tens of thousands of exposures per arm. Testing bolder
changes is often the faster path than waiting on more traffic.
## After a winner
When a result is conclusive, the losing code is dead weight. Ship the winner from the
experiment page and Trevo opens a cleanup PR that promotes it into permanent code and
removes the variant along with the `getVariant()` call.
Merging that promptly matters more than it sounds: unresolved experiments accumulate into
conditional logic nobody remembers the reason for, which is the flag debt this whole workflow
exists to avoid.
# Core concepts
Source: https://docs.trevosdk.com/getting-started/core-concepts
The vocabulary, in one page.
Everything in Trevo is built from a handful of ideas. This page is the whole vocabulary; the
[Concepts](/concepts/experiments-and-variants) section goes deeper on each.
## Experiment
One question you're testing, with a key you reference in code:
```ts theme={null}
trevo.getVariant('checkout-cta');
```
## Control and variant
The two (or more) versions being compared. **Control** is your current behaviour — the
baseline. A **variant** is a proposed change. Both ship in the same build and run at the same
time; different users get different ones.
Nobody sees both. There's no side-by-side comparison — each user gets one version and is
unaware the other exists.
## Traffic split
What share of users lands in each arm, summing to 100. A 50/50 split is the default and the
usual choice, since equal groups reach a conclusion fastest.
## Identity and assignment
Which variant you get is a hash of your **identity** plus the experiment key. Same identity,
same key, same variant — every time, on every device, with no network call.
Identity is your `userId` once you've called `identify()`, and an anonymous id stored in the
browser before that. Anonymous ids are per browser, so one person on a laptop and a phone is
two participants until they sign in.
Because identity determines assignment, **calling `identify()` can change someone's
variant** — see [Variant mismatch](/troubleshooting/variant-mismatch).
## Exposure
"This user saw this variant." Fires automatically inside `getVariant()`.
Exposure is the **denominator** of your results. If you call `getVariant()` somewhere the
user never actually sees the thing, you inflate the denominator and dilute your measured
effect.
```ts theme={null}
// read the assignment without recording an exposure
trevo.getVariant('checkout-cta', { trackExposure: false });
```
## Conversion
"The thing I care about happened." The **numerator**. It only exists where you write it:
```ts theme={null}
trevo.track('purchase_completed', { value: 49.99 });
```
Trevo has no autocapture. No clicks, no pageviews, nothing implicit.
## Conversion rate, and lift
```
conversion rate = conversions ÷ exposures (per arm)
```
**Lift** is how much better the variant did:
* **Absolute** — subtract the rates. 18% → 26% is +8 percentage points.
* **Relative** — the percentage change. The same move is +44%.
Both are true. Relative is the bigger number and the one usually quoted; absolute tells you
how many extra people actually got through.
## Decision metric and guardrail
The **decision metric** is the conversion event that determines the winner.
A **guardrail** is a second event that catches collateral damage — the case where a variant
wins the click but breaks what comes after. Winning the first step while destroying the
second is not a win, and the guardrail is what makes that visible.
## Statistical significance, and mSPRT
A gap between two rates might be real, or it might be noise. **Significance** is the
judgement that it's too large to be chance.
Trevo uses **mSPRT**, a sequential test, which means results stay valid no matter how often
you look. Classical tests require committing to a sample size upfront; checking early
inflates false positives. Sequential testing removes that trap.
## Funnel
An ordered series of events, so you can see which step loses people. Experiments answer "did
this change help?"; funnels answer "where are we losing them?"
## Feature flag
The `if (variant === …)` switch itself. In Trevo the flag is temporary by design — when an
experiment concludes, a cleanup PR promotes the winner and deletes the branch along with the
`getVariant()` call.
## Putting it together
> 1,000 users reached the location gate. 500 saw control, 500 saw the variant — that's
> **exposure**. 90 and 130 respectively got through — that's **conversion**. So 18% versus
> 26%: a +8 point **absolute lift**, +44% **relative**. **mSPRT** says that gap is larger
> than noise, and the **guardrail** confirms the recovered users behaved normally
> afterwards. Ship the variant.
# Quickstart
Source: https://docs.trevosdk.com/getting-started/quickstart
Install the SDK, read a variant, and record a conversion in about ten minutes.
By the end of this page your app will be assigning users to a variant and sending
conversions back to Trevo.
You need a workspace and its SDK key. The key is in **Settings → SDK keys** and looks like
`tsk_live_…`. It is publishable — it ships in your JavaScript bundle by design, and it can
read your experiment config and post events, and nothing else: it cannot read results,
change experiments, or touch workspace settings.
## Where the key goes
Pasting the key into `init()` is fine for a first test. For anything deployed, put it in
an environment variable so rotating it never needs a code change:
| Where you run | Set this variable | Read it as |
| - | - | - |
| Next.js | `NEXT_PUBLIC_TREVO_API_KEY` | `process.env.NEXT_PUBLIC_TREVO_API_KEY` |
| Vite | `VITE_TREVO_API_KEY` | `import.meta.env.VITE_TREVO_API_KEY` |
| Node server | `TREVO_SECRET_KEY` | `process.env.TREVO_SECRET_KEY` |
| Python server | `TREVO_SECRET_KEY` | `os.environ["TREVO_SECRET_KEY"]` |
| Ruby server | `TREVO_SECRET_KEY` | `ENV.fetch("TREVO_SECRET_KEY")` |
Two rules keep this from going wrong:
* **Match the key class to the surface.** Browsers use the publishable `tsk_live_…` key.
Server SDKs use a **server** key (`tsk_secret_…`, created in Settings → SDK keys with
platform *Server*), which must never reach a browser — the API rejects a secret key
sent with an `Origin` header for exactly that reason.
* **Redeploy after adding or rotating a key.** Bundlers compile public env vars into
your JavaScript at build time, and hosts like Vercel apply env changes to *new*
deployments only. Until you redeploy, the live build keeps the old key and its events
are rejected.
## 1. Install
```bash theme={null}
npm install @trevosdk/browser
```
No bundler? Load the CDN build instead — it exposes a global called `Trevo`. Pin the exact
version in production:
```html theme={null}
```
## 2. Initialise
Once, as early as your app boots:
```ts theme={null}
import trevo from '@trevosdk/browser';
trevo.init({ apiKey: 'tsk_live_…' });
```
Call `identify()` when you know who the user is — usually right after login:
```ts theme={null}
trevo.identify(currentUser.id);
```
Identity decides which variant a user gets, so calling `identify()` later can move
someone from one variant to another. Call it as early as you can, and before rendering
anything you are testing.
## 3. Read a variant
```ts theme={null}
export function subscribeToCheckoutVariant() {
let active = true;
const apply = () => {
if (!active || !trevo.isReady()) return;
const variant = trevo.getVariant('checkout-cta');
renderCheckout(variant);
};
const unsubscribe = trevo.onChange(apply);
void trevo.ready().then(apply);
return () => {
active = false;
unsubscribe();
};
}
// Start once at the page/component lifecycle boundary. In an SPA, call the
// returned function when that boundary unmounts.
const stopCheckoutExperiment = subscribeToCheckoutVariant();
```
`getVariant()` is synchronous and does no network call — assignment is a local hash of
the user's identity and the experiment key. The same user always gets the same variant.
Keep your existing loading boundary visible until the first `apply`; reading once before
`ready()` can return control and never update when config arrives.
It returns `'control'` for an experiment key it has never seen, so shipping this code
before the experiment exists in Trevo is safe.
Calling `getVariant()` also records an **exposure** — "this user saw this variant". That
is the denominator for your results, so only call it where the user genuinely sees the
thing. To read an assignment without recording an exposure:
```ts theme={null}
const variant = trevo.getVariant('checkout-cta', { trackExposure: false });
```
## 4. Record a conversion
Nothing is tracked automatically by the browser SDK (`@trevosdk/react`'s provider is the
one exception — it emits a `page_view` on mount). A conversion exists only where you write
one:
```ts theme={null}
trevo.track('purchase_completed', { value: 49.99, plan: 'pro' });
```
Events are batched and sent in the background, including on page unload. You do not need
to flush manually, though `trevo.flush()` exists if you want to force it.
## 5. Check it arrived
Open **Data → Events** in your workspace and refresh — the table doesn't auto-update. Your
event should appear within a few seconds. **Settings → Setup Trevo** polls live if you'd
rather watch it arrive.
From a terminal, the [CLI](/install/cli#check-an-sdk-install) can wait for it instead:
```bash theme={null}
trevo connect --wait
```
It exits `0` once a new event arrives, so a coding agent can confirm the install on its own.
If nothing shows up, see [No events arriving](/troubleshooting/no-events-arriving).
## What to do next
* **Using React?** [`install/react`](/install/react) has a provider and a hook that
handle initialisation for you.
* **On Next.js?** [`install/nextjs`](/install/nextjs) resolves variants on the server
so the first paint is already correct — no flash of the control version.
* **Tracking conversions on a backend?** [`install/node`](/install/node),
[`install/python`](/install/python), or [`install/ruby`](/install/ruby). Server-side
events are immune to ad blockers and closed tabs, which improves the numbers for your
browser experiments too.
* **Building a mobile app?** The [iOS](/install/ios), [Android](/install/android),
[Flutter](/install/flutter) and [React Native](/install/react-native) SDKs bucket users
identically to the web and are built for offline queues and app-store constraints.
* **Multiple variants?** `defineExperiment()` gives you a typed union and makes an
unhandled variant a compile error. See [Typed variants](/install/browser#typed-variants).
## The whole thing
```ts theme={null}
import trevo from '@trevosdk/browser';
trevo.init({ apiKey: 'tsk_live_…' });
// Call this from the app's real signed-in lifecycle, before experiment UI.
trevo.identify(currentUser.id);
const render = () => {
if (!trevo.isReady()) return;
const variant = trevo.getVariant('checkout-cta');
if (variant === 'treatment') {
showNewCheckout();
} else {
showCurrentCheckout();
}
};
const unsubscribe = trevo.onChange(render);
void trevo.ready().then(render);
// later, when the user converts
trevo.track('purchase_completed', { value: 49.99, plan: 'pro' });
// In an SPA, call unsubscribe() when this UI boundary unmounts.
```
# What is Trevo
Source: https://docs.trevosdk.com/getting-started/what-is-trevo
An AI agent that proposes experiments from your codebase and ships them as pull requests.
Trevo is an A/B testing platform where the experiments arrive as pull requests.
You connect a repository. Trevo reads it, proposes an experiment with a hypothesis grounded
in your actual code, and — once you approve — opens a PR containing both variants behind a
flag, plus the tracking calls needed to measure it. You review the diff like any other PR,
merge it, and real traffic decides the outcome. When there's a winner, you ship it with one
click and a cleanup PR promotes it and deletes the loser.
## Why this shape
Running an experiment normally has two bottlenecks: someone has to think of what to test,
and an engineer has to build both versions. That's why most teams run a handful of tests a
year rather than hundreds.
Trevo's bet is that an agent can do both, and that the output should be **code in your
repository** rather than configuration in someone else's dashboard.
That last part is the real difference from older tools. Visual editors inject JavaScript
that rewrites your page at runtime, which is why those sites flicker and why the experiment
is invisible to your codebase. Trevo never touches the DOM. Your own code branches on a
variant:
```ts theme={null}
const variant = trevo.getVariant('checkout-cta');
if (variant === 'treatment') {
// your alternate experience
}
```
Which means experiments go through code review, run in CI, and are removed by a PR when
they're done. No accumulated flag debt, no drift between what's deployed and what's
configured.
## What the SDK does
Very little, deliberately. Two things:
1. **Answers "which variant is this user in?"** — a local hash of the user's identity and
the experiment key. No network call, deterministic, sub-millisecond.
2. **Reports what happened** — exposures when a variant is seen, conversions when you call
`track()`.
Everything else — deciding what to test, writing the variants, calling the winner — happens
in Trevo, not in your bundle. The browser SDK is under 10kb gzipped.
## What you need
* **A web app to experiment on.** SDKs ship for the browser
([`@trevosdk/browser`](/install/browser)), [React](/install/react), and
[Next.js](/install/nextjs). Apps use [iOS](/install/ios), [Android](/install/android),
[Flutter](/install/flutter) or [React Native](/install/react-native).
Backends track and assign with [Node](/install/node), [Python](/install/python), or
[Ruby](/install/ruby); other languages can record conversions over [REST](/install/rest).
* **Live traffic.** Experiments need users. How many depends on your conversion rate and the
size of the effect you're looking for.
* **Conversion events you've instrumented.** Trevo has no autocapture — a conversion exists
where you write `track()`. This is the step people most often skip, and without it an
experiment runs but can never produce a result.
## How results are decided
Trevo uses **mSPRT**, a sequential test. The practical consequence is that you can look at
results whenever you like without invalidating them.
That isn't true of classical A/B statistics, where you commit to a sample size in advance
and checking early inflates your false-positive rate — peek at a dashboard daily and you
will "find" winners that aren't real. Sequential testing is built for the way people
actually use these tools.
More in [Reading results](/concepts/reading-results).
## Where to start
* [Quickstart](/getting-started/quickstart) — install the SDK and record your first conversion
* [Core concepts](/getting-started/core-concepts) — the vocabulary, in one page
# Android
Source: https://docs.trevosdk.com/install/android
Experiments and tracking for Kotlin and Java Android apps, assigning the same variants as the web.
`com.trevosdk:trevosdk-android` runs experiments and records events in Android apps, assigning
the same variant the web SDK does for the same user. Kotlin, no dependencies beyond the Kotlin
standard library, Android 5.0 (API 21) and later. Kotlin projects need Kotlin 2.0 or later; Java
projects work as they are.
```kotlin theme={null}
// build.gradle.kts
dependencies {
implementation("com.trevosdk:trevosdk-android:0.1.1")
}
```
The library declares the `INTERNET` permission, which merges into your manifest.
## Create the client
Use a **Mobile** key (`tsk_live_…`). Keep it in your build configuration, for example a
`buildConfigField`, and create one client in `Application.onCreate`:
```kotlin theme={null}
class App : Application() {
override fun onCreate() {
super.onCreate()
trevo = TrevoClient.create(this, TrevoOptions(apiKey = BuildConfig.TREVO_API_KEY))
}
companion object {
lateinit var trevo: TrevoClient
}
}
```
The client reads the build's `versionName`, so `minAppVersion` gating and the version on every
event work with no setup. Every method is safe to call from any thread. Create it in the main
process only: a second process would share its files.
## Read a variant
`getVariant` is synchronous and safe on the main thread. It returns `control` until stored
state and the first config fetch have loaded, so wait for `ready()` (a suspend function) or
`whenReady { }` before showing experiment UI:
```kotlin theme={null}
@Composable
fun CheckoutButton() {
var variant by remember { mutableStateOf(null) }
LaunchedEffect(Unit) {
App.trevo.ready()
variant = App.trevo.getVariant("checkout-v2")
}
when (variant) {
null -> Unit
"treatment" -> Button(onClick = { App.trevo.track("checkout_started") }) { Text("Start free trial") }
else -> Button(onClick = { App.trevo.track("checkout_started") }) { Text("Subscribe") }
}
}
```
Each call records an **exposure** the first time. Pass `trackExposure = false` to read without
recording one. `onChange` calls a listener on the main thread whenever config or identity
changes; keep the returned `TrevoSubscription` and `cancel()` it when the screen goes away.
## Parameters
A [parameter](/concepts/parameters) lets later experiments change a value with no release:
```kotlin theme={null}
val headline = trevo.getParameter("paywall.headline", "Subscribe")
val trialDays = trevo.getParameter("paywall.trial_days", 7)
```
There are overloads for `String`, `Boolean`, `Int`, `Long` and `Double`. A value of another
type, or a number that isn't whole for `Int` or `Long`, serves the default.
A `String` parameter can carry [text per language](/concepts/parameters#lists-and-translated-text):
pass your app's own translation as the default, and if users can pick the app's language, call
`trevo.setLocale("pt-BR")` when they do. Without it the SDK reads the app's configured locale.
## Track events and identify users
```kotlin theme={null}
trevo.track("checkout_completed", mapOf("plan" to "pro", "seats" to 3))
trevo.identify(user.id) // after sign-in, and on launch when auth restores a user
trevo.reset() // on sign-out: clears the user and starts a new anonymous id
```
Property values are strings, numbers, booleans, lists, maps or null. Events are queued on disk
and sent in batches every 15 seconds, when the app moves to the background, and on `flush()`.
See [Mobile experiments](/concepts/mobile-experiments) for how experiments ramp on mobile, how
the SDK survives a lost network, and the Google Play data safety answers.
## Options
| Option | Default | Notes |
| - | - | - |
| `apiKey` | | Required. A Mobile key, `tsk_live_…` |
| `appVersion` | The app's `versionName` | Sent on every event; compared with `minAppVersion` |
| `bootstrapConfig` | empty | Assign before storage and the network answer |
| `pollIntervalMs` | 300000 | Config is also refreshed on every foreground |
| `flushIntervalMs` | 15000 | Also flushes when the app moves to the background |
| `maxBatchSize` | 50 | Capped at 500 by the server |
| `configUrl`, `ingestionUrl` | Trevo | Endpoint overrides for proxied installs |
| `storage`, `transport`, `lifecycle` | Files, HttpURLConnection, activity lifecycle | Replace for tests or your own stack |
| `onError` | Logcat | Background failures; the SDK never throws |
## Correctness
The library runs the shared conformance vectors in CI, so a change that would assign a user
differently from the web fails the build. The rules are in the
[bucketing spec](/reference/bucketing-spec).
# Browser
Source: https://docs.trevosdk.com/install/browser
Install the JavaScript SDK in any web app, with or without a bundler.
`@trevosdk/browser` assigns variants and records events in the browser. It never touches
the DOM — your own code branches on the variant it returns.
Under 10kb gzipped, no dependencies. This is the plain JavaScript SDK — on React use
[`@trevosdk/react`](/install/react), which wraps it in a provider and a hook.
## Install
```bash theme={null}
npm install @trevosdk/browser
```
### Without a bundler
The CDN build exposes a global called `Trevo`. **Pin the exact version in production** —
the floating channels change under you with no deploy on your side.
```html theme={null}
```
| URL | Updates | Cache |
| - | - | - |
| `…/browser/v0.3.8/trevo.min.js` | never | 1 year |
| `…/browser/v0/trevo.min.js` | patches and minors within v0 | 5 minutes |
| `…/browser/latest/trevo.min.js` | every release | 5 minutes |
Use `v0` or `latest` for prototyping only.
## Initialise
```ts theme={null}
import trevo from '@trevosdk/browser';
const apiKey = import.meta.env.VITE_TREVO_API_KEY;
if (!apiKey) throw new Error('Missing VITE_TREVO_API_KEY');
trevo.init({ apiKey });
```
Use your bundler's public prefix — `NEXT_PUBLIC_`, `VITE_`, `PUBLIC_`. Fail explicitly when
it is missing; passing an empty string makes setup fail later and is much harder to diagnose.
The key is publishable (`tsk_live_…`) and belongs in your client bundle. Server keys
(`tsk_secret_…`) are rejected from browsers.
[Where the key goes](/getting-started/quickstart#where-the-key-goes) lists the variable
for each stack — and why a key change needs a redeploy.
`init()` is re-entrant — calling it again reconfigures rather than duplicating.
### Options
| Option | Default | Notes |
| - | - | - |
| `apiKey` | — | Required |
| `bootstrap` | — | Pre-resolved `{ experimentKey: variantName }` for a correct first paint. See [Next.js](/install/nextjs) |
| `manualReveal` | `false` | With the anti-flicker snippet, wait for your `reveal()` instead of revealing automatically |
| `ingestionUrl` | — | Endpoint override for proxied installs |
| `configUrl` | — | Endpoint override for proxied installs |
## Identify the user
```ts theme={null}
trevo.identify(currentUser.id);
```
Before this, users are bucketed on an anonymous id kept in local storage and mirrored to a
`trevo_id` cookie (1 year, SameSite=Lax) — the cookie is what lets your backend and SSR
bucket the same visitor. After it, they
are bucketed on your user id — which means **`identify()` can change a user's variant**.
Call it as early as you can, and before rendering anything under test.
Anonymous ids are per browser, so the same person on a phone and a laptop is two
participants until they sign in.
On logout:
```ts theme={null}
trevo.reset();
```
The user id is cleared and a fresh anonymous id is minted, so the SDK keeps
assigning and tracking — the visitor is simply a new anonymous participant.
## Read a variant
```ts theme={null}
const apply = () => {
if (trevo.isReady()) renderCheckout(trevo.getVariant('checkout-cta'));
};
const unsubscribe = trevo.onChange(apply);
void trevo.ready().then(apply);
```
Synchronous, no network call, and deterministic — the same identity and key always produce
the same variant. Unknown keys return `'control'`, so this is safe to ship before the
experiment exists.
The first call records an **exposure**, deduplicated per identity and variant within a
10-minute window. Calls made before config has loaded return `control` and record nothing,
so a page that reads only once, before `ready()`, never counts that visitor. The SDK warns in
the console and reports a `read_before_ready` SDK error for it, once per experiment, and the
experiment's page in the dashboard shows how many visitors were missed. A read after a failed
first config fetch is reported as `config_fetch_failed` instead. Read inside
`onChange()` and after `ready()`, as above, and it never fires. To read without recording an
exposure:
```ts theme={null}
trevo.getVariant('checkout-cta', { trackExposure: false });
```
### When an experiment stops
A visitor already in an experiment gets `'control'` once it leaves the config: paused, ended,
rejected, stopped by a guardrail, or shipped more than 30 days ago. An open page switches on the
next config poll (`onChange()` fires), and those reads record no exposure. The visitor's variant
stays cached, so a resumed experiment brings them back to the same one.
Until a config has loaded, the cached variant is still served. A variant passed in `bootstrap`
holds until a config fetch succeeds, so server-rendered pages don't flash control.
The shipped case means that on day 30 every bucketed visitor reverts to control, including those
on the winning variant. Merge the cleanup PR, or remove the `getVariant()` call, before then. See
[Unknown keys return control](/concepts/experiments-and-variants#unknown-keys-return-control).
### Typed variants
`defineExperiment()` returns a typed union and turns an unhandled variant into a compile
error — so a variant added in Trevo that your code does not handle fails the build instead
of silently falling through:
```ts theme={null}
import { defineExperiment, assertNever } from '@trevosdk/browser';
const emailTiming = defineExperiment('email-capture-timing', [
'control',
'before-checkout',
'after-payment',
]);
const variant = trevo.getVariant(emailTiming);
switch (variant) {
case 'control': return;
case 'before-checkout': return showEmailBeforeCheckout();
case 'after-payment': return showEmailAfterPayment();
default: return assertNever(variant);
}
```
## Track conversions
```ts theme={null}
trevo.track('purchase_completed', { value: 49.99, plan: 'pro' });
```
Batched automatically — a flush is triggered once 50 events are queued or every couple of
seconds, and on page unload; a single request carries up to 500 events (the server's cap).
`trevo.flush()` forces a send if you need one.
Every event carries the page's `path` and `host` (the hostname, lowercased, no port), so two
apps on one workspace, such as `example.com` and `app.example.com`, can be told apart. Query
strings and hashes are never captured.
Limits: event names up to 500 characters using `A–Z a–z 0–9 _ . - $` only (anything else
is dropped with a console warning); properties up to 8KB serialised.
## Waiting for config
On a first visit the SDK has no cached config, so `getVariant()` returns `'control'` until
the first fetch lands. Returning visitors read from a warm cache and are correct
immediately.
```ts theme={null}
if (trevo.isReady()) {
// safe to read synchronously during render
}
await trevo.ready(); // resolves when config loads, or the first fetch fails
```
Config is polled every 60 seconds and cached in local storage for 24 hours, so a slow
network delays the first visit only.
`ready()` also resolves after the first fetch fails. Keep the `onChange()` subscription shown
above so a later successful poll updates the view instead of pinning that visitor to control.
To avoid the flash of control on a first visit entirely, either resolve variants on the
server ([Next.js](/install/nextjs)) or use the anti-flicker snippet below.
## Anti-flicker
Hides the page until variants are resolved, with a safety timeout so a blocked or failed
SDK can never leave your page blank:
```ts theme={null}
import { ANTI_FLICKER_SNIPPET } from '@trevosdk/browser';
```
Inline it in a `
```
Set it in a script that runs **before** the snippet — it's read once, at snippet
execution — and values above 10 s are clamped to 10 s.
With `manualReveal: true`, call `trevo.reveal()` once you have committed the variant.
Server-side bootstrapping is better where you can do it — nothing is hidden and there is
no timeout to tune.
## Consent and opt-out
```ts theme={null}
trevo.optOut(); // stops everything, clears identity, drops queued events unsent
trevo.reset(); // clears the user and mints a fresh anonymous id
```
`reset()` leaves the SDK working: the visitor becomes a new anonymous participant,
so post-logout page views, variant reads and conversions are still recorded.
`optOut()` is the opposite — queued events are discarded rather than delivered, and
no new anonymous id is minted. Both are idempotent and safe to call before `init()`.
## API summary
| Method | Purpose |
| - | - |
| `init(options)` | Start the SDK |
| `identify(userId)` | Set the authenticated user |
| `getVariant(key, options?)` | Resolve a variant, recording an exposure by default. A read before `ready()` records none and is reported as a `read_before_ready` SDK error |
| `trackExposure(key, variant)` | Record an exposure explicitly. Ignored (and reported as a `variant_mismatch` SDK error) if the experiment or variant isn't in the loaded config; deduplicated like any exposure |
| `track(name, properties?)` | Queue a conversion event |
| `flush()` | Send queued events now |
| `isReady()` / `ready()` | Whether config has loaded |
| `reset()` | Clear the user and mint a fresh anonymous id (logout) |
| `optOut()` | Stop all activity and discard queued events (consent withdrawal) |
| `onChange(listener)` | Subscribe to config and identity changes; returns an unsubscribe |
| `reveal()` | Reveal the anti-flicker overlay |
| `destroy()` | Tear down entirely |
# CLI
Source: https://docs.trevosdk.com/install/cli
Drive proposals and experiments from a terminal, a script, or CI.
`trevo` is the dashboard's `/v1` routes with a workspace API key instead of a browser session.
Anything it does, a person could do by clicking — list what Trevo proposed, approve or dismiss,
send revision instructions, ask for a fresh batch, start and end experiments.
```bash theme={null}
npm install -g @trevosdk/cli
trevo login
trevo proposals list
```
It has no runtime dependencies and needs Node 18 or newer.
## Authentication
Make a key under **Settings → API access**. It is shown once.
```bash theme={null}
trevo login # paste the key; stored at ~/.config/trevo/config.json, mode 0600
trevo login --key tsk_api_… # non-interactive
```
Prefer the prompt on a shared machine: a key passed as `--key` is visible in `ps` and lands in your
shell history. In CI, use `TREVO_API_KEY` and never `trevo login`.
The CLI sends the key only to `https://api.trevosdk.com` unless `TREVO_API_URL` says otherwise, and
it refuses to send it over plain `http` to anything but a local address, to a URL carrying
credentials, or over a scheme that is not http(s). Pointing it anywhere other than the product host
prints a warning on stderr — in CI that line is the difference between a redirected key and a silent
one.
In CI, set `TREVO_API_KEY` instead — the environment wins over the stored file, so a job never
writes one:
```yaml theme={null}
- run: trevo experiments list --status running --json
env:
TREVO_API_KEY: ${{ secrets.TREVO_API_KEY }}
```
A key opens **one workspace**, reads everything in it, and writes only what its scopes allow. It
acts as the person who made it. Scopes, refusal codes, and the routes themselves are in the
[API reference](/reference/api).
`tsk_live_` and `tsk_secret_` SDK keys are your site's and are refused here. `TREVO_API_URL`
points the CLI at another host if you run one.
## Commands
```bash theme={null}
trevo proposals list
trevo proposals show
trevo proposals approve # --acknowledge-overlap to run beside an overlap
trevo proposals dismiss --reason too_risky
trevo proposals revise "Keep the copy, make the CTA green" --wait
trevo generate # --replace retires pending drafts when the batch lands
trevo runs # what generation is doing
trevo experiments list --status running # --search text, --limit n
trevo experiments show
trevo experiments create --file experiment.json
trevo experiments start|pause|resume|end|ship [ …]
trevo experiments decide --ship treatment
trevo experiments status
trevo funnels list
trevo funnels pull --file funnels.json
trevo funnels apply --file funnels.json
trevo whoami # which workspace this key opens, and who it acts as
trevo connect # is the SDK installed and sending events?
trevo --version
```
Dismiss reasons, comma-separated for more than one: `not_relevant`, `too_risky`, `tried_before`,
`wrong_metric`, `does_not_match_code`, `not_feasible`, `wrong_area`.
`trevo proposals revise --wait` blocks until the revision lands, up to ten minutes, and exits
non-zero if it fails.
## Check an SDK install
First run `trevo whoami` to confirm the CLI is authenticated to the intended workspace. This checks
the workspace API key; it does not prove that the SDK is installed.
```bash theme={null}
trevo whoami
```
Then ask the workspace whether the SDK has reported in:
```bash theme={null}
trevo connect # has an event arrived?
trevo connect --until loaded # or has the SDK at least fetched its config?
trevo connect --wait # block until something new arrives
```
| Flag | Default | Notes |
| - | - | - |
| `--until event` | yes | Passes once an event has arrived |
| `--until loaded` | | Also passes on a config fetch. Use it when the app sends no event until it calls `track()` |
| `--wait` | | Polls until it passes. Only an event or config fetch newer than its first read counts, so an already-connected workspace can't vouch for a new install |
| `--timeout ` | `600` | How long `--wait` polls before giving up |
Without `--wait` it is a one-off check, and `--until loaded` accepts a config fetch from the last
ten minutes. It exits `0` once the condition is met and `4` until then, so a script or coding agent
can retry on `4` without mistaking it for an API refusal. `--json` adds `reached` and `timedOut`
to the workspace's `firstEventAt`, `lastEventAt` and `lastConfigFetchAt`.
You can also verify the SDK from the running application:
* For a browser SDK, open the app in a real browser and confirm the network panel shows a successful
request to `https://api.trevosdk.com/v1/config`. `curl` and `fetch` do not run the app's JavaScript.
* For a server SDK, start the application and confirm its existing `ready()` call completes without
a Trevo error.
* The dashboard's **Settings → SDK** page shows **installed** after a config fetch and **connected**
after the first tracked event.
If the workspace has already received SDK traffic, preserve the existing integration. Do not add a
second provider, initialization call, or Next.js proxy/middleware wrapper just to match a fresh-install
example.
## Declare an experiment yourself
You do not have to wait for a proposal. `create` takes the same body the dashboard's custom-experiment
form sends:
```json theme={null}
{
"name": "Two-step sample form",
"mechanism": "Fewer fields per screen should raise completion.",
"variants": [
{ "displayName": "control", "trafficSplit": 50 },
{ "displayName": "treatment", "trafficSplit": 50 }
],
"conversionTargets": [{ "eventName": "sample_requested" }]
}
```
```bash theme={null}
trevo experiments create --file experiment.json --generate-pr
```
Splits must sum to 100, and the **first** conversion target is the primary metric — the others may
carry `"role": "guardrail"`. An event your site does not send yet is fine: Trevo Bot wires the
`track()` call in the pull request. The `Idempotency-Key` is derived from the body, so a re-run of the same step
within about ten minutes replays the first result instead of opening a second pull request. Pass
`--idempotency-key` to choose your own.
## Keep funnels in your repository
`pull` writes the definitions as a file to commit; `apply` reconciles a workspace to that file.
Funnels are matched **by name**, so renaming one in the file creates a new funnel rather than
renaming the old one.
```bash theme={null}
trevo funnels pull --file funnels.json # or without --file to print to stdout
trevo funnels apply --file funnels.json --dry-run
trevo funnels apply --file funnels.json
```
`apply` creates what is missing and updates what changed, and is a no-op the second time it runs.
It never deletes unless you pass `--prune` — a partial file must not quietly remove the funnel a
running experiment is judged on.
```json theme={null}
[
{
"name": "Signup",
"steps": [{ "eventName": "visit_pricing" }, { "eventName": "signup" }]
}
]
```
Step order comes from the order in the file unless a step states its own `stepOrder`.
## Following the slow ones
`generate` and `approve` both answer before the work is done — generation is minutes of model work,
and a pull request means Trevo Bot cloning your repository and writing code. Each has a way to
follow it.
```bash theme={null}
trevo generate --wait # blocks until the batch lands; exits 1 if the run failed
trevo runs # or check whenever you like
trevo runs show
```
```bash theme={null}
trevo proposals approve --wait # blocks until the pull request is open
```
`approve --wait` exits `0` with the pull-request URL, and `1` the moment generation ends at
`pr_failed` — it does not sit out the timeout on a failure. Both waits are bounded (`--timeout`,
in seconds; 20 minutes by default for a pull request) and print what to run next if they give up.
Without `--wait` the same answers come from `trevo runs` and
`trevo experiments status `.
## Wait for a status in CI
```bash theme={null}
trevo experiments status exp_123 --wait --until running --timeout 600
```
Exits `0` when the status arrives, `1` when the experiment settles somewhere it will not leave
(`pr_failed`, `rejected`, …) or the timeout passes — `--wait` always ends.
## Output and exit codes
Every command takes `--json` and prints the API response verbatim; without it you get a table or a
line of prose. Exit codes separate the cases a script has to tell apart:
| Code | Meaning |
| - | - |
| `0` | Fine |
| `1` | The API refused. The reason and its `code` are on stderr |
| `2` | Usage — an unknown command, a missing argument, no key configured |
| `3` | Auth — the key is unknown, revoked, or lacks the scope |
| `4` | `trevo connect` only: the SDK has not reported in yet |
So a CI job can tell a revoked key from a proposal that was not approvable:
```bash theme={null}
if ! trevo proposals approve "$ID" --json > result.json; then
case $? in
3) echo "::error::TREVO_API_KEY is revoked or lacks proposals.review" ;;
*) jq -r '.code // .error' result.json ;;
esac
exit 1
fi
```
## In a script
The client the CLI uses is exported, for scripts that would rather call the routes than parse
output:
```ts theme={null}
import { TrevoApi } from '@trevosdk/cli';
const api = new TrevoApi({ apiKey: process.env.TREVO_API_KEY! });
const { items } = await api.listExperiments({ status: 'proposed' });
```
Errors throw `ApiError` carrying `status` and the API's `code`, so a caller can branch on
`SURFACE_OVERLAP` rather than on prose.
# Flutter
Source: https://docs.trevosdk.com/install/flutter
Experiments and tracking for Flutter apps on iOS and Android, assigning the same variants as the web.
`trevosdk_flutter` runs experiments and records events in Flutter apps, assigning the same
variant the web SDK does for the same user. Written in Dart; its one dependency is
`path_provider`. Flutter 3.24 and later, on iOS and Android.
```bash theme={null}
flutter pub add trevosdk_flutter
```
## Create the client
Use a **Mobile** key (`tsk_live_…`), passed in at build time with `--dart-define`. Pass the
installed build's version too; [package_info_plus](https://pub.dev/packages/package_info_plus)
reads it. Create one client for the app's lifetime:
```dart theme={null}
import 'package:flutter/widgets.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:trevosdk_flutter/trevosdk_flutter.dart';
late final TrevoClient trevo;
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
final info = await PackageInfo.fromPlatform();
trevo = TrevoClient(TrevoOptions(
apiKey: const String.fromEnvironment('TREVO_API_KEY'),
appVersion: info.version,
));
runApp(const App());
}
```
`appVersion` is required on purpose: without the real build version, a `minAppVersion`
experiment returns control for everyone. Never hard-code a sample version.
## Read a variant
`getVariant` is synchronous. It returns `control` until stored state and the first config
fetch have loaded, so wait for `ready()` before showing experiment UI:
```dart theme={null}
FutureBuilder(
future: trevo.ready(),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) return const SizedBox.shrink();
final variant = trevo.getVariant('checkout-v2');
return ElevatedButton(
onPressed: () => trevo.track('checkout_started'),
child: Text(variant == 'treatment' ? 'Start free trial' : 'Subscribe'),
);
},
)
```
Each call records an **exposure** the first time. Pass `trackExposure: false` to read without
recording one. `onChange` calls a listener whenever config or identity changes and returns a
function that stops it.
## Parameters
A [parameter](/concepts/parameters) lets later experiments change a value with no release:
```dart theme={null}
final headline = trevo.getParameter('paywall.headline', 'Subscribe');
final trialDays = trevo.getParameter('paywall.trial_days', 7);
```
The default's type decides the result's: `String`, `bool`, `int` or `double`. A value of another
type, or a number that isn't whole for an `int`, serves the default.
A `String` parameter can carry [text per language](/concepts/parameters#lists-and-translated-text):
pass your app's own translation as the default and call `trevo.setLocale(...)` with the locale your
app shows, such as `Localizations.localeOf(context).toLanguageTag()`, since only your app knows it.
Without it the SDK reads the device's language.
## Track events and identify users
```dart theme={null}
trevo.track('checkout_completed', properties: {'plan': 'pro', 'seats': 3});
trevo.identify(user.id); // after sign-in, and on launch when auth restores a user
await trevo.reset(); // on sign-out: clears the user and starts a new anonymous id
```
Events are queued on disk and sent in batches every 15 seconds, when the app moves to the
background, and on `await trevo.flush()`.
The SDK keeps its files in `trevosdk` under the app support directory, which device backups
include. A device restored from a backup then shares the anonymous id of the one it came from.
On Android you can leave the folder out of backups in your `data_extraction_rules.xml` (and
`full_backup_content` for Android 11 and older):
````xml theme={null}
``` See [Mobile experiments](/concepts/mobile-experiments)
for how experiments ramp on mobile, how the SDK survives a lost network, and the App Store and
Google Play answers.
## Options
| Option | Default | Notes |
| --- | --- | --- |
| `apiKey` | | Required. A Mobile key, `tsk_live_…` |
| `appVersion` | | Required, may be null. Sent on every event; compared with `minAppVersion` |
| `bootstrapConfig` | `[]` | Assign before storage and the network answer |
| `pollInterval` | 5 minutes | Config is also refreshed on every foreground |
| `flushInterval` | 15 seconds | Also flushes when the app moves to the background |
| `maxBatchSize` | 50 | Capped at 500 by the server |
| `configUrl`, `ingestionUrl` | Trevo | Endpoint overrides for proxied installs |
| `storage`, `transport`, `lifecycle` | Files, `dart:io`, Flutter lifecycle | Replace for tests or your own stack |
| `onError` | `debugPrint` | Background failures; the SDK never throws |
## Correctness
The package runs the shared conformance vectors in CI, so a change that would assign a user
differently from the web fails the build. The rules are in the
[bucketing spec](/reference/bucketing-spec).
````
# iOS
Source: https://docs.trevosdk.com/install/ios
Experiments and tracking for Swift and SwiftUI apps, assigning the same variants as the web.
`TrevoSDK` runs experiments and records events in iOS apps, assigning the same variant the web
SDK does for the same user. Swift, no dependencies, iOS 15 and later (also visionOS and macOS).
On tvOS it works, but tvOS only lets an app keep files in a cache it may clear, so a device can
lose its anonymous id.
In Xcode, choose **File → Add Package Dependencies** and enter
`https://github.com/trevosdk/trevosdk-ios`. In a `Package.swift`:
```swift theme={null}
.package(url: "https://github.com/trevosdk/trevosdk-ios", from: "0.1.1"),
// in your target's dependencies:
.product(name: "TrevoSDK", package: "trevosdk-ios"),
```
## Create the client
Use a **Mobile** key (`tsk_live_…`). Keep it in your build configuration, for example an
xcconfig value exposed in Info.plist, and create one client for the app's lifetime:
```swift theme={null}
import TrevoSDK
let trevo = TrevoClient(
options: TrevoOptions(
apiKey: Bundle.main.object(forInfoDictionaryKey: "TrevoApiKey") as? String ?? ""))
```
The client reads the build's version from `CFBundleShortVersionString`, so `minAppVersion`
gating and the version on every event work with no setup.
## Read a variant
`getVariant` is synchronous and safe on the main thread. It returns `control` until stored
state and the first config fetch have loaded, so wait for `ready()` before showing experiment
UI, the way you would wait for a signed-in user:
```swift theme={null}
struct CheckoutButton: View {
@State private var variant: String?
var body: some View {
Group {
if variant == "treatment" {
Button("Start free trial") { trevo.track("checkout_started") }
} else if variant != nil {
Button("Subscribe") { trevo.track("checkout_started") }
}
}
.task {
await trevo.ready()
variant = trevo.getVariant("checkout-v2")
}
}
}
```
Each call records an **exposure** the first time. Pass `trackExposure: false` to read without
recording one. `onChange` calls a listener on the main thread whenever config or identity
changes; keep the returned `TrevoSubscription` and `cancel()` it when the view goes away.
## Parameters
A [parameter](/concepts/parameters) lets later experiments change a value with no release:
```swift theme={null}
let headline = trevo.getParameter("paywall.headline", default: "Subscribe")
let trialDays = trevo.getParameter("paywall.trial_days", default: 7)
```
There are overloads for `String`, `Bool`, `Int` and `Double`. A value of another type, or a
number that isn't whole for an `Int`, serves the default.
A `String` parameter can carry [text per language](/concepts/parameters#lists-and-translated-text):
pass your app's own translation as the default, and if users can pick the app's language, call
`trevo.setLocale("pt-BR")` when they do. Without it the SDK reads the localization the app runs in.
## Track events and identify users
```swift theme={null}
trevo.track("checkout_completed", properties: ["plan": "pro", "seats": 3])
trevo.identify(user.id) // after sign-in, and on launch when auth restores a user
trevo.reset() // on sign-out: clears the user and starts a new anonymous id
```
Events are queued on disk and sent in batches every 15 seconds, when the app moves to the
background, and on `await trevo.flush()`. See [Mobile experiments](/concepts/mobile-experiments)
for how experiments ramp on mobile, how the SDK survives a lost network, and the App Store and
Google Play answers. The package ships its own privacy manifest.
## Options
| Option | Default | Notes |
| - | - | - |
| `apiKey` | | Required. A Mobile key, `tsk_live_…` |
| `appVersion` | `CFBundleShortVersionString` | Sent on every event; compared with `minAppVersion` |
| `bootstrapConfig` | `[]` | Assign before storage and the network answer |
| `pollInterval` | 300 s | Config is also refreshed on every foreground |
| `flushInterval` | 15 s | Also flushes when the app moves to the background |
| `maxBatchSize` | 50 | Capped at 500 by the server |
| `configURL`, `ingestionURL` | Trevo | Endpoint overrides for proxied installs |
| `storage`, `transport`, `lifecycle` | Files, URLSession, UIKit | Replace for tests or your own stack |
| `onError` | Unified log | Background failures; the SDK never throws |
## Correctness
The package runs the shared conformance vectors in CI, so a change that would assign a user
differently from the web fails the build. The rules are in the
[bucketing spec](/reference/bucketing-spec).
# MCP
Source: https://docs.trevosdk.com/install/mcp
Review proposals and run experiments from Claude, ChatGPT, Cursor or any MCP client.
TrevoSDK MCP is a hosted [MCP](https://modelcontextprotocol.io) server at
`https://mcp.trevosdk.com/mcp`. It lets an AI app do what the [CLI](/install/cli) does: list what
Trevo proposed, approve or dismiss, ask for a fresh batch, follow generation, and start, end and
decide experiments. Nothing runs on your machine.
## Connect
Add the server to your app. On first use it opens a Trevo sign-in, then a page where you choose:
* **What it can reach.** All your organizations and workspaces (the default), one organization, or
one workspace. All and one organization include ones you join later, and drop ones you leave,
without connecting again.
* **What it may change.** Every write is off until you turn it on, and in each organization it can
only do what your role there allows. Reading is always included.
### Claude Code
```bash theme={null}
claude mcp add --transport http trevosdk https://mcp.trevosdk.com/mcp
```
Then run `/mcp` in Claude Code and choose **Authenticate**.
### Cursor
Add it to `~/.cursor/mcp.json`, or `.cursor/mcp.json` in a project:
```json theme={null}
{
"mcpServers": {
"trevosdk": { "url": "https://mcp.trevosdk.com/mcp" }
}
}
```
### claude.ai
**Settings → Connectors → Add custom connector**, with the URL above.
### ChatGPT
Add a custom connector with the URL above and **OAuth** as the authentication. Custom connectors
need developer mode, which depends on your ChatGPT plan.
### With an API key
For a script, a CI job or a headless agent, send a workspace API key instead of signing in. Make
one under **Settings → API access**:
```bash theme={null}
claude mcp add --transport http trevosdk https://mcp.trevosdk.com/mcp \
--header "Authorization: Bearer $TREVO_API_KEY"
```
A key opens its own workspace with its own scopes, as it does for the CLI. Apps that only support
OAuth, such as ChatGPT, cannot use one.
## Switch workspaces
Tell the app which workspace you mean, for example "use Storefront in Acme". It calls
`workspaces_list` and passes that workspace's id to every other tool, so one connection covers
all of them. With one workspace in reach, it needs no id.
Each call acts in one workspace; asking about all of them at once takes one call per workspace.
Working for several clients? Connect once per client, each reaching that client's organization
only. Data from one client then never sits in an agent that can change another's.
## Tools
| Tool | What it does |
| - | - |
| `organizations_list`, `workspaces_list` | Where the connection reaches, and the writes it may make in each workspace |
| `proposals_list`, `proposals_show` | Proposals waiting for review |
| `experiments_list`, `experiments_show`, `experiments_status` | Experiments and where each one is |
| `runs_list`, `runs_show` | Proposal generation runs |
| `funnels_list` | The funnels the workspace measures |
| `generate` | Ask for a new batch of proposals |
| `proposals_approve`, `proposals_dismiss`, `proposals_revise` | Review a proposal |
| `experiments_start`, `experiments_pause`, `experiments_resume`, `experiments_end` | Control a running experiment |
| `experiments_decide` | Ship a winner or reject |
Every write is marked as one that changes things, and the server asks the app to confirm with you
first. `generate` and `proposals_approve` answer before the work is done: follow them with
`runs_show` or `experiments_status`, which wait up to 45 seconds per call.
## What it can do
The app acts as you, with the writes you allowed and your role in that workspace's organization
still holds. A write it may not make gets Trevo's refusal, with the reason. A workspace outside its
reach reads as missing. Each workspace's audit log records when an app that reaches it is connected
or disconnected, and each change under your name, marked with the app that made it, for example
"via ChatGPT".
What the app reads from Trevo goes to it and to its model provider, and is handled under that
app's terms. Connect only apps your company allows for this data.
## Disconnect
* **Account → Connected apps** lists the apps you connected, with what each one reaches.
* **Settings → API access → Connected apps** lists the apps that can reach that organization. Anyone
who can manage API keys sees and disconnects everyone's. An app connected to all of a member's
organizations is disconnected from this organization only; their other organizations keep it
until the member connects it again.
A disconnected app stops at once. Leaving an organization stops every app you connected to it; an
app connected to all your organizations keeps working in the others. If you rejoin, they work again
until you disconnect them.
# Next.js
Source: https://docs.trevosdk.com/install/nextjs
Resolve variants on the server so the first paint is correct for everyone.
Everything in [React](/install/react) works in Next.js as-is. `@trevosdk/nextjs` adds the
one thing only a server can do: resolve variants **before** the page renders, so first-time
visitors never see the control version flash.
```bash theme={null}
npm install @trevosdk/nextjs @trevosdk/react
```
`next` is an optional peer dependency (>= 14).
## 1. Request hook: Proxy or Middleware
Sets a stable `trevo_id` cookie so the server and browser bucket the same visitor
identically. Use the file and named export for your Next.js version:
| Next.js version | File | Trevo export |
| - | - | - |
| 16 and newer | `proxy.ts` (or `proxy.js`) | `proxy` |
| 14 and 15 | `middleware.ts` (or `middleware.js`) | `middleware` |
For Next.js 16 and newer:
```ts theme={null}
// proxy.ts
export { proxy } from '@trevosdk/nextjs';
export const config = {
matcher: ['/((?!api(?:/|$)|_next/static|_next/image|favicon\\.ico|sitemap\\.xml|robots\\.txt|.*\\.(?:avif|css|eot|gif|ico|jpe?g|js|json|map|mjs|mp3|mp4|otf|pdf|png|svg|ttf|txt|wav|webm|webp|woff2?|xml|zip)$).*)'],
};
```
For Next.js 14 and 15:
```ts theme={null}
// middleware.ts
export { middleware } from '@trevosdk/nextjs';
export const config = {
matcher: ['/((?!api(?:/|$)|_next/static|_next/image|favicon\\.ico|sitemap\\.xml|robots\\.txt|.*\\.(?:avif|css|eot|gif|ico|jpe?g|js|json|map|mjs|mp3|mp4|otf|pdf|png|svg|ttf|txt|wav|webm|webp|woff2?|xml|zip)$).*)'],
};
```
Create **exactly one** of these files. Never add both `proxy.*` and `middleware.*` to one
app: Next.js treats that as a conflict. Put the file beside the app's `app` or `pages`
directory. That is `/proxy.ts` when `app/` or `pages/` is at the root, or
`/src/proxy.ts` for `src/app/` or `src/pages/`; use the equivalent
`middleware.ts` path on Next.js 14/15. In a monorepo, `` means the Next.js
app directory, not the workspace root.
If `next.config.*` defines custom `pageExtensions`, the request-hook filename must use one
of those suffixes. For example, `pageExtensions: ['page.tsx', 'page.ts']` requires
`proxy.page.ts` on Next.js 16+ or `middleware.page.ts` on Next.js 14/15.
Write the matcher out as a literal, as above. Next extracts `export const config`
by static analysis and rejects imported identifiers, so importing a shared
constant fails `next dev` outright and, in a production build, silently falls back
to running the request hook on every request — static assets included.
### Compose with auth or internationalization
An app can have only one Proxy or Middleware. If auth, internationalization, or another
integration already owns it, wrap that handler instead of adding a second file:
```ts theme={null}
// proxy.ts (Next.js 16+)
import { withTrevoProxy } from '@trevosdk/nextjs';
import { existingProxy } from './lib/existing-proxy';
export const proxy = withTrevoProxy(existingProxy);
// Keep the app's existing matcher/config here as a literal.
export const config = {
matcher: ['/((?!api(?:/|$)|_next/static|_next/image|favicon\\.ico|sitemap\\.xml|robots\\.txt|.*\\.(?:avif|css|eot|gif|ico|jpe?g|js|json|map|mjs|mp3|mp4|otf|pdf|png|svg|ttf|txt|wav|webm|webp|woff2?|xml|zip)$).*)'],
};
```
On Next.js 14/15, put the same pattern in `middleware.ts` and export it as
`middleware`:
```ts theme={null}
import { withTrevoMiddleware } from '@trevosdk/nextjs';
import { existingMiddleware } from './lib/existing-middleware';
export const middleware = withTrevoMiddleware(existingMiddleware);
```
Both helpers keep the existing response body and status, redirects and rewrites, response
headers and cookies, and downstream request-header overrides. They then add Trevo's
identity and preview headers to that same result. The version-neutral `withTrevo` alias is
also available for shared setup code.
Without this, the server has no identity to bucket on for a first-time visitor.
## 2. Resolve on the server
In a server component on the page running the experiment:
```tsx theme={null}
// app//layout.tsx — use the nearest shared layout, not the root
import type { ReactNode } from 'react';
import { getTrevoBootstrap } from '@trevosdk/nextjs';
import { TrevoProvider } from '@trevosdk/react';
export default async function Layout({ children }: { children: ReactNode }) {
const apiKey = process.env.NEXT_PUBLIC_TREVO_API_KEY;
if (!apiKey) throw new Error('Missing NEXT_PUBLIC_TREVO_API_KEY');
const bootstrap = await getTrevoBootstrap({
apiKey,
experimentKeys: ['checkout-cta'],
});
return (
{children}
);
}
```
`getTrevoBootstrap()` reads the `trevo_id` cookie and the API key from the environment, then
resolves every experiment with the same deterministic hash the browser uses. The client
starts with those assignments already in hand, so the first paint is correct.
It fails soft: if the config fetch fails, it returns an empty map and the client resolves on
its own as usual.
Previews work through it too: the request hook forwards `?trevo_force=key:variant` to the render
as an `x-trevo-force` header, and `getTrevoBootstrap()` serves the forced variant instead of a
real assignment, so a page you preview doesn't flip on hydration. Without the request hook, pass
`forceVariants` yourself. Forced renders record no exposure, and the browser stamps everything
it sends during a preview so nothing from a QA tab reaches results.
It takes options: `experimentKeys` fetches only the experiments the route needs, and
`revalidate` controls how long the server-side config fetch is cached. A signed-in user's
id goes here too — see [the rule below](#the-rule-that-keeps-client-and-server-agreeing).
(The provider itself emits one `page_view` event with `path` when it initialises — don't
add your own `page_view` call or visits count twice.)
### Keeping most routes static
Reading a cookie forces a route to render dynamically. To confine that to the pages that
need it, skip the provider-wide bootstrap and pass a single experiment instead:
```tsx theme={null}
const bootstrap = await getTrevoBootstrap();
```
```tsx theme={null}
'use client';
const variant = useExperiment('checkout-cta', { initialVariant });
```
`initialVariant` takes precedence over the provider's `bootstrap`.
### Pages Router
The same primitives work from `getServerSideProps`:
```tsx theme={null}
// pages/pricing.tsx
import { resolveExperiments, TREVO_ID_COOKIE } from '@trevosdk/nextjs/server';
export async function getServerSideProps({ req }) {
const apiKey = process.env.NEXT_PUBLIC_TREVO_API_KEY;
if (!apiKey) throw new Error('Missing NEXT_PUBLIC_TREVO_API_KEY');
const bootstrap = await resolveExperiments({
apiKey,
bucketingId: req.cookies[TREVO_ID_COOKIE] ?? '',
});
return { props: { bootstrap } };
}
```
Pass `bootstrap` to `` exactly as in the App Router example.
## 3. Track conversions as normal
```tsx theme={null}
'use client';
const trevo = useTrevo();
trevo?.track('purchase_completed', { value: 49.99 });
```
For conversions that happen on your backend — payment webhooks especially — use
[`@trevosdk/node`](/install/node) instead. Those events cannot be lost to an ad blocker or a
closed tab.
## Other backends
The Next.js entry is a thin wrapper. `@trevosdk/nextjs/server` has no Next.js imports, so
the same primitives run on any Node 18+ or edge runtime:
```ts theme={null}
import { resolveExperiments, TREVO_ID_COOKIE } from '@trevosdk/nextjs/server';
const bucketingId = req.cookies[TREVO_ID_COOKIE];
const variants = bucketingId
? await resolveExperiments({ apiKey, bucketingId })
: {}; // Return control until a request hook has persisted a stable id.
```
`resolveExperiments()` never records an exposure — the client does that when the variant
actually renders. Never replace a missing cookie with an id generated only for this call:
persist it on the response first, or the same visitor can be re-bucketed on every request.
## The rule that keeps client and server agreeing
Both sides must bucket on the **same identity at the same moment**: the user id when the
visitor is identified, otherwise the `trevo_id` cookie value. Anything else assigns one
person different variants on the server and the client, which corrupts the experiment.
For anonymous visitors the request hook plus `getTrevoBootstrap()` handle this. Once a
visitor signs in, the browser buckets on their user id — pass it to the server too:
`await getTrevoBootstrap({ userId: session?.user.id })`. Omit it and SSR buckets on the
cookie while the client buckets on the user id: the variant flips on hydration. If you
hand-roll with `resolveExperiments()`, all of this is your responsibility.
# Node
Source: https://docs.trevosdk.com/install/node
Server-side assignment and tracking for Node, Bun, Deno, and edge runtimes.
`@trevosdk/node` runs experiments and records conversions from your backend. It uses
web-standard APIs only — `fetch`, `AbortSignal`, timers — so it runs on Node 18+, Bun, Deno,
and edge runtimes.
```bash theme={null}
npm install @trevosdk/node
```
## Why use it
**Conversions that cannot be blocked.** A `subscription_started` fired from a Stripe webhook
is never lost to an ad blocker, a closed tab, or a failed beacon. This improves the numbers
for your *browser* experiments too, which is the most common reason to adopt it before
running a single backend experiment.
**Experiments only a backend can run** — pricing and packaging, search ranking, prompt or
model choices, lifecycle email content. The variant is a code path, not a UI element.
**Properties the browser shouldn't be trusted with** — plan, seat count, MRR.
## Create a client
You need a **server** key: `tsk_secret_…`, from Settings → SDK keys with platform `Server`.
It is shown once. Never put it in client code — secret keys sent with an `Origin` header are
rejected.
```ts theme={null}
import { createClient } from '@trevosdk/node';
const secretKey = process.env.TREVO_SECRET_KEY;
if (!secretKey) throw new Error('Missing TREVO_SECRET_KEY');
export const trevo = createClient({ secretKey });
```
Create the client at module scope — one per process, reused across requests — then
`await trevo.ready()` inside your request or startup lifecycle. Starting network work inside
the lifecycle also works in edge runtimes that forbid it during module evaluation.
## Identity is passed per call
A server holds no ambient user state, so every call takes the identity explicitly:
```ts theme={null}
await trevo.ready();
const userId = req.user?.id;
const anonymousId = req.cookies.trevo_id;
const identity = {
...(userId ? { userId } : {}),
...(anonymousId ? { anonymousId } : {}),
};
const variant = trevo.getVariant('pricing-algo-v2', identity);
trevo.track('subscription_started', identity, { plan: 'pro' });
```
**Send both ids whenever you have them.** Trevo links an anonymous journey to a user the
first time it sees an event carrying both. A backend that only ever sends `userId` never
creates that link, and the user's pre-login activity is never attached to their conversion.
**Bucket with the identity the browser is using at that moment** — the user id when
identified, otherwise the `trevo_id` cookie. Anything else assigns the same person different
variants on the client and the server.
## Linking identities without a cookie
Webhooks and cron jobs have no cookie to read. State the link directly:
```ts theme={null}
await trevo.alias(anonymousId, userId);
```
Idempotent and safe to retry. An `anonymousId` belongs to one user — pointing it at a
different user changes nothing and **throws** `TrevoSDKError` (HTTP 409). Retrying can't
succeed — catch it rather than letting your queue replay.
## Idempotency
Payment providers replay webhooks, and a conversion counted twice inflates whichever variant
that user was in. Pass a stable `insertId` derived from the thing that happened:
```ts theme={null}
trevo.track(
'subscription_started',
{ userId },
{ plan: 'pro' },
{ insertId: subscription.id },
);
```
Trevo records that event once regardless of how many deliveries arrive.
## Serverless
Timers do not survive between invocations, so flush explicitly before returning:
```ts theme={null}
export async function handler(event) {
await trevo.ready();
trevo.track('order_placed', { userId: event.userId }, { value: 42 });
await trevo.flush(); // rejects if delivery failed, so you can react
}
```
For long-running processes, call `shutdown()` before exit — it stops timers and flushes once.
Cloudflare Workers expose secrets through the request's `env` binding rather than
`process.env`. Cache construction at module scope, but read the binding and start network work
inside `fetch`:
```ts theme={null}
import { createClient } from '@trevosdk/node';
let client: ReturnType | undefined;
export default {
async fetch(_request, env, ctx) {
if (!env.TREVO_SECRET_KEY) throw new Error('Missing TREVO_SECRET_KEY binding');
client ??= createClient({ secretKey: env.TREVO_SECRET_KEY });
await client.ready();
// Resolve and track with the userId from existing auth, or the same
// trevo_id cookie the browser uses. Never pass an empty identity.
ctx.waitUntil(client.flush());
return new Response('ok');
},
};
```
## Local development
Pin variants without touching Trevo:
```bash theme={null}
TREVO_FORCE_VARIANTS=checkout-cta:treatment,pricing-v2:control
```
Or in code:
```ts theme={null}
createClient({ secretKey, forceVariants: { 'checkout-cta': 'treatment' } });
```
Forced reads never record an exposure, and while a force is pinned every event the client
sends is marked `preview`, which every experiment read excludes — so your local testing never
pollutes results, conversions included. A force naming a variant the experiment
doesn't have is reported through `onError` rather than ignored quietly.
To render for a browser previewing with `?trevo_force=`, pass that request's force — it wins
over the process-wide one — and mark the events that request produces:
```ts theme={null}
import { parseForceVariants } from '@trevosdk/node';
const forceVariants = parseForceVariants(url.searchParams.get('trevo_force'));
const variant = trevo.getVariant('checkout-cta', identity, { forceVariants });
trevo.track('checkout_started', identity, props, {
forcedPreview: Object.keys(forceVariants).length > 0,
});
```
## Options
| Option | Default | Notes |
| - | - | - |
| `secretKey` | — | Required. `tsk_secret_…` |
| `pollIntervalMs` | `60000` | Config refresh cadence; minimum `10000` |
| `flushIntervalMs` | `5000` | Background flush cadence; minimum `500`. Serverless should `await flush()` instead |
| `maxBatchSize` | `50` | Requests capped at 500 by the server |
| `configUrl` | — | Endpoint override for proxied installs |
| `ingestionUrl` | — | Endpoint override for proxied installs |
| `aliasUrl` | — | Endpoint override for proxied installs |
| `bootstrapConfig` | — | Assign against this before the first fetch resolves, so a cold start never serves control |
| `forceVariants` | — | Pin variants locally; also read from `TREVO_FORCE_VARIANTS` |
| `fetch` | global | Override for tests or runtimes without a global fetch |
| `onError` | `console.error` | Background failures that have nowhere else to surface |
## API summary
| Method | Purpose |
| - | - |
| `ready()` | Resolves once initial config is loaded, or the first fetch failed |
| `getVariant(key, identity, options?)` | Deterministic assignment |
| `track(name, identity, properties?, options?)` | Queue a conversion |
| `alias(anonymousId, userId)` | Link an anonymous journey to a user |
| `flush()` | Send everything queued; rejects on failure |
| `shutdown()` | Stop timers and flush once |
# Python
Source: https://docs.trevosdk.com/install/python
Server-side assignment and tracking for Django, Flask, FastAPI, Celery, and scripts.
`trevosdk` runs experiments and records conversions from your Python backend. Zero
dependencies, Python 3.10+, and assignment is byte-identical to every other Trevo SDK — the
same user gets the same variant in the browser and on the backend.
```bash theme={null}
pip install trevosdk
```
## Create a client
You need a **server** key: `tsk_secret_…`, from Settings → SDK keys with platform `Server`.
It is shown once. Never put it in client code.
```python theme={null}
from trevosdk import TrevoClient
trevo = TrevoClient("tsk_secret_...")
```
Create the client once at module scope — one per process, reused across requests. Config
refresh (60-second poll) and event delivery run on background daemon threads; events flush
on interpreter exit, or deterministically via `trevo.flush()` / `trevo.close()`.
Assignment needs config, so wait for the first fetch once at startup:
```python theme={null}
trevo.ready(timeout_s=2) # True once config loaded; False on timeout
```
Without this, requests in the first moments after a deploy fall back to control.
## Read a variant
```python theme={null}
variant = trevo.get_variant("checkout-cta", user_id="user-42")
if variant == "treatment":
... # alternate experience
```
`get_variant` reads an immutable in-memory config snapshot — no network call, nothing that
blocks — so it is safe anywhere: Django and Flask views, FastAPI handlers, Celery tasks,
cron scripts.
Each call records an **exposure** (deduplicated per identity and variant within a 10-minute
window). To read without recording one, pass `track_exposure=False`.
## Identity is passed per call
A server holds no ambient user state, so every call takes the identity explicitly:
```python theme={null}
variant = trevo.get_variant(
"pricing-algo-v2",
user_id=request.user.id if request.user.is_authenticated else None,
anonymous_id=request.COOKIES.get("trevo_id"),
)
```
**Send both ids whenever you have them.** `user_id` wins for bucketing when present; an
event carrying both is what links a user's anonymous browsing to their conversions. With no
identity at all, `get_variant` returns `"control"` and records nothing.
**Bucket with the identity the browser is using at that moment** — the user id when
identified, otherwise the `trevo_id` cookie. Anything else assigns the same person different
variants on the client and the server.
## Track conversions
```python theme={null}
trevo.track("subscription_started", user_id="user-42", properties={"plan": "pro"})
```
Payment providers replay webhooks, and a conversion counted twice inflates whichever variant
that user was in. Pass a stable `insert_id` derived from the thing that happened, and Trevo
records the event once no matter how many deliveries arrive:
```python theme={null}
trevo.track(
"subscription_started",
user_id="user-42",
properties={"plan": "pro"},
insert_id=subscription.id,
)
```
## Linking identities without a cookie
Webhooks and cron jobs have no cookie to read. State the link directly:
```python theme={null}
trevo.alias(anonymous_id, user_id)
```
Idempotent and safe to retry. An `anonymous_id` belongs to one user — pointing it at a
different user raises and changes nothing.
## Framework notes
* **Django / Flask** — instantiate once at module scope (a settings or extensions file) and
call from views directly.
* **FastAPI / async** — the sync client is safe in async handlers (nothing blocks on the
read path). For an awaitable lifecycle, wrap it:
```python theme={null}
from trevosdk import AsyncTrevoClient, TrevoClient
trevo = AsyncTrevoClient(TrevoClient("tsk_secret_..."))
# in lifespan shutdown: await trevo.aclose()
```
* **Pre-fork servers (`gunicorn --preload`, uWSGI, Celery prefork)** — a client built before
the fork keeps working in the child. Its worker threads do not survive a fork, so the SDK
re-initialises them and its locks via `os.register_at_fork`; the first `get_variant` or
`track` in the child restarts delivery. No `post_fork` hook is needed.
* **Serverless and short-lived scripts** — background timers do not get a chance to fire, so
call `trevo.flush()` before returning. The client is also a context manager: `with
TrevoClient(...) as trevo:` flushes and closes on exit.
## Local development
Pin variants without touching Trevo:
```bash theme={null}
TREVO_FORCE_VARIANTS=checkout-cta:treatment,pricing-v2:control
```
Or in code with `force_variants={"checkout-cta": "treatment"}`. Forced reads never record an
exposure, so local testing never pollutes results. The SDK's own test suite deletes the
variable, so exporting it cannot turn a conformance run red.
## Errors
Everything raised or passed to `on_error` is typed, so you can branch on what happened:
`TrevoConfigError`, `TrevoDeliveryError` (carries `.status`), `TrevoSerializationError`,
`TrevoQueueFullError` and `TrevoEventRejectedError`, all under `TrevoError`.
## Options
| Option | Default | Notes |
| - | - | - |
| `secret_key` | — | Required. `tsk_secret_…` (positional) |
| `bootstrap_config` | — | A list of experiment configs to assign against before the first fetch resolves |
| `poll_interval_s` | `60` | Config refresh cadence |
| `flush_interval_s` | `5` | Background flush cadence; serverless should call `flush()` instead |
| `max_batch_size` | `50` | Capped at 500 by the server |
| `force_variants` | — | Pin variants locally; also read from `TREVO_FORCE_VARIANTS` |
| `transport` | stdlib `urllib` | Override for tests or proxies |
| `on_error` | logs at ERROR on the `trevosdk` logger | Background failures surface here |
## API summary
| Method | Purpose |
| - | - |
| `ready(timeout_s=None)` | Block until initial config loads; returns `bool` |
| `get_variant(key, *, user_id=None, anonymous_id=None, track_exposure=True)` | Deterministic assignment |
| `track(name, *, user_id=None, anonymous_id=None, properties=None, insert_id=None)` | Queue a conversion |
| `alias(anonymous_id, user_id)` | Link an anonymous journey to a user |
| `flush()` | Send everything queued now |
| `close()` | Stop background threads and flush once |
`AsyncTrevoClient` mirrors the same surface with `await`-able `ready()`, `alias()`,
`flush()`, and `aclose()`, plus `async with` support.
# React
Source: https://docs.trevosdk.com/install/react
One provider and one hook.
`@trevosdk/react` wraps the browser SDK in a provider and a hook. It depends on
[`@trevosdk/browser`](/install/browser) under the hood, so one install is all you need:
```bash theme={null}
npm install @trevosdk/react
```
`react` >= 18 is a peer dependency.
## Provider
Wrap your app once, as high as you can:
```tsx theme={null}
import { TrevoProvider } from '@trevosdk/react';
const apiKey = import.meta.env.VITE_TREVO_API_KEY;
{children}
```
The example uses Vite. Match the public configuration mechanism the app already uses:
`REACT_APP_TREVO_API_KEY` for Create React App, `GATSBY_TREVO_API_KEY` for Gatsby,
or the app's existing browser-safe runtime config for another bundler. Do not copy a
Next.js `NEXT_PUBLIC_` variable into a non-Next app.
The provider initialises the SDK synchronously on first render, keyed on `apiKey`. A key
that arrives later — from runtime config, a consent gate or env hydration — initialises the
SDK on the render it appears, and changing the key re-initialises against the new workspace.
The provider emits one `page_view` event (with `path`) when it initialises — don't add your
own `page_view` call or visits count twice.
The provider also accepts `configUrl` and `ingestionUrl` props (endpoint overrides for
proxied installs).
Passing `apiKey={undefined}` keeps the SDK from ever starting — a clean way to keep it off
outside production. It doesn't stop an SDK that already initialised this session; for
consent withdrawal call `trevo.optOut()`.
## Hook
```tsx theme={null}
import { useExperiment } from '@trevosdk/react';
function CheckoutButton() {
const variant = useExperiment('checkout-cta');
return variant === 'treatment' ? : ;
}
```
Exposure is recorded on the variant that actually renders. The hook stays subscribed to the
SDK, so a variant that could not be resolved on first paint — the first config fetch failed,
or `identify()` had not been called yet — updates as soon as it can be.
### Typed variants
Pass an `Experiment` from `defineExperiment()` (re-exported here) and the return type
narrows to a union, so an unhandled arm is a compile error:
```tsx theme={null}
import { assertNever, defineExperiment, useExperiment } from '@trevosdk/react';
const emailTiming = defineExperiment('email-capture-timing', [
'control',
'before-checkout',
'after-payment',
]);
function Checkout() {
const variant = useExperiment(emailTiming);
switch (variant) {
case 'control': return ;
case 'before-checkout': return ;
case 'after-payment': return ;
default: return assertNever(variant);
}
}
```
If the variants you declare here drift from the ones configured in Trevo, the SDK logs a
warning — which surfaces the mismatch instead of silently returning control.
Keep `'control'` in the list. A paused, ended or unknown experiment returns `'control'`; if
you did not declare it, the hook renders your first declared variant instead and logs a
warning telling you to update `defineExperiment()`, even though nothing drifted.
## What renders on the first paint
This is the part worth understanding before you ship an experiment above the fold.
* **Returning visitors** resolve from a warm local-storage cache and render the correct
variant immediately.
* **First-time visitors** have no cache. They render `control` for one paint, then swap to
their assigned variant when config arrives.
Nothing is ever hidden, and exposure fires on the variant that actually rendered — so the
data stays correct either way. But a visible swap on a first visit can look like a glitch.
Two ways to avoid it:
1. **Resolve on the server.** See [Next.js](/install/nextjs) — the first paint is already
correct for everyone, with nothing hidden. Pass the server-resolved assignments as
`bootstrap` on the provider, or per experiment as
`useExperiment(key, { initialVariant })`.
2. **Use the anti-flicker snippet.** See [Browser](/install/browser#anti-flicker). Hides the
page briefly rather than showing the wrong thing.
If neither applies, prefer experiments below the fold or behind an interaction, where a
first-paint swap is not visible.
## Accessing the client directly
```tsx theme={null}
import { useTrevo } from '@trevosdk/react';
const trevo = useTrevo(); // the SDK instance, or null before init
trevo?.track('purchase_completed', { value: 49.99 });
```
Use this for `track()` and `identify()`. For reading variants, prefer `useExperiment()` —
it handles re-rendering when config arrives.
## Identifying users
Call `identify()` as soon as you know who the user is, typically in an effect after auth
resolves:
```tsx theme={null}
const trevo = useTrevo();
useEffect(() => {
if (user) trevo?.identify(user.id);
}, [user, trevo]);
```
Because identity determines assignment, calling `identify()` after an experiment has
rendered can move the user to a different variant mid-session. Identify before rendering
anything under test.
# React Native
Source: https://docs.trevosdk.com/install/react-native
Experiments and tracking for React Native and Expo, bucketing users identically to the web.
`@trevosdk/react-native` runs experiments and records events in React Native and Expo apps,
assigning the same variants the web SDK does for the same user.
Pure TypeScript — no native module, no linking step, no config plugin.
Expo:
```bash theme={null}
npm install @trevosdk/react-native
npx expo install @react-native-async-storage/async-storage
```
Bare React Native:
```bash theme={null}
npm install @trevosdk/react-native @react-native-async-storage/async-storage
```
AsyncStorage is a **required** peer, not an optional one. Without persistence the anonymous
id is re-minted on every launch, which re-buckets every user and corrupts any running
experiment.
## Quick start
Create the client in its own module. This example uses Expo's public environment
convention; in bare React Native, use the app's existing runtime-config adapter.
```ts theme={null}
// lib/trevo.ts
import { createClient } from '@trevosdk/react-native';
const apiKey = process.env.EXPO_PUBLIC_TREVO_API_KEY;
if (!apiKey) throw new Error('Missing EXPO_PUBLIC_TREVO_API_KEY');
export const trevo = createClient({ apiKey });
```
Keep the app's existing splash/loading boundary visible while the hook returns
`null`, so AsyncStorage hydration cannot flash control to a treatment user. If
auth restores a known user, call `trevo.identify(user.id)` before mounting this
experiment UI.
```tsx theme={null}
// hooks/useCheckoutVariant.ts
import { useEffect, useState } from 'react';
import { trevo } from '../lib/trevo';
export function useCheckoutVariant(): string | null {
const [variant, setVariant] = useState(null);
useEffect(() => {
let mounted = true;
let ready = false;
const apply = () => {
if (mounted && ready) setVariant(trevo.getVariant('checkout-v2'));
};
const unsubscribe = trevo.onChange(apply);
void trevo.ready().then(() => {
ready = true;
apply();
});
return () => {
mounted = false;
unsubscribe();
};
}, []);
return variant;
}
export function trackAddToCart(): void {
trevo.track('add_to_cart', { sku: 'ABC' });
}
```
Use a **Mobile** key (`tsk_live_…`, created under API Keys). A shipped binary can be unpacked,
so a secret key in an app is a leaked key. With a Mobile key, a shipped experiment stays in
the config for a year, so old builds that still have its code keep getting the winner; a Web
key drops it after 30 days.
## Before your first mobile experiment
Mobile experiments ramp over weeks, wait for an app release, and keep running on old builds.
[Mobile experiments](/concepts/mobile-experiments) covers what that means for planning, how
the SDK survives a lost network or a killed app, and the App Store and Google Play answers.
## Gating on app version
An experiment whose variant code only exists from a given build onward should not enrol
devices that cannot render it. Set `minAppVersion` on the experiment:
```json theme={null}
{ "experimentKey": "checkout-v2", "minAppVersion": { "ios": "1.4.0", "android": "1.4.0" } }
```
Builds below the threshold get `control` and record no exposure, so they never appear in the
results. This requires you to pass `appVersion` when creating the client — without it, a
gated experiment returns control for everyone, because the SDK cannot prove the build is new
enough and guessing wrong means a broken screen.
Always pass the installed binary's real app version, never a copied sample. Expo apps can read
it from `expo-application` (`npx expo install expo-application`):
```ts theme={null}
import * as Application from 'expo-application';
const appVersion = Application.nativeApplicationVersion;
if (!appVersion) throw new Error('Missing Expo app version');
export const trevo = createClient({ apiKey, appVersion });
```
For bare React Native, pass the value from the build-metadata adapter the app
already uses; do not hard-code it. Every event also records it, so each event names the
build that sent it.
## Options
| Option | Default | Notes |
| - | - | - |
| `apiKey` | — | Required. A Mobile key, `tsk_live_…` |
| `appVersion` | — | This build's version. Required for `minAppVersion` gating; sent on every event |
| `platform` | `Platform.OS` | Override for tests |
| `bootstrapConfig` | — | Assign before storage and network answer |
| `pollIntervalMs` | `300000` | Foreground config refresh happens regardless |
| `flushIntervalMs` | `15000` | Also flushes on background |
| `maxBatchSize` | `50` | Capped at 500 by the server |
| `storage` | AsyncStorage | Override for tests |
| `appState` | RN AppState | Override for tests |
| `configUrl` | — | Endpoint override for proxied installs |
| `ingestionUrl` | — | Endpoint override for proxied installs |
| `fetch` | global | Override for tests |
| `onError` | `console.warn` | Background failures surface here |
## API summary
| Method | Purpose |
| - | - |
| `getVariant(key, { trackExposure }?)` | Deterministic and synchronous. Returns `control` until `ready()` resolves |
| `track(event, properties?, { insertId }?)` | Queue an event |
| `identify(userId)` | Associate subsequent events with a user and re-resolve assignment from that user id |
| `reset()` | Clear the user and mint a new anonymous id. Call on sign-out |
| `getAnonymousId()` | The device's stable id, once storage has been read |
| `ready()` | Resolves once stored state is loaded and the first fetch settles |
| `onChange(listener)` | Subscribe to config and identity changes; returns an unsubscribe |
| `flush()` / `shutdown()` | Send queued events now / stop timers and flush once |
## Expo
Works in Expo Go and in development builds with no config plugin — there is no native code
to link. Install AsyncStorage the Expo way:
```bash theme={null}
npx expo install @react-native-async-storage/async-storage
```
## Store compliance
The package ships `ios/PrivacyInfo.xcprivacy`. The Google Play data safety answers are in
[Mobile experiments](/concepts/mobile-experiments#store-compliance).
## Correctness
This package runs the shared conformance vectors against its public API in CI, so a change
that would bucket a user differently from the browser fails the build. The normative rules
are in the [bucketing spec](/reference/bucketing-spec).
# REST
Source: https://docs.trevosdk.com/install/rest
Record conversions over plain HTTP from any language.
For languages Trevo does not ship an SDK for — Go, Elixir, PHP, Java, Dart. Tracking is a
plain HTTP POST with no client-side logic, so there is nothing to get subtly wrong.
Python and Ruby backends should use the native SDKs instead — [Python](/install/python) and
[Ruby](/install/ruby) — which also do assignment.
## Do not implement assignment yourself
Assignment is a hash whose exact behaviour is a frozen contract shared by every Trevo SDK:
FNV-1a over **UTF-16 code units**, not UTF-8 bytes.
An implementation written against bytes agrees with ours on ASCII identifiers and diverges
on every accented name, every CJK id, every emoji. It passes your tests and silently
corrupts that customer's experiment months later. Nothing errors — the numbers just stop
meaning anything.
If you only need to record conversions, everything below is safe and sufficient: resolve
variants in the browser or a backend SDK ([Node](/install/node), [Python](/install/python),
[Ruby](/install/ruby)), and use REST purely for tracking.
If you genuinely need assignment in an unsupported language, implement the
[bucketing spec](/reference/bucketing-spec) **and** pass every case in the published
conformance vectors before sending a single exposure.
## Authentication
A server key (`tsk_secret_…`) from Settings → SDK keys, platform `Server`:
```
Authorization: Bearer tsk_secret_…
```
Publishable `tsk_live_` keys are for browsers. A secret key sent with an `Origin` header is
rejected, because that combination means it has been shipped into client code.
## Send events
```
POST https://ingest.trevosdk.com/v1/events
Content-Type: application/json
```
```json theme={null}
{
"events": [
{
"event": "subscription_started",
"userId": "user_123",
"anonymousId": "3f2504e0-4f89-11d3-9a0c-0305e82c3301",
"properties": { "plan": "pro", "value": 49.99 },
"timestamp": "2026-08-09T12:34:56.000Z"
}
]
}
```
| Field | Required | Notes |
| - | - | - |
| `event` | yes | ≤500 chars, `A–Z a–z 0–9 _ . - $` only |
| `userId` | one of the two | ≤255 chars |
| `anonymousId` | one of the two | The `trevo_id` cookie value |
| `properties` | no | JSON object, ≤8192 bytes serialised |
| `timestamp` | no | ISO 8601. Defaults to receipt time |
| `insertId` | no | Idempotency key, ≤200 chars |
| `sdkVersion` | no | Free-form, ≤50 chars — a longer value drops that event |
Up to **500 events per request** — batch rather than sending one request per event. The
body also accepts a top-level `sentAt` (ISO 8601), set when the batch leaves your client.
### Send both ids
Trevo links an anonymous journey to a user the first time it sees an event carrying both. A
backend that only ever sends `userId` never creates that link, and the user's pre-login
browsing is never attached to their conversion.
## Timestamps and wrong clocks
Events are **never dropped for their timestamp.**
`receivedAt - sentAt` gives your client's clock offset, and every event in the batch is
corrected by it. That distinguishes "this clock is wrong" from "this event is genuinely
old", which comparing against the server clock alone cannot do.
* Offsets under 2 seconds are treated as network transit and ignored
* Corrections are capped at ±24 hours
* After correction, timestamps older than 7 days or more than 1 hour in the future are
clamped to the boundary and marked, not discarded
Send `sentAt` if you buffer events. Without it, timestamps are taken at face value and only
the sanity clamp applies — fine for a server sending events as they happen, wrong for
anything that queues.
## Link identities explicitly
When the caller has no cookie to read — a webhook, a cron job — state the link directly:
```
POST https://ingest.trevosdk.com/v1/alias
Authorization: Bearer tsk_secret_…
```
```json theme={null}
{ "anonymousId": "3f2504e0-4f89-11d3-9a0c-0305e82c3301", "userId": "user_123" }
```
Returns `202` with an outcome of `linked` or `already-linked`. Sending the same pair
repeatedly is a no-op, so it is safe inside a handler your provider may replay.
An `anonymousId` belongs to one user. Pointing one at a *different* user returns `409` and
changes nothing — that request is usually a shared browser or a reused cookie, and honouring
it would credit one person's browsing to another.
## Idempotency
Set `insertId` to a stable value derived from the thing that happened — an order id, a
subscription id, `${userId}:${invoiceId}` — and Trevo records that event once no matter how
many times you send it.
This matters most where you least want a duplicate: payment providers replay webhooks, and a
`subscription_started` counted twice inflates the conversion rate of whichever variant that
user was in.
**Without `insertId`, retries are not deduplicated.** A request that timed out after the
server accepted it will be counted twice if you send it again.
One boundary: deduplication is scoped to the calendar month the event was recorded in. Two
deliveries of the same `insertId` landing in different months are both kept. Rarely
reachable in practice — but if you replay historical events in bulk, do it within a month's
window.
## Responses and retries
| Status | Meaning | Safe to retry |
| - | - | - |
| `202` | Accepted. Check `rejected` in the body: individually invalid events are dropped and still return 202 (`{"success":true,"rejected":M}`). Batches sent with a crawler User-Agent are accepted and discarded. A batch past the workspace's daily event cap is discarded too, with `"accepted":0,"reason":"daily_event_cap"`; the cap resets at midnight UTC | — |
| `400` | The request envelope failed validation (missing `events`, empty array, >500 entries, unparseable body) | No, not unchanged |
| `401` | Missing, malformed, revoked, or wrong-class key | No |
| `403` | Publishable key used from an origin the workspace doesn't allow | No |
| `409` | `/alias` only — already linked to another user | No |
| `415` | `application/octet-stream` without `?gz=1` | No, not unchanged |
| `429` | Rate limited, or `/alias` past its daily cap, which resets at midnight UTC | Yes, after backing off |
| `5xx` | Server error; the batch was not recorded | Yes, with exponential backoff |
A timeout or dropped connection is the ambiguous case: the request may or may not have
landed. Send `insertId` and retry freely.
## Minimal example
```bash theme={null}
curl -X POST https://ingest.trevosdk.com/v1/events \
-H "Authorization: Bearer $TREVO_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"events":[{"event":"subscription_started","userId":"user_123","properties":{"plan":"pro"}}]}'
```
# Ruby
Source: https://docs.trevosdk.com/install/ruby
Server-side assignment and tracking for Rails, Sidekiq, and scripts.
`trevosdk` runs experiments and records conversions from your Ruby backend. Zero
dependencies, Ruby 3.2+, and assignment is byte-identical to every other Trevo SDK — the
same user gets the same variant in the browser and on the backend.
```bash theme={null}
gem install trevosdk
```
Or in your Gemfile: `gem "trevosdk"`.
## Create a client
You need a **server** key: `tsk_secret_…`, from Settings → SDK keys with platform `Server`.
It is shown once. Never put it in client code.
```ruby theme={null}
# config/initializers/trevosdk.rb (Rails) or anywhere at boot
Trevosdk.init(ENV.fetch("TREVO_SECRET_KEY"))
```
`Trevosdk.init` sets up a process-wide singleton reachable as `Trevosdk.client` — the common
one-client-per-app setup. Config refresh (60-second poll) and event delivery run on
background threads; events flush at process exit, or deterministically via `flush` / `close`.
For multiple clients, use `Trevosdk::Client.new(secret_key, **options)` directly.
Assignment needs config, so wait for the first fetch once at boot:
```ruby theme={null}
Trevosdk.client.ready(2) # true once config loaded; false on timeout
```
Without this, requests in the first moments after a deploy fall back to control.
## Read a variant
```ruby theme={null}
variant = Trevosdk.client.get_variant("checkout-cta", user_id: current_user.id)
if variant == "treatment"
# alternate experience
end
```
`get_variant` reads an immutable in-memory config snapshot — no network call, nothing that
blocks — so it is safe anywhere: Rails controllers, Sidekiq jobs, rake tasks. The singleton
is safe across Puma threads.
Each call records an **exposure** (deduplicated per identity and variant within a 10-minute
window). To read without recording one, pass `track_exposure: false`.
## Identity is passed per call
A server holds no ambient user state, so every call takes the identity explicitly:
```ruby theme={null}
variant = Trevosdk.client.get_variant(
"pricing-algo-v2",
user_id: current_user&.id,
anonymous_id: cookies[:trevo_id]
)
```
**Send both ids whenever you have them.** `user_id:` wins for bucketing when present; an
event carrying both is what links a user's anonymous browsing to their conversions. With no
identity at all, `get_variant` returns `"control"` and records nothing.
**Bucket with the identity the browser is using at that moment** — the user id when
identified, otherwise the `trevo_id` cookie. Anything else assigns the same person different
variants on the client and the server.
## Track conversions
```ruby theme={null}
Trevosdk.client.track("subscription_started", user_id: current_user.id, properties: {plan: "pro"})
```
Payment providers replay webhooks, and a conversion counted twice inflates whichever variant
that user was in. Pass a stable `insert_id:` derived from the thing that happened, and Trevo
records the event once no matter how many deliveries arrive:
```ruby theme={null}
Trevosdk.client.track(
"subscription_started",
user_id: user.id,
properties: {plan: "pro"},
insert_id: subscription.id
)
```
## Linking identities without a cookie
Webhooks and background jobs have no cookie to read. State the link directly:
```ruby theme={null}
Trevosdk.client.alias(anonymous_id, user_id)
```
Idempotent and safe to retry. An `anonymous_id` belongs to one user — pointing it at a
different user raises and changes nothing.
## Runtime notes
* **Rails** — initialize in `config/initializers/trevosdk.rb` and call `Trevosdk.client`
from anywhere.
* **Forking servers (Puma workers, Sidekiq, Spring)** — a client built before the fork keeps
working in the child. Background threads do not survive a fork, so the SDK detects the new
pid and restarts them on the first `get_variant` or `track`; an explicit `on_worker_boot`
re-init is optional.
* **Short-lived scripts and jobs** — call `Trevosdk.client.flush` before exiting so the
batch is delivered inside the run (an `at_exit` flush also runs).
## Local development
Pin variants without touching Trevo:
```bash theme={null}
TREVO_FORCE_VARIANTS=checkout-cta:treatment,pricing-v2:control
```
Or in code with `force_variants: {"checkout-cta" => "treatment"}`. Forced reads never record
an exposure, so local testing never pollutes results. The SDK's own spec suite deletes the
variable around every example, so exporting it cannot turn a conformance run red.
Experiment keys may be Strings or Symbols — `get_variant(:"checkout-cta", ...)` and
`get_variant("checkout-cta", ...)` resolve the same experiment.
## Errors
Everything raised or passed to `on_error:` is typed, so you can branch on what happened:
`Trevosdk::ConfigError`, `Trevosdk::DeliveryError` (carries `#status`),
`Trevosdk::SerializationError`, `Trevosdk::QueueFullError` and
`Trevosdk::EventRejectedError`, all under `Trevosdk::Error` (itself a `RuntimeError`).
## Options
| Option | Default | Notes |
| - | - | - |
| `secret_key` | — | Required. `tsk_secret_…` (positional) |
| `bootstrap_config:` | — | An array of experiment configs to assign against before the first fetch resolves |
| `poll_interval_s:` | `60` | Config refresh cadence |
| `flush_interval_s:` | `5` | Background flush cadence; short-lived processes should call `flush` instead |
| `max_batch_size:` | `50` | Capped at 500 by the server |
| `force_variants:` | — | Pin variants locally; also read from `TREVO_FORCE_VARIANTS` |
| `transport:` | stdlib `Net::HTTP` | Override for tests or proxies |
| `on_error:` | log warning | Background failures surface here |
## API summary
| Method | Purpose |
| - | - |
| `ready(timeout_s = nil)` | Block until initial config loads; returns a boolean |
| `get_variant(key, user_id:, anonymous_id:, track_exposure:)` | Deterministic assignment |
| `track(name, user_id:, anonymous_id:, properties:, insert_id:)` | Queue a conversion |
| `alias(anonymous_id, user_id)` | Link an anonymous journey to a user |
| `flush` | Send everything queued now |
| `close` | Stop background threads and flush once |
# API & CLI
Source: https://docs.trevosdk.com/reference/api
Drive Trevo from a script, CI, or an agent — the same routes the dashboard uses, with a workspace API key.
Everything the dashboard does to proposals and experiments goes through `https://api.trevosdk.com/v1`.
A **workspace API key** lets a script, a CI job, or an agent do the same: list what Trevo proposed,
approve or dismiss, send revision instructions, ask for a fresh batch, start and end experiments.
## Keys
Any member of the organisation can make one under **Settings → API access**. A key:
* opens **one workspace** — no workspace header needed, and one that disagrees is refused;
* **reads everything** in it, and writes only what its scopes allow — `proposals.review`,
`experiments.manage`, `experiments.decide`, `funnels.manage`, each a permission the routes already
check for people;
* **acts as the person who made it** in the audit log and in what Trevo says it did, so it can
only carry scopes their role has. If their role later loses one, the key loses it too;
* is shown **once**, stored hashed, and revocable from the same page. Members see and revoke their
own keys; anyone who manages keys sees and revokes everyone's.
A key cannot manage keys, billing, members, or the organisation. SDK keys (`tsk_live_`,
`tsk_secret_`) are your site's, and are refused on these routes.
Every write a key makes is recorded in the audit trail as that key, beside the person it acts as —
the dashboard's trail and the CSV export both name it, and `GET /v1/audit?actorApiKeyId=…` filters
to one key.
```bash theme={null}
curl https://api.trevosdk.com/v1/experiments?status=proposed \
-H "Authorization: Bearer tsk_api_…"
```
## The CLI
```bash theme={null}
npm install -g @trevosdk/cli
trevo login # paste a key once; or set TREVO_API_KEY
```
Every command takes `--json` and prints the API response verbatim. Exit codes: `0` ok, `1` the API
refused (the reason and its code are on stderr), `2` usage, and `3` auth — so a script can tell a
revoked key from a proposal that was not approvable. `trevo connect` also exits `4` while the SDK
has not reported in yet. Installation and CI setup: [CLI](/install/cli).
Reading is always allowed; the **Scope** column is the permission a key needs for the write.
### Keys and identity
| Command | What it does | Route | Scope |
| - | - | - | - |
| `trevo login` | Stores a key in `~/.config/trevo/config.json` (mode 0600) after checking it against the API. `TREVO_API_KEY` overrides the file, so CI never writes one. | `GET /experiments/counts` | — |
| `trevo whoami` | Which workspace the key opens, the key's own name, the person it acts as, and what it may write — the first thing to run when a script hits the wrong workspace. | `GET /me`, `GET /experiments/counts` | — |
| `trevo connect` | Whether the SDK is installed (`--until loaded`) and sending events. `--wait` blocks until something newer than its first read arrives, bounded by `--timeout`. Exits `4` until then. | `GET /events/connection` | — |
### Proposals
| Command | What it does | Route | Scope |
| - | - | - | - |
| `trevo proposals list` | The proposals waiting for a decision — experiments at `status=proposed`, newest first. | `GET /experiments?status=proposed` | — |
| `trevo proposals show ` | One proposal in full: the hypothesis, the change plan file by file, and whether any of those files have since moved or gone. | `GET /experiments/{id}` | — |
| `trevo proposals approve ` | Accepts the proposal and starts the pull request. `--wait` blocks until it is open and exits non-zero the moment generation fails; `--acknowledge-overlap` confirms you want it running beside an experiment that shares a surface. | `POST /experiments/{id}/approve` | `proposals.review` |
| `trevo proposals dismiss --reason ` | Refuses a proposal, terminally. Comma-separate more than one reason. The reason is what teaches the next generation round. | `POST /experiments/{id}/dismiss` | `proposals.review` |
| `trevo proposals revise ""` | Asks for the proposal to be rewritten to your brief, in place. `--wait` blocks until the revision lands (ten minutes, then it gives up). | `POST /experiments/{id}/refine`, `GET …/refine` | `proposals.review` |
### Generation
| Command | What it does | Route | Scope |
| - | - | - | - |
| `trevo generate` | Asks for a fresh batch of proposals, grounded in your repository. Returns as soon as the run starts. `--replace` retires the pending drafts when the new batch lands, not before. `--wait` blocks until the run finishes and exits non-zero if it failed. | `POST /experiments/generate` | `proposals.review` |
| `trevo runs` | The generation runs, newest first: status, how many proposals survived filtering, and when. This is how you check on a `generate` you did not wait for. `--wait` blocks on the current one. | `GET /experiment-runs` | — |
| `trevo runs show ` | One run, including why it failed and at which step. | `GET /experiment-runs/{id}` | — |
### Experiments
| Command | What it does | Route | Scope |
| - | - | - | - |
| `trevo experiments list` | Every experiment, filterable with `--status`, `--search` and `--limit`. Statuses comma-separate. | `GET /experiments` | — |
| `trevo experiments show ` | One experiment with its results, readiness flags and pull requests. | `GET /experiments/{id}` | — |
| `trevo experiments status ` | Just the status word — what a CI job polls. `--wait --until ` blocks until it arrives, exits `1` if the experiment settles somewhere it will never leave (`pr_failed`, `rejected`), and is always bounded by `--timeout`. | `GET /experiments/{id}/status` | — |
| `trevo experiments create --file ` | Declares an experiment you wrote yourself, instead of accepting a proposal. The `Idempotency-Key` is derived from the file, so a re-run of the same CI step replays the first result rather than opening a second pull request. `--generate-pr` starts the code immediately. | `POST /experiments` | `experiments.manage` |
| `trevo experiments start\|pause\|resume\|end\|ship ` | Moves experiments through the lifecycle. Takes several ids and applies them in order; if one is refused the earlier ones have already moved, and the CLI says which. `start` refuses when the primary event cannot be verified — measurement fails closed rather than starting blind. | `POST /experiments/{id}/{action}` | `experiments.manage` |
| `trevo experiments decide --ship ` | Calls the winner and opens the cleanup pull request. `--reject` reverts instead; `--reason` records why; `--force` skips the settling wait that holds a decision while conversions from the last exposures are still arriving; with `--reason` it also ships past a broken traffic split, a guardrail drop or under 7 days of runtime, which otherwise refuse the ship. | `POST /experiments/{id}/decide` | `experiments.decide` |
### Funnels
| Command | What it does | Route | Scope |
| - | - | - | - |
| `trevo funnels list` | Every funnel with its steps in order. | `GET /funnel` | — |
| `trevo funnels pull` | Writes the definitions as a file to commit — name and ordered steps, nothing the workspace owns. Without `--file` it prints to stdout. | `GET /funnel` | — |
| `trevo funnels apply --file ` | Reconciles the workspace to that file: creates what is missing, updates what changed, no-ops on the second run. Funnels are matched **by name**, so a rename creates a new funnel. `--dry-run` prints the plan without calling a write; `--prune` is the only way it deletes. | `GET`/`POST`/`PATCH`/`DELETE /funnel` | `funnels.manage` |
## Reference
The OpenAPI description of these routes is at [`/reference/openapi.json`](/reference/openapi.json).
It is generated from the schemas the API parses, so it describes what the routes actually accept
and return.
Refusals carry a `code` worth branching on:
| Code | Meaning |
| - | - |
| `SURFACE_OVERLAP` | The proposal shares a surface with an experiment already in flight. Approve with `acknowledgeOverlap: true` to run both. |
| `SURFACE_HELD_BY_LIVE_EXPERIMENT` | The experiment it shares a surface with is running or paused. Nothing overrides that: approve once it ends. |
| `PROPOSAL_FILES_MISSING` | A file the plan edits is no longer in the repository; the message names it. Revise or regenerate. |
| `PROPOSAL_SNAPSHOT_STALE` | Code the proposal relies on changed after it was written. Generate a fresh one. |
| `GENERATION_IN_FLIGHT` | A batch is already being generated for this workspace. |
| `MISSING_PERMISSION` | The key lacks the scope this write needs. |
| `API_KEY_NOT_ALLOWED_HERE` | Keys work on experiments, proposals, funnels, readiness and events — not settings. |
# Bucketing spec
Source: https://docs.trevosdk.com/reference/bucketing-spec
The normative definition of how an identity maps to a variant. Frozen.
Status: **frozen**. Normative for every Trevo SDK.
This defines how an identity is mapped to a variant. It is the one piece of logic that must be
byte-identical on every platform: given the same `bucketingId`, `experimentKey`, and variant
list, a conforming implementation returns the same variant name as every other conforming
implementation.
You only need this page if you are implementing assignment in a language Trevo does not ship
an SDK for. If you are only recording conversions, use [REST](/install/rest) — no
assignment logic required.
## Why it is frozen
Assignment is deterministic and stateless. Nothing is stored, so a change to the arithmetic
silently re-buckets every user in flight.
If two implementations disagree, the same visitor gets one variant in the browser and another
from the backend, their exposures collide, and the statistics stop meaning anything. Nothing
errors and nothing alerts — the numbers are just quietly wrong.
## Terminology
| Term | Meaning |
| - | - |
| `bucketingId` | The identity assignment is keyed on. A stable opaque string |
| `experimentKey` | The experiment's stable key |
| `variants` | Ordered list of `{ name, trafficSplit }`. Order is significant |
| `trafficSplit` | Whole percent, `0`–`100`. The list sums to `100` |
| bucket | Integer in `[0, 10000)` derived from the identity and key |
## 1. Identity resolution
Resolved in this order, first non-empty value wins:
1. The identified user id, if the host application has called `identify()`
2. The anonymous id — a v4 UUID minted on first visit and persisted by the platform
If neither is available, do **not** assign: return the control variant and record no exposure.
Switching from an anonymous id to a user id changes the bucketing basis and may therefore
change the assigned variant. That is intended — it is the point at which a visitor becomes a
known user.
Server-side callers supply `bucketingId` explicitly and are responsible for passing the same
value the browser would use, in practice the `trevo_id` cookie.
The `bucketingId` is used **verbatim**. Do not trim, case-fold, or Unicode-normalise it.
`café` (NFC) and `café` (NFD) are different identities and bucket differently.
## 2. Hash
FNV-1a, 32-bit, over **UTF-16 code units** — not over UTF-8 bytes.
```
FNV_OFFSET_BASIS_32 = 0x811C9DC5
FNV_PRIME_32 = 0x01000193
fnv1a32(s):
hash = FNV_OFFSET_BASIS_32
for each UTF-16 code unit u in s: # 0..0xFFFF
hash = hash XOR u # 16-bit XOR, not 8-bit
hash = (hash * FNV_PRIME_32) mod 2^32
return hash as unsigned 32-bit
```
Two properties differ from textbook FNV-1a and are the most likely source of a divergent port:
* **The unit is a UTF-16 code unit, not a byte.** Textbook FNV-1a consumes one byte at a time;
this consumes one 16-bit unit, XORing all 16 bits. ASCII inputs agree with a byte-wise
implementation by coincidence — every ASCII character is one code unit whose high byte is
zero — and diverge for everything else. An implementation validated only against ASCII
identifiers will pass its own tests and corrupt data for any customer with non-ASCII ids.
* **Characters outside the BMP are two units.** `🙂` (U+1F642) is the surrogate pair
`0xD83D 0xDE42` and contributes two iterations — not one code point, and not four UTF-8
bytes.
Non-JavaScript implementations must encode to UTF-16 and iterate 16-bit units. Unpaired
surrogates are hashed as-is; the algorithm is defined over code units and is total over any
UTF-16 sequence.
Arithmetic is unsigned 32-bit with wraparound.
## 3. Bucket derivation
```
bucket = fnv1a32(bucketingId + ":" + experimentKey) mod 10000
```
The separator is a single ASCII colon (`U+003A`), and the operands are concatenated in that
order — identity first.
**Known property:** the concatenation is not injective when an operand contains a colon.
`("a:b", "c")` and `("a", "b:c")` both hash `"a:b:c"` and share a bucket. This is unreachable
in practice — bucketing ids are UUIDs, experiment keys are slugs — and is frozen as-is rather
than fixed, because adding escaping would re-bucket every existing user.
## 4. Bucket walk
Variants are walked **in list order**, accumulating traffic in basis points:
```
cumulative = 0
for variant in variants:
cumulative = cumulative + variant.trafficSplit * 100
if bucket < cumulative:
return variant.name
return last variant's name
```
* `trafficSplit` is a whole percent, scaled to basis points by `* 100`, giving a `[0, 10000)`
space that matches the bucket space exactly. All arithmetic is exact in integers; no rounding
is performed and none is permitted.
* The comparison is **strictly less than**. A variant owns `[cumulative_before,
cumulative_after)`. With a 50/50 split, bucket `4999` is the first variant and `5000` is the
second.
* **List order is part of the contract.** Reordering variants with identical splits reassigns
users.
* The trailing return is reachable only when splits sum to less than 100. Configs are
schema-validated to sum to exactly 100, so it is a guard, not a behaviour to rely on.
## 5. Degenerate configurations
| Condition | Required behaviour |
| - | - |
| `variants` is empty | Return `"control"`. Warn (the reference implementation warns on every call). Do not throw |
| Splits do not sum to 100 (±0.01 tolerance) | Assign anyway, using the walk above. Warn (the reference implementation warns on every call) |
| No resolvable identity | Return `"control"`, record no exposure |
| Experiment key absent from loaded config | Return `"control"`, record no exposure. Paused, ended, rejected and guardrail-stopped experiments leave the config, so this is how every visitor reverts. A config read from the SDK's own cache counts as loaded. Leave any cached assignment in place, so a resumed experiment restores the same arm. Exception: a key passed as a server-resolved assignment (the browser's `bootstrap`) keeps that assignment, unassigned, until the first config fetch succeeds, because the cache can predate the experiment's launch or resume |
| No config loaded yet (first fetch pending or failed) | Return the last cached assignment for that identity if one exists, otherwise `"control"`. Record no exposure. Never assign against a config the SDK has not seen. Because a cached config counts as loaded, a visitor keeps the cached arm only until any config loads. The app SDKs (React Native, iOS, Android and Flutter) do not follow this row yet: before config loads they return `"control"` for a key outside the app's bundled `bootstrapConfig`, even when they hold a sticky assignment |
Note: the reference config parser rejects any experiment with fewer than two variants — and
one invalid experiment invalidates the whole config response — so the empty- and
single-variant rows describe the assignment function's contract in isolation, not states
reachable through the config endpoint.
An SDK must **never throw** out of variant resolution. Failing to assign degrades to control,
because a thrown error in a host application's render path is a worse outcome than an
unbucketed user.
## 6. Override precedence
Overrides are a QA affordance. Resolution order, highest first:
1. **Explicit override** — `?trevo_force=:` in the browser, or a programmatic /
environment `forceVariants` map in a server SDK. An override applies **only if the named
variant exists in that experiment's loaded config**; an unknown variant name is ignored and
resolution continues. This is what stops a crafted URL from making `getVariant()` return an
arbitrary string. Ignoring is never silent: the SDK warns through its error channel
(`force_ignored` in the browser, `onError` on a server), naming the force and the variants
the experiment has.
2. **Deterministic assignment** — sections 2 to 4.
A forced variant **must not** record an exposure and **must not** be written to the assignment
cache. Preview traffic that reaches the results pipeline is indistinguishable from real traffic
and biases the experiment it was previewing.
While any override is active, every event the SDK sends is marked `preview: true`. Ingestion
records no exposure for a preview event and every conversion read drops one, so a tester's
conversions never move an arm — not even the control arm an earlier, unforced visit put them
in.
A server SDK accepts a per-request override (the map `?trevo_force=key:variant` parses to)
with precedence over a process-wide one, so a render for a browser that is previewing serves
the variant being previewed. `@trevosdk/nextjs` does this for you: the Next.js request hook
(`proxy` on Next 16+, `middleware` on Next 14/15) forwards `?trevo_force=` to the render and
`getTrevoBootstrap()` honours it.
In the browser, `?trevo_force=` persists for the tab session, and `?trevo_force=clear` drops
it. Overrides are per experiment key; comma-separate to force several.
## 7. Conformance
The conformance vectors live at `packages/contracts/src/corpus/vectors.json` in the Trevo
monorepo — ask us for a copy if you're implementing outside it:
* **`hash`** — `{ name, input, hash }` entries exercising the hash directly, including ASCII,
accented Latin in both NFC and NFD, Cyrillic, CJK, emoji, and astral-plane input.
* **`assignment`** — `{ name, experimentKey, bucketingId, variants, hash, bucket, expected }`.
The `hash` and `bucket` fields are diagnostics: they tell a failing implementation whether
it diverged in the hash or in the walk.
The same file also carries `configParse`, `buildEvent` and `exposureDedup` categories, plus
a semver `specVersion`.
Every Trevo SDK runs these vectors in its own test suite, and CI runs every SDK's suite. **A
new language binding is not conformant until it does.** If you are writing one, pass every
vector before sending a single exposure.
# Flicker on first paint
Source: https://docs.trevosdk.com/troubleshooting/flicker-on-first-paint
Why a first-time visitor briefly sees the control version, and the three ways to stop it.
A first-time visitor loads your page, sees the current version for a moment, and then it
switches to the variant. Returning visitors don't see it.
That's expected behaviour, not a bug — and it has three fixes depending on your stack.
## Why it happens
`getVariant()` is synchronous and needs experiment config to answer correctly. Where that
config comes from differs by visitor:
* **Returning visitor** — config is in local storage from a previous visit, read
synchronously before first paint. Correct immediately, no flicker.
* **First-time visitor** — no cache. The SDK returns `control` while the first config fetch
is in flight, then re-renders with the real assignment when it lands.
Nothing is hidden — and nothing is miscounted, because a pre-config `control` read records
no exposure at all. `@trevosdk/react`'s `useExperiment` re-reads once config lands and
reports the exposure on the settled variant. If you call `trevo.getVariant()` directly in
run-once code, re-read after `await trevo.ready()` (or subscribe with `trevo.onChange()`)
or the visitor is never counted.
The SDK tells you when that happens: it warns in the console and reports a
`read_before_ready` error for the experiment, and the experiment's page in the dashboard
shows **Some visitors aren't being counted** with how many were missed in the last 7 days:
visitors whose page read early and never recorded an exposure. The warning clears once a day
passes without a new one, so when it is gone your fix is working. Those visitors are mostly
first-time ones, so until the read waits for readiness the results lean toward returning visitors.
Config is cached for 24 hours, so this affects genuinely new visitors and people who cleared
storage — not your regular traffic.
## Fix 1 — Resolve on the server (best)
If you're on Next.js, the server can resolve variants before any HTML is sent, so the first
paint is already correct for everyone. Nothing is hidden and there's no timeout to tune.
```ts theme={null}
// proxy.ts — Next.js 16+
export { proxy } from '@trevosdk/nextjs';
export const config = {
matcher: ['/((?!api(?:/|$)|_next/static|_next/image|favicon\\.ico|sitemap\\.xml|robots\\.txt|.*\\.(?:avif|css|eot|gif|ico|jpe?g|js|json|map|mjs|mp3|mp4|otf|pdf|png|svg|ttf|txt|wav|webm|webp|woff2?|xml|zip)$).*)'],
};
```
On Next.js 14 or 15, use `middleware.ts` and export `middleware` instead. Put the one
request-hook file beside the app's `app`/`pages` directory (at the app root or under `src`),
and preserve custom `pageExtensions`. The matcher must be an inline literal — Next extracts
it by static analysis.
```tsx theme={null}
const bootstrap = await getTrevoBootstrap();
{children}
```
Full setup in [Next.js](/install/nextjs). Other server frameworks can do the same via
`resolveExperiments()` from `@trevosdk/nextjs/server`.
## Fix 2 — Anti-flicker snippet
If you can't resolve server-side, hide the page until variants are ready. Inline this in
``, before anything renders:
```tsx theme={null}
import { ANTI_FLICKER_SNIPPET } from '@trevosdk/browser';
// it's a string — inject it as the script's contents, in the document head:
```
In plain HTML, paste its contents into a `
```
Set it in a script that runs **before** the snippet — it's read once, at snippet
execution — and values above 10 s are clamped to 10 s.
You're choosing between a brief flash and a brief blank page. Neither is free — the blank page
is usually less jarring, but it's worse if it goes wrong.
For full control, initialise with `manualReveal: true` and call `trevo.reveal()` yourself once
you've committed the variant.
## Fix 3 — Design around it
Often the cheapest answer. A first-paint swap is only visible if the tested element is visible
on first paint.
* Test things **below the fold**, or behind an interaction — a modal, a second step, a menu
* Gate rendering on readiness where the surface can wait:
```ts theme={null}
if (!trevo.isReady()) return ;
```
* Or `await trevo.ready()` before rendering the section under test
If your experiment is on a hero CTA for a landing page whose whole audience is first-time
visitors, that's exactly the case for fix 1 or 2.
## Which to choose
| Situation | Use |
| - | - |
| Next.js | Server bootstrap |
| Other SSR framework | `resolveExperiments()` from `/server` |
| Client-only app, element above the fold | Anti-flicker snippet |
| Element below the fold or behind interaction | Nothing — it isn't visible |
| Mostly returning visitors | Nothing — they read from cache |
# No events arriving
Source: https://docs.trevosdk.com/troubleshooting/no-events-arriving
Work out where the chain broke — the script, the key, the init call, or the track call.
**Data → Events** is empty, or **Settings → Setup Trevo** still says "Waiting for the first
event." Work down this list in order; each step rules out everything above it.
## 0. Check the status chip in the topbar
It tells you where to start:
* `not connected` — the SDK never ran; start at step 1
* `SDK connected, no events` — key and network are fine; skip to the events step
* `receiving events`
* `SDK errors detected`
* `no recent events`
* `events rejected — old SDK key` — a deploy still ships a rotated key: update the env var
and redeploy
From a terminal, or for a coding agent, the [CLI](/install/cli#check-an-sdk-install) asks the
same question:
```bash theme={null}
trevo connect --until loaded --wait # passes once the SDK fetches its config
trevo connect --wait # passes once an event arrives
```
Run it, then load the app. It exits `0` when the SDK reports in, and `4` with a hint about what
to check if it doesn't. Config loaded but no event means skip to step 4.
## 1. Did the SDK load at all?
Open your browser console on a page where Trevo should be running:
```js theme={null}
typeof window.Trevo
```
* `"object"` — loaded. Go to step 2.
* `"undefined"` — the script never ran.
If you installed via a `