---
title: "Define and sync your catalog"
description: "Declare meters, a free plan, plans with monthly and yearly prices in one currency or several, packs, features, quotas and promotions in billing.catalog.ts, push them with `nuxt-backend billing sync`, retire a plan without breaking its subscribers, and keep provider ids out of your code."
canonical_url: "https://nuxt-backend.dev/docs/build/billing/catalog"
---
# Define and sync your catalog

> Declare meters, a free plan, plans with monthly and yearly prices in one currency or several, packs, features, quotas and promotions in billing.catalog.ts, push them with `nuxt-backend billing sync`, retire a plan without breaking its subscribers, and keep provider ids out of your code.

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.

- [Try it live in the playground](https://nuxt-backend.dev/playground/pricing)
- [API reference](https://nuxt-backend.dev/docs/reference/api/billing)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/catalog.ts)

Your billing catalog is one TypeScript file, and Polar's products are made from it. `defineBillingCatalog` in `backend/billing.catalog.ts` declares the meters, plans, packs, features, quotas and promotions. `npx nuxt-backend billing sync` pushes them to Polar and writes the ids it gets back to `backend/billing.generated.ts`, the only place provider ids live. Your code names everything by its catalog key.

- **Polar does natively:** products, prices in many currencies, meters, benefits and discounts. It grants benefits every billing cycle, and never rewrites a price a subscriber holds (checked on 2026-10-25).
- **The package adds:** one typed file for all of it, find-or-create sync that never deletes, drift reports, the free plan, quotas on benefits, a private gift twin per pack, and the webhook endpoint with its secret.

Granting stays with Polar. "The Creator plan includes 500 credits a month" becomes a meter-credit benefit on the plan's product, which Polar grants every billing cycle, and once at purchase for a pack. The package pushes the catalog and reads the balances.

Which of plans, credits, usage prices and packs fits your product is on [Choose a pricing model](https://nuxt-backend.dev/docs/build/billing/pricing-models). How the catalog reaches your pricing page is on [Customize the pricing page](https://nuxt-backend.dev/docs/build/billing/pricing-page).

## Declare

A catalog for an app where people write stories and spend credits on generations:

```ts [backend/billing.catalog.ts]
import { defineBillingCatalog } from 'nuxt-backend/billing'

export default defineBillingCatalog({
  currency: 'usd',
  meters: {
    credits: {},                                   // sums `amount`: a spend can cost several credits
  },
  plans: {
    free: {
      name: 'Free',
      prices: { month: 0 },                        // the free plan: every new workspace starts on it
      credits: { meter: 'credits', units: 20 },
    },
    creator: {
      name: 'Creator',
      description: 'For people who publish every week.',
      prices: { month: 1200, year: 12000 },        // cents; one product per interval
      credits: { meter: 'credits', units: 500 },   // a month's allowance; the yearly price grants 6,000
      features: ['hd_export'],
      trial: { interval: 'day', count: 14 },
    },
  },
  packs: {
    credits500: {
      name: '500 credits',
      price: { usd: 2000, eur: 1800 },             // one price per currency, on one product
      credits: { meter: 'credits', units: 500 },   // granted once; pack credits roll over
    },
  },
  features: {
    hd_export: { description: 'Exports in full resolution' },
  },
})
```

The fields, in the order the catalog takes them:

<field-group>
<field name="currency" type="string">

ISO 4217, lowercase (`'usd'`, `'eur'`). The currency a single-currency `price` and every usage price is created in, and the one a visitor pays in when the catalog does not price theirs. Defaults to the Polar organization's default presentment currency, which the sync reads and reports (`exists currency usd — organization default`). A per-currency price must name it. See [Currencies](#currencies).

</field>

<field name="meters[key]" type="CatalogMeter">

A usage meter, named by the key your spends use (`spendCredits({ meter: 'credits' })`). `aggregation` is `'sum'` (the default), which sums `property` (default `'amount'`) across events so one event can spend several credits; or `'count'`, which counts events, one credit each, and can't be refunded. `eventName` defaults to the key. `unit?` names what it counts, for the packaged labels: see [Name the unit a meter counts](#name-the-unit-a-meter-counts).

</field>

<field name="plans[key]" type="CatalogPlan">

A subscription plan:

- `name`, `description?`.
- `prices`: `{ month?, year? }` in cents, at least one. Each is a product of its own at the provider, so a subscriber switches between monthly and yearly as between plans. Per currency: `{ usd: { month, year }, eur: { month, year } }` ([Currencies](#currencies)). `{ month: 0 }` makes it [the free plan](#the-free-plan).
- `credits?`: a `CatalogPlanCreditGrant` (`meter`, `units`, `rollover?`, `once?`), granted every cycle. `units` as a number is the monthly allowance, and the yearly price grants twelve times it once a year; `units: { month, year }` sets each cycle's grant. `rollover` defaults to `false` for plans. On the free plan, `once: true` makes them [welcome credits](#welcome-credits) instead: granted once per person.
- `features?`: keys from `features`.
- `quotas?`: experimental. How many of each quota from `quotas` the plan allows, a whole number or `'unlimited'`. A quota the plan leaves out allows none ([Limit resources per plan](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas)).
- `trial?`: a `CatalogTrial`, `interval` of `'day' | 'week' | 'month' | 'year'` and `count?` (default 1), the free trial before the first charge, on every interval. `npx nuxt-backend doctor` warns when a plan declares one but the Polar organization has not turned on trial-abuse prevention.
- `usage?`: `CatalogUsagePrice[]`, each `meter`, `unitAmount` in cents (a string for sub-cent precision) and `cap?`, the most cents one cycle may bill. A metered price on top of the plan's fixed price, so a plan can include an allowance and then charge for what goes past it.
- `retired?`: see [Retire a plan](#retire-a-plan).
- `taxBehavior?`: `'inclusive' | 'exclusive' | 'location'`, default the organization's setting.
- `customFields?`: keys from `customFields`.

Three plan fields shape how a plan runs:

- `meterCycle?`: `'month'`. The plan's meters reset, and its credits are granted, every month on every price: Polar's meter cycle ([Grant credits every month on a yearly plan](https://nuxt-backend.dev/docs/build/billing/credits#grant-credits-every-month-on-a-yearly-plan)). `billing sync` sets it on the yearly product as it creates it; Polar never changes a product's meter cycle, so a yearly product made without it is reported as drift.
- `gift?`: `{ months }`, any of 1, 3 and 12. The plan can be bought once as a [plan pass](https://nuxt-backend.dev/docs/build/growth/offers/plan-passes) for those lengths. It needs a free plan to return to.
- `trial?`: `{ interval?, count?, pass: true }`. A [reverse trial](https://nuxt-backend.dev/docs/build/growth/offers/plan-passes#run-a-reverse-trial): a new workspace starts on the plan as a pass for `count` `interval`s (14 days when both are left out, at most 92), with no card, and falls back to the free plan when it ends. The plan's products then carry no trial of their own. One plan of the catalog runs one, and it needs a free plan.

</field>

<field name="packs[key]" type="CatalogPack">

A one-time credit pack: `name`, `description?`, `price` (cents, or per currency: `{ usd: 2000, eur: 1800 }`), `credits` (granted once at purchase), `taxBehavior?` and `customFields?`. `rollover` defaults to `true` for packs. Turned off, unspent credits lapse at the customer's next billing cycle, and the sync warns.

</field>

<field name="features[key]" type="CatalogFeature">

`description`. Created as a custom benefit tagged with the key, so `useFeatures().has(key)` matches it by metadata and no provider id appears in the app.

</field>

<field name="quotas[key]" type="CatalogQuota">

Experimental. `description`: what the quota counts, as a sentence names it (`'stories'`). `<Gate quota>` says it, `getFeatures` reports it and DevTools shows it. The key is what `billing.requireQuota`, `useFeatures().quota()` and `<Gate quota>` name it by: a letter, then letters, digits, `_` or `-`, at most 34 in all. A quota counts what is held, never an allowance per period, and never people: a quota on members, seats, users, teammates, collaborators, guests or people is refused, whatever words about the count follow (`seat_limit`), since a plan here is never priced per seat.

</field>

<field name="discounts[key]" type="CatalogDiscount">

A promotion: Polar's own discount, applied by its key. `name`, `percentOff` (up to two decimals) or `amountOff` (cents, one per currency the products are priced in), `duration` (`'once' | 'forever' | { months }`), `products` (`{ plans?, interval?, packs? }`, never every product), `code?` (3 to 64 letters and digits: a public promotion; without one only your server applies it), `maxRedemptions?`, `perCustomer?`, `startsAt?`, `endsAt?` and `retired?`. See [Run a promotion](https://nuxt-backend.dev/docs/build/growth/offers).

</field>

<field name="customFields[key]" type="CatalogCustomField">

A field the checkout collects and stores on the order or subscription, where the provider's dashboard and webhook payloads show the answer. `type` (`'text' | 'number' | 'checkbox' | 'date' | 'select'`), `name?` (the checkout label, default the key), `slug?` (the key the answer is stored under, default the key), `required?` (default `false`) and `options?` (`{ value, label }[]`, for `'select'`). Plans and packs opt in by key through their `customFields`.

</field>
</field-group>

## Name the unit a meter counts

The packaged components say "credits": "120 credits left.", "500 credits / month", "€0.04 per credit". When your meter counts something else, name its unit once and every packaged label says it:

```ts [backend/billing.catalog.ts]
meters: {
  pages: { unit: { one: 'page', other: 'pages' } },
},
```

`unit` holds the word for each plural category of your language, as `Intl.PluralRules` names them: `one` and `other` at least, and `few` or `many` where your language has them (`{ one: 'страница', few: 'страницы', many: 'страниц', other: 'страницы' }` in Russian). A category it leaves out reads as `other`, and a heading, such as the credits section of `/settings`, reads `other` with a capital. `npx nuxt-backend billing sync` writes it to `billing.generated.ts`; nothing changes at Polar. Then `useCredits().unit`, the prices `getPricing` reads and the events `useUsage()` reads carry it, and the labels of the `credits`, `usage`, `settings` and `pricing` groups fill `{unit}` with the form their count takes: "1 page left.", "120 pages left.", "€0.04 per page".

Without a `unit`, `{unit}` reads as the `credits.unit` labels, "credits" in every language the package speaks. One unit serves every locale. For an app in several languages, translate the labels that name it instead ([Change copy and labels](https://nuxt-backend.dev/docs/build/ui/customize/labels)).

## Sync

```bash
npx nuxt-backend billing sync
```

```text
[nuxt-backend] billing sync → sandbox
  created      meter    credits (meter_…)
  created      benefit  hd_export (benefit_…)
  created      benefit  creator-credits (benefit_…)
  created      product  creator (prod_…)
  created      benefit  creator-credits-year (benefit_…)
  created      product  creator:year (prod_…)
  created      benefit  credits500-credits (benefit_…)
  created      product  credits500 (prod_…)
  created      product  credits500-gift (prod_…)
  created      webhook  https://<slug>.convex.site/billing/events (wh_…)
[nuxt-backend] Wrote backend/billing.generated.ts
[nuxt-backend] Webhook endpoint created; its secret is stored on the dev deployment as BILLING_WEBHOOK_SECRET.
[nuxt-backend] Refreshed the deployment's products (billing:syncProducts).
```

In development the sync targets your Polar sandbox organization, with the sandbox token in `.env.local` ([Develop with real sandboxes](https://nuxt-backend.dev/docs/develop/sandboxes#billing-on-polars-sandbox)). What the command guarantees:

- **Find-or-create, idempotent.** Every managed object carries `metadata: { managedBy: 'nuxt-backend', key }`, and a plan's products their `interval` too. The next run finds each object by that tag (`exists` in the log). A plan product made before plans had intervals is found by its key and its billing interval.
- **Nothing remote is deleted, and no price or grant a customer holds is rewritten.** Prices on subscribed products are a dashboard task. Beyond creating what is missing, the sync changes existing objects only where no customer can lose by it, each listed below: benefits, trials, currencies, quotas, retired plans, gift twins, promotions and the webhook endpoint.
- **One product per price.** A plan's `prices.month` is the product `<plan>`, and its `prices.year` the product `<plan>:year`. Each carries its own credit benefit (`<plan>-credits`, `<plan>-credits-year`) and the plan's features. A plan billed yearly before plans had intervals keeps its product, now `<plan>:year` in the map, and the `<plan>-credits` benefit it carries, checked against the year's grant (write `units: { year: <units> }` to keep it); a monthly price beside it grants `<plan>-credits-month`. A product whose interval the catalog no longer prices keeps selling and shows as `drift`: retire the plan, or archive it in the dashboard.
- **The trial follows the catalog.** A plan product whose trial differs from `trial` (another length, none, or one the catalog dropped) gets the catalog's (`updated` in the log, `would-update` on a dry run). A trial only decides what a new checkout gets: a subscriber already trialing keeps the one they started.
- **The organization's currency is on every product.** The provider makes no product without a price in the organization's default presentment currency, whatever currency the catalog pins. The sync reads it before anything else and refuses a catalog with a paid plan or a pack that has no price in it, in one line that names them and the currency to add, before it creates anything. The free plan's product and a plan's pass are priced at nothing in it by the sync itself, beside the catalog's own currency. `npx nuxt-backend doctor` warns of the same ([`billing-currency`](https://nuxt-backend.dev/docs/reference/cli/diagnostics#billing-currency)).
- **A currency the catalog adds is added.** A per-currency price gets a native presentment price in each currency on the same product. A currency the product has no price in yet is added, its other prices kept by id (`updated`, `adds its price in eur`), so nobody's subscription or order moves. An amount that differs in a currency both name is drift. A pack's gift twin follows the pack into the new currency in the same run.
- **The free plan is a $0 product.** A plan priced `{ month: 0 }` becomes a monthly product with a $0 price and the plan's benefits, recorded as `free` in the generated map. The sync refuses, before it creates anything: more than one free plan, a free plan priced by the year or per currency, one with a `trial` or with `usage`, and a plan free somewhere and paid elsewhere.
- **Drift is reported, never fixed.** A managed object whose key left the catalog shows as `drift` and stays at the provider. So does a product whose `name` or price, a meter whose aggregation or event name, or a credit benefit whose `units` or `rollover` no longer matches the catalog. The provider never rewrites a product or a meter once it carries orders or usage: rename the key to publish a new one. A benefit's grant changes in the dashboard, and new grants follow it.
- **A plan's quotas ride on one benefit.** A plan with `quotas` gets one feature-flag benefit, `<plan>-quotas`, whose metadata carries each quota as `quota_<key>`. It is attached to every product of the plan, on creation and to a product that exists already (`updated`), whose subscribers the provider grants it as well. A quota changed in the catalog is pushed to the benefit, and every subscriber's limit moves with it; a quota dropped allows none from then on. [What the sync writes](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas) has every rule, and the generated map's `quotas` maps each quota key to its `description`.
- **Benefits attach on creation, and to a product that exists.** A plan's `credits` become a meter-credit benefit per interval, and its `features` attach the matching custom benefits. A plan's product (or its pass) that the sync finds by its key gets the catalog's benefits it lacks attached, a grant or a feature added to the catalog since, or one another app's catalog on the same organization left off (`attached benefit <key> — to product <key>` in the log, `would-attach` on a dry run for a benefit that exists already). Attaching adds a grant and rewrites none, and the provider grants it to the product's current subscribers too. A credit benefit is never attached beside another one on the same meter, which would grant both: that product shows as `drift`, to swap in the dashboard. A pack's product that lacks its credits is `drift` too: the provider would credit everyone who ever bought the pack, at once, so attach it in the dashboard if they should have them. `npx nuxt-backend doctor` names a plan product that lacks its credits or a feature ([`billing-plan-benefits`](https://nuxt-backend.dev/docs/reference/cli/diagnostics#billing-plan-benefits)). A feature named in a plan but missing from `features` is a `warn`, and so is a pack whose credits do not roll over.
- **Each pack gets a private gift twin.** `<pack>-gift` has the pack's name with " (gift)", its prices and none of its benefits, so a purchaser who buys it for someone else is granted nothing ([Send and receive gifts](https://nuxt-backend.dev/docs/build/growth/offers/gifts)). It stays out of `products`, the price list and the checkout allow-list, and is listed under `gifts` by pack key. It follows its pack's live price, amount and currency, and a benefit attached to it in the dashboard is detached. It is the one product the sync rewrites, since nobody subscribes to it. A catalog key that is a pack's twin key (`<pack>-gift`) is refused.
- **Prices, trials and checkout fields are created with the product.** One fixed price per currency, plus one metered price per `usage` entry in the catalog `currency`. `trial` goes on the product, `taxBehavior` on each of its prices, and the `customFields` keys attach the checkout fields created right before it (`custom-field` in the log). A `usage` price or custom field naming a key missing from the catalog is a `warn`.
- **The webhook endpoint is provisioned** at `<site url>/billing/events`, subscribed to the provider's whole event catalog. Its secret is stored on the deployment as `BILLING_WEBHOOK_SECRET` through the `env push` engine, and never printed, so it lands in no terminal history or agent transcript. The site URL is `--webhook <url>` when given, else the HTTP origin of the deployment the secret goes to (its `.convex.site` URL, or a self-hosted backend's). A local deployment has no origin Polar can reach, so the sync skips the webhook there and says why. An endpoint whose secret would land on another deployment is refused. An existing endpoint's secret is stored when the deployment lacks one, and a deployment's secret is kept unless you pass `--force`. If storing fails, the command exits `1` and prints the `npx convex env set BILLING_WEBHOOK_SECRET` command that asks for the value.
- **Promotions are kept in line in place.** Each discount is found by its tag and patched where the catalog moved: its name, code, dates, caps and products always, its amount and months while nobody has redeemed it. A changed type or duration, or an amount changed after a redemption, is `drift`: retire the key and declare the new terms under another. A discount the sync refuses (no products, a code that is no code, a 100% forever code, a month count that would discount a whole year) stops the run before anything is created. See [Run a promotion](https://nuxt-backend.dev/docs/build/growth/offers#push-it).
- **The generated map is per environment.** `billing.generated.ts` keeps `sandbox` and `production` side by side, and syncing one leaves the other untouched.

### Flags

<table>
<thead>
  <tr>
    <th>
      Flag
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        --env sandbox|production
      </code>
    </td>
    
    <td>
      Target environment. Defaults to <code>
        production
      </code>
      
       when <code>
        BACKEND_ENVIRONMENT
      </code>
      
       is <code>
        production
      </code>
      
      , else <code>
        sandbox
      </code>
      
      . <code>
        sandbox
      </code>
      
       writes the deployment <code>
        .env.local
      </code>
      
       names and refuses a production deploy key; <code>
        production
      </code>
      
       writes the production deployment and refuses a dev or preview <code>
        CONVEX_DEPLOY_KEY
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        --dry-run
      </code>
    </td>
    
    <td>
      Print the plan (<code>
        would-create
      </code>
      
       entries) without creating anything or writing the generated file.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        --webhook <url>
      </code>
    </td>
    
    <td>
      Provision the endpoint at this URL instead of the derived one, such as a tunnel to a local deployment. <code>
        --webhook off
      </code>
      
       skips webhook provisioning.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        --force
      </code>
    </td>
    
    <td>
      Let a new endpoint's secret replace the deployment's <code>
        BILLING_WEBHOOK_SECRET
      </code>
      
      . Without it, an endpoint whose secret would replace one is not created.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        --adopt key=<id>[,key=<id>…]
      </code>
    </td>
    
    <td>
      Record an existing product, meter, custom field or discount under a catalog key instead of creating a managed twin. Adopted products keep their benefits exactly as they are, so nothing is granted twice.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        --cwd <dir>
      </code>
    </td>
    
    <td>
      Project directory.
    </td>
  </tr>
</tbody>
</table>

`BILLING_ACCESS_TOKEN` must be in the environment or `.env.local`: a sandbox token for `sandbox`, a live one for `production`. The command exits `1` without it, without a `billing.catalog.ts`, or on an unknown `--env`. A production sync with no URL the provider can reach is refused: pass `--webhook <url>`, or `--webhook off`.

## Retire a plan

A plan you no longer sell keeps its subscribers: mark it `retired: true` instead of deleting it.

```ts [backend/billing.catalog.ts]
plans: {
  creator2025: { name: 'Creator (2025)', prices: { month: 900 }, retired: true },
},
```

The next sync archives each of its products, at every interval it was ever sold at (`archived` in the log, `would-archive` on a dry run). An adopted product is recorded and left as it is, so archive that one in the dashboard. From then on:

- **Nobody new buys it.** The provider refuses a new checkout for its products, and so does the package: `generateCheckoutLink` and a plan change to it are refused as `invalid_input` with reason `retired`.
- **Everyone on it keeps it.** Subscribers renew on it, and can switch away from it.
- **It still reads back.** Its ids stay in the generated map under `retired`, so a subscriber's plan still reads by its key, and the [pricing page](https://nuxt-backend.dev/docs/build/billing/pricing-page#retired-plans) shows its card to its subscribers alone.

A plan retired before it was ever synced creates nothing. Delete the plan from the catalog once nobody holds it: the sync then reports its archived products as `drift`, and never deletes them.

## The free plan

A plan priced `{ month: 0 }` is the catalog's free plan. It is a real subscription at the provider, so its credits and features are granted every cycle like any plan's, and `useFeatures()` and `useCredits()` read them the same way.

```ts [backend/billing.catalog.ts]
plans: {
  free: { name: 'Free', prices: { month: 0 }, credits: { meter: 'credits', units: 20 }, quotas: { stories: 3 } },
  creator: { name: 'Creator', prices: { month: 1200 }, credits: { meter: 'credits', units: 500 }, trial: { interval: 'day', count: 14 } },
},
```

- **Every workspace the auth capability makes starts on it.** That is a first sign-in's personal workspace, and every workspace made with `useWorkspace().create()` or from your own function through the auth component. Where `registerBackendRoutes` mounts the auth routes, it connects billing, which queues the free plan on the scaffold's workpool: `billing:startFreePlan` finds or makes the workspace's customer and subscribes it, a few provider requests at a time, retried when the provider refuses one. Elsewhere, the auth capability queues `billing:startFreePlan` on the scheduler, once. With `billTo: 'user'`, each new account starts on it instead.
- **A workspace your code writes another way is not announced.** For one made by a data migration or an adapter write, call `billing.startFreePlan(ctx, entityId)`, or run the backfill below.
- **Each one is a provider customer.** The start makes the workspace's customer at once, so its owner's email (or the user's) reaches the provider at sign-up rather than at a first purchase. Creating a workspace is held to the `workspaceCreate` limit (five at once, then ten an hour per member), so one account can't mint free credits in a loop. Narrow it if your free plan grants a lot ([Tune rate limits](https://nuxt-backend.dev/docs/ship/security/rate-limits)).
- **A checkout upgrades it in place.** A checkout of a paid plan names the workspace's free subscription, which the provider moves to the plan. There is no second subscription, the plan's trial is still offered (one per owner, across their workspaces), and the plan's benefits replace the free plan's.
- **It comes back.** When a paid plan ends (cancelled at the period's end, or revoked), the workspace returns to the free plan. It doesn't when the workspace holds another plan, no longer exists, or the provider deleted its customer in an erasure. Whether it holds a plan is read from the provider, since a revoke may arrive before the update that ends it in the synced table.
- **Add-ons sit beside it.** With `setupBilling({ multipleSubscriptions: true })`, only a catalog plan's checkout upgrades the free subscription: a recurring add-on sits beside it and leaves its credits and features alone.
- **It is never sold.** A checkout of its product, a plan change to it, and a change, cancellation or pause of the free subscription are refused as `invalid_input` with reason `free_plan`. Its $0 cycles are left out of the order history, and DevTools folds a run of its deliveries into one row.
- **Existing workspaces join with a backfill.** A catalog that gains a free plan puts every workspace made from then on on it. For the ones that exist, run the backfill once per deployment: `npx convex run billing:startFreePlan '{}'` queues every workspace (or user), a page at a time, and leaves alone any that holds a plan.

### Welcome credits

`credits: { meter, units, once: true }` on the free plan grants `units` once per person, as the first workspace they own (or their account, with `billTo: 'user'`) first starts on the plan, and never again:

```ts [backend/billing.catalog.ts]
meters: { credits: { unit: { one: 'credit', other: 'credits' } } },
plans: {
  free: { name: 'Free', prices: { month: 0 }, credits: { meter: 'credits', units: 8, once: true } },
},
```

- **Once per person.** The person is the owner's address, once tags and dots are taken out of its local part, as the [reverse trial](https://nuxt-backend.dev/docs/build/growth/offers/plan-passes#run-a-reverse-trial) counts it: a second workspace of the same owner, and an account deleted and made again with the address, get none. The package keeps a hash of that form, never the address, and keeps it through an account's erasure, so the grant can't be had again by signing up again. Outside production (`BACKEND_ENVIRONMENT` anything but `production`), an email provider sandbox address counts whole, tag and all: each `delivered+<label>@resend.dev` is a person of its own, so every sandbox identity of the playground or a test gets its welcome credits once. Production strips the tag of those too.
- **No benefit at the provider.** `billing sync` pushes no credit benefit for them and writes `welcome: { meter, units }` to the generated map. A free plan that should also refill every cycle needs no `once`.
- **After the reverse trial.** The first start runs the reverse trial first, when the catalog has one, then queues the grant: a workspace on the trial's pass holds the pass's credits plus its welcome credits. A first start whose answer from Polar was lost queues the grant too.
- **Once, whatever runs twice.** The grant is a refund-shaped usage event keyed `welcome:<workspaceId>`. Polar drops a second event under the same key, so a retried grant, or two first starts that raced, grant nothing more, and the cached balance is credited once. A grant Polar refuses is retried, five attempts from two seconds apart, on the scaffold's workpool; without one it runs once, on the scheduler, and a refused grant is lost (`billing.welcome_credits_unqueued` logs a queue that refused).
- **Shown at once.** Polar applies the event a moment after it takes it, so the cached balance holds the credits for five minutes, through any read of Polar that does not count them yet, and the balance is read from Polar again once that window has passed.
- **Claimed before they are granted.** The person's one grant is claimed as it is queued, so a grant that does not land stays claimed: one Polar refused five times, or one whose workspace or customer was gone by then. Grant it by hand with `npx convex run billing:startFreePlan '{"entityId":"<id>","welcome":true}'`, which skips the claim.
- **On a first subscription ever.** A workspace that held a plan before gets none when it returns to the free plan. A start that finds the free plan already held, started within the hour and with no other plan in the workspace's history (a first start whose answer was lost, retried), queues them too; the reverse trial runs only from the start that made the subscription. The backfill grants them to every workspace it starts for the first time, one per person: on a production deployment that [launches billing](https://nuxt-backend.dev/docs/build/billing/setup#before-billing-launches) after early access, that is everyone who joined meanwhile. To grant them to one entity by hand, whoever had them, run `npx convex run billing:startFreePlan '{"entityId":"<id>","welcome":true}'`: it is the same grant under the same key.
- **On a sum meter.** `once` is the free plan's alone, takes `units` as one whole number, and needs a meter that sums `property`: a count meter takes no refund.
- **Shown on the pricing page.** `getPricing` carries them on the free plan as `welcome`, `usePricing().welcome` reads them, and `<PricingTable>` lists them on the free card (the `pricing.welcome` label, "8 credits to start").

`useBilling()` reads it as a subscription marked `free: true`, with the plan's key as its `productKey`: `isFree` is `true` on it, `isSubscribed` is `false`, and `plan` names it. `npx nuxt-backend doctor` warns when the Polar organization lets a customer hold several subscriptions beside it.

## Currencies

Price a plan or a pack per currency, and each currency becomes a native presentment price on the same product:

```ts [backend/billing.catalog.ts]
currency: 'usd',
plans: {
  creator: { name: 'Creator', prices: { usd: { month: 1200, year: 12000 }, eur: { month: 1100, year: 11000 } } },
},
packs: {
  credits500: { name: '500 credits', price: { usd: 2000, eur: 1800 }, credits: { meter: 'credits', units: 500 } },
},
```

- **One product, one subscription.** A customer paying in euros holds the same Creator plan as one paying in dollars: the same benefits, the same plan changes, the same quotas.
- **Every currency prices the same intervals**, and one of them is the catalog's `currency` (the organization's default presentment currency without it), which the provider needs on every product. A plan with `usage` stays in one currency, since its metered price bills in it.
- **The visitor pays in theirs.** `getPricing` takes the visitor's currency and answers every price in it where the catalog has one, else in the catalog's own. The [pricing page](https://nuxt-backend.dev/docs/build/billing/pricing-page#currencies) picks it from the request and offers a switch, and a checkout carries it (`currency`), refused as `invalid_input` for a currency the catalog does not price.
- **Gifts follow.** A pack's gift twin carries the pack's live price in every currency, and a gift checkout pays in one of them: `useGifts().send(pack, { recipientEmail, currency })`, refused as `invalid_input` for a currency the twin is not priced in. Without `currency` it pays in the catalog's own.

## Keep the products table fresh

The pricing page reads the deployment's products table, which the provider's `product.*` webhooks keep up to date. A benefit edited in the provider's dashboard (a pack's units, say) sends `benefit.updated` but no product event, so the package re-syncs the products table when that event arrives. The pricing page follows the edit within seconds.

## The generated map

```ts [backend/billing.generated.ts]
/* Generated by `npx nuxt-backend billing sync` — do not edit. */
import type { BillingCatalogIds } from 'nuxt-backend/billing'

export const catalog: Partial<Record<'sandbox' | 'production', BillingCatalogIds>> = {
  // After `creator2025` was retired.
  sandbox: {
    products: { 'free': 'prod_…', 'creator': 'prod_…', 'creator:year': 'prod_…', 'creator2025': 'prod_…', 'credits500': 'prod_…' },
    plans: { free: { month: 'prod_…' }, creator: { month: 'prod_…', year: 'prod_…' }, creator2025: { month: 'prod_…' } },
    retired: ['creator2025'],
    free: 'free',
    currency: 'usd',
    packs: ['credits500'],
    gifts: { credits500: 'prod_…' },
    meters: { credits: { meterId: 'meter_…', eventName: 'credits', property: 'amount' } },
    discounts: {
      launch: { id: 'disc_…', name: 'Launch offer', code: 'LAUNCH20', percentOff: 20, duration: 'repeating', months: 3, endsAt: '2027-01-31T23:59:59.000Z', productIds: ['prod_…'] },
    },
  },
}
```

`setupBilling(components, { catalog, email })` fills its `products` map and named `credits` meters from the entry for the deployment: `production` when `BACKEND_ENVIRONMENT` is `production`, `sandbox` everywhere else. Each key of an entry has one job:

- **products**: the list a checkout may sell, the retired plans' and the free plan's products aside. `useBilling().products` is keyed by it: `creator` is the monthly product, `creator:year` the yearly one.
- **plans**: each plan's product per interval, which `getPricing` groups. `appConfig.backend.billing.plans[].key` names a plan by this key on the pricing page.
- **retired**: the plans sold to nobody new. **free**: the free plan's key, whose product is in `plans`. **welcome**: its [welcome credits](#welcome-credits), the meter and how many. **currency**: the fallback currency, for a catalog priced in several.
- **packs**: the keys a [gift](https://nuxt-backend.dev/docs/build/growth/offers/gifts) may buy. **gifts**: the private product a purchaser pays for when they do.
- **meters**: what `useCredits({ meter: 'credits' })` and `spendCredits({ meter: 'credits' })` name, with each meter's `unit` when the catalog names one.
- **discounts**: each promotion that is not retired, with the terms checkout applies it by and the pricing page shows.

Explicit `products` and `credits` options still win when you need them.

<tip>

Every sync then runs `billing:syncProducts` on the deployment, so the reactive products table knows the products it created before their webhooks arrive. From then on, `product.*` webhooks keep it fresh. When the deployment can't load them, because it has no `BILLING_ACCESS_TOKEN` yet or bills in the other environment, the sync says which and finishes: set the token, then run `npx convex run billing:syncProducts`. It is an internal action, a deployment bootstrap you reach from the CLI and the dashboard, never from a client.

</tip>

In 0.2.0 the `simulated` entry and `--env simulated` are gone: development bills in Polar's sandbox.

## What happens when…

`billing sync` refuses before it creates anything, and exits `1`, when:

- `BILLING_ACCESS_TOKEN` is missing, `backend/billing.catalog.ts` is missing, or `--env` names no environment;
- the catalog has more than one free plan, a free plan priced by the year or per currency, or one with a `trial` or `usage`;
- a plan other than the free plan grants credits `once`, or welcome credits name a meter the catalog lacks, a count meter, or `units` that are no whole number above 0;
- a quota counts people, or a plan sets a quota the catalog does not declare ([Limit resources per plan](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas));
- a promotion has no products, a code that is no code, a 100% forever code, or months that would discount a whole year;
- a production sync has no URL Polar can reach: pass `--webhook <url>`, or `--webhook off`;
- the deploy key and `--env` disagree, such as a production key with `--env sandbox`.

At runtime, a checkout with no catalog for its environment is refused as `not_ready` (reason `no_catalog`), on a production deployment as `unavailable` (reason `not_launched`): billing is [not launched](https://nuxt-backend.dev/docs/build/billing/setup#before-billing-launches) there. A retired plan is refused as `invalid_input` (reason `retired`).

## Limits

- **Never deletes, never rewrites a held price.** Change a subscribed product's price in Polar's dashboard, or publish it under a new key.
- **One currency for usage.** A plan with a usage price bills it in the catalog's `currency`.
- **No seats.** Polar's seat-based pricing is beta, and the catalog has no field for it.
- **Benefit grants change in the dashboard.** The sync reports a changed `units` or `rollover` as drift, and new grants follow the dashboard.

## Test it

`--dry-run` reads Polar and prints the plan, without creating anything or writing the generated file. Run it in CI, with a sandbox token in the job's secrets, to catch a catalog the sync would refuse:

```bash
npx nuxt-backend billing sync --dry-run
```

A refusal exits `1` with its reason, so the job fails before a deploy, and `would-create` lines show what the next real sync adds ([Check every change in CI](https://nuxt-backend.dev/docs/develop/testing/ci)).

## Related

- [Polar](https://nuxt-backend.dev/docs/services/polar): the organization, its tokens, and the settings a catalog relies on.
- [Choose a pricing model](https://nuxt-backend.dev/docs/build/billing/pricing-models): which of plans, credits, usage and packs fits.
- [Customize the pricing page](https://nuxt-backend.dev/docs/build/billing/pricing-page): how the catalog reaches `/pricing`.
- [Run a promotion](https://nuxt-backend.dev/docs/build/growth/offers): the `discounts` the sync keeps in line.
- [`billing sync` in the CLI reference](https://nuxt-backend.dev/docs/reference/cli#billing-sync): its flags, side effects and exit codes.


## Sitemap

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