---
title: "Run an experiment"
description: "Split signed-in people between two versions of a page or an offer with a variant flag, record who saw which, count each variant's conversions and guardrails in the admin console, and run price tests only as disclosed discounts."
canonical_url: "https://nuxt-backend.dev/docs/build/growth/measure/experiments"
---
# Run an experiment

> Split signed-in people between two versions of a page or an offer with a variant flag, record who saw which, count each variant's conversions and guardrails in the admin console, and run price tests only as disclosed discounts.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [API reference](https://nuxt-backend.dev/docs/reference/api/flags)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/flags.ts)

Find out which of two versions works better, with numbers your deployment already holds. You declare an experiment as a flag with variants. Each person lands in one variant and stays there. The first time a page or a function reads the variant, the package records an exposure. The **Experiments** view of the admin console's Analytics tab then compares each variant on one goal, and watches guardrails that must not get worse.

**What powers it natively:** the flag bucket the package already uses for rollouts (`flagBucket`), and the event path every feature records on ([Roll out features and pause services](https://nuxt-backend.dev/docs/ship/operate/flags)). Convex's aggregate component keeps the counts. No third-party testing service is involved (checked on 2026-10-25).

**What the package adds:** variants on `defineFlags`, `useExperiment(key)` and `flags.variant(ctx, key)`, the exposure event, results per variant with guardrails, and the rules for price tests.

## Define an experiment

Add `variants` to a flag in `backend/flags.ts`. The first variant is the control, the version people see today:

```ts [backend/flags.ts]
import { defineFlags, setupFlags } from 'nuxt-backend/flags'
import { components } from './_generated/api'
import { audit } from './audit'
import { billing } from './billing'

export const flags = setupFlags(components, {
  flags: defineFlags({
    pricingHeadline: {
      default: false,
      description: 'Pricing page headline: the plan list, or a finished strip.',
      variants: ['plans', 'strip'],
      goal: 'billing.subscription_created',
      guardrails: ['billing.order_refunded', 'billing.subscription_canceled'],
    },
  }),
  audit,
  billing,
})

export const { getFlags, listFlags, setFlag, exposeExperiment, getExperiments } = flags.api
```

`exposeExperiment` records the exposures `useExperiment` reports, and `getExperiments` is the Experiments view's read; the scaffold re-exports both.

- **variants** lists two to four names. Everyone is split evenly by default. Pass `weights: [90, 10]` to send fewer people to the new version.
- **goal** is the event kind that counts as a conversion: a [billing kind](https://nuxt-backend.dev/docs/build/billing/events#on-the-activity-trail), or one of your own `app.*` events, such as `app.strip_published`.
- **guardrails** are event kinds that must not rise. A refund or a cancellation that climbs in one variant flags it, whatever its goal says.
- **by** works as on any flag: `'user'` by default, or `'workspace'` so a whole team sees one version.

The experiment starts when an administrator turns the flag on in the admin console, and stops when they turn it off or pick a winner.

## Show it in a page

`useExperiment(key)` returns the variant for whoever is looking. It is read on the server, so the first HTML already shows the right version:

```vue [app/pages/pricing.vue]
<script setup lang="ts">
const { variant } = useExperiment('pricingHeadline')
</script>

<template>
  <StripShowcase v-if="variant === 'strip'" />
  <h1 v-else>Plans for every comic</h1>
  <PricingTable />
</template>
```

`variant` is the control while the experiment is off, for a signed-out visitor and during an administrator's visit, and the winner once one is picked. It is `undefined` only while the first read is on its way in the browser, which a page rendered on the server never shows.

## Read the variant on the server

`flags.variant(ctx, key)` reads the same assignment in a mutation or action of yours, and records the exposure the same way. Use it when the variant changes what the server does, such as the subject of an email:

```ts [backend/strips.ts]
import { email } from './email'
import { flags } from './flags'
import { authed } from './functions'

export const sendPricingReminder = authed.mutation({
  args: {},
  handler: async (ctx) => {
    const variant = await flags.variant(ctx, 'pricingHeadline')
    const subject = variant === 'strip'
      ? 'See what a finished strip looks like'
      : 'Plans for every comic'
    await email.send(ctx, {
      to: ctx.user.email,
      subject,
      text: 'Pick a plan from your studio.',
    })
  },
})
```

The two reads never disagree: `useExperiment` on the client and `flags.variant` on the server hash the same key and id.

## How assignment and exposure work

- **Stable.** The variant comes from a hash of the flag's key and the account's id (or the workspace's), so a person sees the same version on every device and every visit.
- **Independent.** Two experiments hash differently, so being in one variant of one test says nothing about another.
- **Counted on first read.** The first `useExperiment` or `flags.variant` call for a person records `experiment.exposed` with the key and the variant (`useExperiment` sends it through `exposeExperiment` once the read shows the experiment runs for them). Only exposed people count, so someone who never reached the pricing page does not dilute its result. A goal or a guardrail counts only after the exposure, once per person and kind. The person's own activity on `/security` leaves the exposure out, so nobody reads which version they were given; the workspace's activity and the admin console's trail show it.
- **Signed in only.** A visitor who is not signed in has no id, and the package stores nothing on their device. Test the steps after sign-in, or the sign-in page itself as a whole.

## Read the results

The Experiments view of the admin console's Analytics tab lists each experiment with, per variant:

- the people exposed, and how many reached the goal, with the conversion rate and its 95% confidence interval;
- each guardrail's rate, marked when it is worse than the control's;
- how long it has run, in days and in full weeks, from its first exposure;
- the promotion a price test's variant shows.

Below the table it says what the results say: too few people yet (under 100 exposures in a variant), no clear difference, or which variant leads because its interval is clear of the control's. Its buttons show one variant to everyone (the flag's `winner`, set like any flag change, with a recent sign-in) and run the experiment again.

Decide before you start, then let it run:

1. **Write the hypothesis.** "A finished strip at the top of the pricing page raises paid sign-ups, because people see what they get."
2. **Pick one goal.** Several goals invite you to choose the one that won.
3. **Run whole weeks.** Weekday and weekend visitors behave differently. Run at least two full weeks.
4. **Don't stop at the first lead.** Early leads come and go. Stop when the confidence intervals no longer overlap, or at the end date you set.
5. **Ship or drop.** Pick the winner in the console. Then delete the variants from code, so the flag is plain again.

## Test a price

A price test must never charge two people different prices for the same plan without telling them. The package runs price tests as discount cohorts: the control pays the list price, and a variant gets a public discount on it, shown as a discount.

```ts [backend/flags.ts]
annualOffer: {
  default: false,
  description: 'Yearly plan at 20% off for half of new visitors.',
  variants: ['list', 'discount20'],
  discounts: { discount20: 'annual20' },
  goal: 'billing.subscription_created',
},
```

`discounts` maps a variant to a public promotion of the catalog, one with a `code` ([Run a promotion](https://nuxt-backend.dev/docs/build/growth/offers)). `<PricingTable>` shows it to the people in that variant like any promotion, the regular price struck through, the discount and its end date, and its checkout applies it. A campaign link's own code wins over it. Everyone sees what they would pay before they pay it, and since the code is public, nobody is held to a price others can't get.

The EU's Consumer Rights Directive requires telling the customer when a price was personalised by automated decision-making (Art. 6(1)(ea), added by Directive (EU) 2019/2161). A disclosed discount shown to everyone in a cohort keeps you clear of a hidden personalised price. This is not legal advice: check the rules where you sell.

## What happens when…

<table>
<thead>
  <tr>
    <th>
      Situation
    </th>
    
    <th>
      Result
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      A flag declares one variant, an unknown <code>
        goal
      </code>
      
       kind, or <code>
        weights
      </code>
      
       that don't match <code>
        variants
      </code>
    </td>
    
    <td>
      <code>
        defineFlags
      </code>
      
       throws when the deployment loads, naming the flag
    </td>
  </tr>
  
  <tr>
    <td>
      A variant names a discount that is no public promotion of the catalog
    </td>
    
    <td>
      Its people see the regular price, as for any name that is no promotion
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        useExperiment
      </code>
      
       reads a key that has no variants
    </td>
    
    <td>
      The control, <code>
        undefined
      </code>
      
      , with a warning in development
    </td>
  </tr>
  
  <tr>
    <td>
      The flag is turned off mid-test
    </td>
    
    <td>
      Everyone sees the control. Exposures and results stay for the console.
    </td>
  </tr>
  
  <tr>
    <td>
      An administrator visits an account
    </td>
    
    <td>
      They see the account's variant, and no exposure is recorded. An event recorded during the visit counts toward no goal or guardrail
    </td>
  </tr>
  
  <tr>
    <td>
      An administrator acts on someone else's account
    </td>
    
    <td>
      The event counts toward no goal or guardrail, and no active week of the account's cohort
    </td>
  </tr>
  
  <tr>
    <td>
      A winner is picked
    </td>
    
    <td>
      Everyone sees it, nobody is exposed any more, and the results stay
    </td>
  </tr>
  
  <tr>
    <td>
      An account is erased
    </td>
    
    <td>
      Its exposure loses who it was and stays counted, as the funnel's counts do
    </td>
  </tr>
</tbody>
</table>

## Limits

- **Signed-in people only.** There is no anonymous assignment, by design: it would need an identifier on the visitor's device.
- **Two to four variants.** More splits traffic too thin for a small app to reach a result.
- **Small samples decide nothing.** With a few hundred exposures, only a large difference shows. The console says so instead of naming a winner.
- **One goal per experiment.** Read the others in the [funnel](https://nuxt-backend.dev/docs/build/growth/measure).

## Test it

Assignment is deterministic, so a test pins a person to a variant by their id:

```ts [backend/experiments.test.ts]
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('a person keeps their variant across reads', async () => {
  const ada = await asUser(testApp())
  const first = await ada.query(api.flags.getFlags, {})
  const second = await ada.query(api.flags.getFlags, {})
  expect(first.variants.pricingHeadline).toBe(second.variants.pricingHeadline)
})
```

## Related

- [Measure growth](https://nuxt-backend.dev/docs/build/growth/measure): the funnel the goal events come from.
- [Roll out features and pause services](https://nuxt-backend.dev/docs/ship/operate/flags): the flags experiments are built on.
- [Run a promotion](https://nuxt-backend.dev/docs/build/growth/offers): the discounts a price test uses.
- [Customize the pricing page](https://nuxt-backend.dev/docs/build/billing/pricing-page): the page most tests change.
- [Polar](https://nuxt-backend.dev/docs/services/polar): the checkout that shows each cohort's price.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
