> ## Documentation Index
> Fetch the complete documentation index at: https://polar.sh/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Billing config

> Create, write, check, draft and publish a Pricing as Code billing config with the polar config commands.

A **billing config** is the file behind [Pricing as Code](https://polar.sh/docs/features/pricing-as-code/overview.md): it declares your organization's meters, benefits and products in your repository. This page covers the `polar config` commands that create, check, draft and publish it. Read the [overview](https://polar.sh/docs/features/pricing-as-code/overview.md) for what Pricing as Code changes for your organization, and [Versioning](https://polar.sh/docs/features/pricing-as-code/versioning.md) for how drafts, versions and existing customers work.

| File | For |
| - | - |
| `polar.config.ts` | JavaScript and TypeScript projects |
| `polar.config.json` | Every other project: Python, Go, Ruby, PHP and so on |

Work in sandbox until the user asks for production. Run `polar` commands with `--json` and read the fields, not the text. `validate` changes nothing. `init`, `draft`, `publish` and `disable` change the organization: run each only after the user agrees to what it will do. Never invent a product, price, currency or billing interval. Never store a Polar product, benefit or meter ID in code or env files: pass the external ID.

## Create the config

Install the [Polar CLI](https://polar.sh/docs/integrate/cli/introduction.md#installation), sign in to your [sandbox](https://polar.sh/docs/integrate/sandbox.md) organization and run `init`:

```bash Terminal theme={null}
polar auth login --sandbox
polar config init --sandbox
```

> [!WARNING]
>
> `init` turns Pricing as Code on, which makes the dashboard and the API read-only for products, benefits, meters and custom fields, so read [Before you adopt](https://polar.sh/docs/features/pricing-as-code/overview.md#before-you-adopt) first. You can undo it with `polar config disable` until a publish replaces your live catalog. That's your first `polar config publish` if your organization already had a catalog when you ran `init`, or your second if it started from scratch.

`init` writes the file from your current catalog. A new organization starts from scratch.

* **Format:** TypeScript in a project with a `package.json`, for which `init` also installs `@polar-sh/config`, and JSON otherwise. Pass `--format ts` or `--format json` to choose.
* **External IDs:** `init` suggests an external ID for each existing resource that doesn't have one, and asks you to confirm it.
* **Skipped resources:** `init` lists anything it left out of the file, and those stay on Polar as they are.

## Write the config

| Section | What it holds |
| - | - |
| Events | TypeScript only. The events your app sends, with a schema for each, so meters are type-checked against them |
| Meters | What usage to measure: a filter on your events and an aggregation |
| Benefits | Feature flags, meter credits, Slack channels and custom benefits |
| Products | Fixed, free, seat-based, unit-based and metered prices, flat or tiered, in one or more currencies. Recurring or one-time, with an optional trial |
| Custom fields | The questions checkout asks: text, number, date, checkbox and select |
| Settings | Organization-wide settings. See [Organization settings](#organization-settings) |

A config holds at most 100 meters, 100 benefits, 100 products and 100 custom fields. For what can't be in a config yet, see [Before you adopt](https://polar.sh/docs/features/pricing-as-code/overview.md#before-you-adopt).

The examples below are small. For every option, read the types of `@polar-sh/config`, or with a JSON config let `polar config validate` tell you which field is wrong and which values it accepts.

> [tab] TypeScript
>
> Each section is a function that receives its helpers and returns the entries by external ID.
>
> ```ts polar.config.ts theme={null}
> import { defineConfig, eq, eur, perThousand, usd } from '@polar-sh/config'
>
> export default defineConfig({
>   meters: ({ meter }) => ({
>     api_calls: meter('API calls').where(eq('name', 'api_call')).count(),
>   }),
>   benefits: ({ flag, credits }) => ({
>     priority_support: flag('Priority support'),
>     included_calls: credits('Included API calls').meter('api_calls').units(1000),
>   }),
>   products: ({ product, free, fixed, meter }) => ({
>     free: product('Free').prices(free()).recurring('monthly'),
>     pro: product('Pro')
>       .prices(
>         fixed().amount(usd(29), eur(27)),
>         meter('api_calls')
>           .flat()
>           .amount(perThousand(usd(2)), perThousand(eur(1.9))),
>       )
>       .recurring('monthly')
>       .grants(['priority_support', 'included_calls']),
>   }),
> })
> ```
>
> The package is fully typed. A wrong helper, or a meter or benefit key that does not exist, is a type error.

> [tab] JSON
>
> Each section is a list, and each entry carries its `external_id`. Entries refer to each other by external ID: a benefit names its `meter`, a product lists its `benefits`.
>
> ```json polar.config.json theme={null}
> {
>   "meters": [
>     {
>       "external_id": "api_calls",
>       "name": "API calls",
>       "filter": {
>         "conjunction": "and",
>         "clauses": [{ "property": "name", "operator": "eq", "value": "api_call" }]
>       },
>       "aggregation": { "func": "count" }
>     }
>   ],
>   "benefits": [
>     {
>       "external_id": "priority_support",
>       "description": "Priority support",
>       "type": "feature_flag"
>     },
>     {
>       "external_id": "included_calls",
>       "description": "1,000 API calls a month",
>       "type": "meter_credit",
>       "properties": { "meter": "api_calls", "units": 1000, "rollover": false }
>     }
>   ],
>   "products": [
>     {
>       "external_id": "free",
>       "name": "Free",
>       "recurring_interval": "month",
>       "prices": [{ "amount_type": "fixed", "price_currency": "usd", "price_amount": 0 }],
>       "benefits": []
>     },
>     {
>       "external_id": "pro",
>       "name": "Pro",
>       "recurring_interval": "month",
>       "prices": [
>         { "amount_type": "fixed", "price_currency": "usd", "price_amount": 2900 },
>         { "amount_type": "metered_unit", "price_currency": "usd", "meter": "api_calls", "unit_amount": "0.2" }
>       ],
>       "benefits": ["priority_support", "included_calls"]
>     }
>   ]
> }
> ```
>
> Amounts are in cents: `2900` is \$29.00, and a `unit_amount` of `"0.2"` is \$2 per 1,000 units.
>
> Unknown keys, comments and trailing commas are rejected.

Three rules hold in both formats:

* **Never rename an external ID.** Changing it removes the old resource and creates a new one, so change the name when you want customers to see something different.
* **A section you leave out is left alone**, so a file without `meters` doesn't touch your meters.
* **A section you include is complete.** A product missing from `products` is left out of the next catalog version, and an empty list takes every product off sale. `validate` lists each one as removed, but nothing is deleted and customers keep what they have.

### Organization settings

An optional `settings` section holds organization-wide settings: payments, subscriptions, the Customer Portal and customer notifications. Keys are camelCase in TypeScript and snake\_case in JSON.

**One trade-off:** a file with `settings` describes every setting, so any setting it leaves out goes back to its default, and `validate` shows that reset as a change. Leave the section out entirely to keep your settings as they are.

## Check, draft and publish

**1. Check what would change**

```bash Terminal theme={null}
polar config validate
```

`validate` lists every entry as created, updated, unchanged or removed, with the old and new value of each changed field. It also reports errors and warnings with their location in the file.

**2. Save the draft**

```bash Terminal theme={null}
polar config draft
```

`draft` shows the same plan, asks you to confirm, then saves the file to the draft catalog. Nothing a customer sees changes.

**3. Publish**

```bash Terminal theme={null}
polar config publish
```

`publish` makes the draft the live catalog and needs the owner or admin role.

If you edit the file after drafting, run `draft` again before you publish. `publish` warns you when the file has changes the draft doesn't. You can name the version with `--name` on either command. Existing customers keep the version they bought, see [What existing customers keep](https://polar.sh/docs/features/pricing-as-code/versioning.md#what-existing-customers-keep).

### When the draft and the file disagree

`draft` stops with a conflict when the draft on Polar has changes your file lacks, such as a teammate's changes that were never committed to the config file. Pick one:

| Command | What it does |
| - | - |
| `polar config draft --force` | Makes the draft match your file and discards the other changes |
| `polar config reset` | Rewrites your file to match Polar: the draft if there is one, the live catalog otherwise. Comments in the file are lost |

### Sandbox and production

Sandbox and production are separate organizations with separate catalogs, but the file doesn't record which one it belongs to, so the same file works for both. Check which organization is active with `polar auth whoami`, or pass `--org` to target one for a single command.

## Generate types

Supported languages: Python

> [!NOTE]
>
> `generate` only writes Python. Skip this section if you have a TypeScript config, which is already type-checked as you write it.

Your app refers to products, benefits and meters by external ID, and a typo in one of those strings only fails at run time. With a JSON config, generate them as constants and types your app imports:

```bash Terminal theme={null}
polar config generate
```

It writes one file next to the config, with every external ID and event name in it. For a Python project that is `polar_types.py`:

```python theme={null}
from polar_types import Benefits, Events, Meters, Products

Products.pro      # "pro"
Events.api_call   # "api_call", from the meters' filters
```

* Run it again after every change to the config and commit the file. Don't edit it by hand.
* `polar config generate --check` writes nothing and fails when the file is missing or out of date.

## Deprecate and prune

You can't remove a product from the file while customers still use it: `validate` reports it as an error. Mark it deprecated instead, then draft and publish:

```ts polar.config.ts theme={null}
legacy_pro: product('Pro (2025)')
  .prices(fixed().amount(usd(19)))
  .recurring('monthly')
  .deprecated(),
```

```json polar.config.json theme={null}
{
  "external_id": "legacy_pro",
  "name": "Pro (2025)",
  "deprecated": true,
  ...
}
```

A deprecated entry is left out of the next version, so nothing new can use it while the customers who have it keep it. See [Stop selling something](https://polar.sh/docs/features/pricing-as-code/versioning.md#stop-selling-something).

Once nobody uses a deprecated entry, remove it from the file:

```bash Terminal theme={null}
polar config prune
```

`prune` removes every deprecated entry nothing uses any more. It only edits your file and changes nothing on Polar.

### Change what a meter counts

Polar rejects a change to the filter or aggregation of a meter with billed usage. Add a new meter under a new external ID, point your prices and benefits at it, and deprecate the old one.

## Run it in CI

CI can show every pricing change on its pull request and release it when the pull request merges.

**1. Create two access tokens**

CI signs in with two [organization access tokens](https://polar.sh/docs/integrate/oat.md) stored as repository secrets: a read-only one for pull requests and a write one for the main branch. Only an owner or admin can create them.

```bash Terminal theme={null}
polar auth token \
  --scope organizations:read --scope meters:read --scope benefits:read \
  --scope products:read --scope catalogs:read \
  | gh secret set POLAR_READ_TOKEN

polar auth token \
  --scope organizations:write --scope meters:write --scope benefits:write \
  --scope products:write --scope catalogs:write \
  | gh secret set POLAR_WRITE_TOKEN
```

Piping into `gh secret set` keeps the token off your screen.

**2. Add the workflow**

This one is for GitHub Actions and a TypeScript config at the root of the repository.

```yaml .github/workflows/polar-config.yml theme={null}
name: Polar billing config

on:
  pull_request:
    paths: [polar.config.ts]
  push:
    branches: [main]
    paths: [polar.config.ts]

jobs:
  validate:
    if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22 }
      - run: npm ci
      - run: npm install -g @polar-sh/cli
      - run: polar config validate --pr-comment
        env:
          POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_READ_TOKEN }}
          GITHUB_TOKEN: ${{ github.token }}

  release:
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: production
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22 }
      - run: npm ci
      - run: npm install -g @polar-sh/cli
      - run: polar config draft --confirm
        env:
          POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }}
      - run: polar config publish --confirm
        env:
          POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_WRITE_TOKEN }}
```

What it does:

* **On a pull request** that changes the config, `validate --pr-comment` posts what would change as one comment and updates it on every push. The job fails when the config has errors, so a broken config can't merge. Pull requests from forks are skipped, because they get no secrets.
* **On a merge to main**, it saves the draft and publishes it. Remove the `publish` step if a person should publish after the merge.

To adapt it:

* **JSON config:** drop `npm ci` and point `paths` at `polar.config.json`. Add `polar config generate --check` to the `validate` job if you generate types.
* **Sandbox organization:** set `POLAR_ENVIRONMENT: sandbox` on the steps that run `polar`.
* **Approval before release:** `environment: production` is a GitHub environment, so giving it a required reviewer makes every pricing change wait for a person's approval after the merge.
* **Other CI systems:** `--pr-comment` also works in Buildkite for a repository on GitHub. Elsewhere, run the same commands without it.

## Learn more

| Resource | Description |
| - | - |
| [Pricing as Code](https://polar.sh/docs/features/pricing-as-code/overview.md) | What it is and what changes when you adopt it |
| [Versioning](https://polar.sh/docs/features/pricing-as-code/versioning.md) | Drafts, versions, external IDs and what existing customers keep |
| [`polar config` reference](https://polar.sh/docs/integrate/cli/reference/config) | Every command, argument and flag |
| [Usage](https://polar.sh/docs/concepts/usage.md) | Events, meters and metered prices |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.