---
title: "Gate features by plan"
description: "Enforce a plan's features in your functions with requireFeature and the withFeature tier, gate the UI with useFeatures and Gate, and offer the plans that include a feature with UpgradePrompt: one feature key, read from one entitlement cache, on the server and in the browser."
canonical_url: "https://nuxt-backend.dev/docs/build/billing/subscriptions/feature-gating"
---
# Gate features by plan

> Enforce a plan's features in your functions with requireFeature and the withFeature tier, gate the UI with useFeatures and Gate, and offer the plans that include a feature with UpgradePrompt: one feature key, read from one entitlement cache, on the server and in the browser.

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/strips)
- [API reference](https://nuxt-backend.dev/docs/reference/api/use-features)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/billing/features.ts)

A feature is something a plan unlocks, named by one key: `hd_export`, `priority_queue`. You enforce it in the function that does the work, and the UI shows or hides what depends on it.

- **Polar does natively:** feature-flag benefits attached to products, granted and revoked with the subscription, and reported by webhook (checked on 2026-10-25).
- **The package adds:** one entitlement cache both sides read with the same match, so a gate in the browser and the check behind it never disagree, and a refusal that names the plans that include the feature, ready for an upgrade prompt.

## Name a feature

Declare each feature once in the [catalog](https://nuxt-backend.dev/docs/build/billing/catalog), and list it on the plans that include it. `billing sync` creates it as a Polar feature benefit with the key in its metadata (`{ managedBy: 'nuxt-backend', key }`):

```ts [backend/billing.catalog.ts]
features: {
  hd_export: { description: 'Exports in full resolution' },
  priority_queue: { description: 'Priority in the generation queue' },
},
plans: {
  creator: { /* … */, features: ['hd_export'] },
  studio: { /* … */, features: ['hd_export', 'priority_queue'] },
},
```

Every gate knows a benefit by one name: the `key` in its metadata, else its benefit id when it has no key. Nothing else matches: not a grant's id, not the provider's type (`feature_flag`), not another metadata value. For a benefit you make in Polar's dashboard, set a stable `key` in its metadata and gate on it the same way. The cache reads metadata live (the `benefit.updated` webhook patches it), so a renamed key takes effect without re-granting.

## Enforce it on the server

The gate that counts is in the function. `setupBilling` returns two checks that read the cache, never the provider:

<table>
<thead>
  <tr>
    <th>
      Call
    </th>
    
    <th>
      Answers
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        billing.requireFeature(ctx, key)
      </code>
    </td>
    
    <td>
      Nothing when the billing entity's plan grants <code>
        key
      </code>
      
      ; otherwise it throws <code>
        feature_required
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        billing.hasFeature(ctx, key)
      </code>
    </td>
    
    <td>
      <code>
        true
      </code>
      
       or <code>
        false
      </code>
      
      ; <code>
        false
      </code>
      
       too for a caller with no billing entity (signed out, no workspace)
    </td>
  </tr>
</tbody>
</table>

Both work in a query, a mutation or an action. Both check the caller first, the way the billing reads do: signed in, and a member of the workspace that pays, read fresh. Pass `{ userId }` to check an entity your server code chose itself, from a webhook handler or a cron. Never pass an id a caller sent: that would tell anyone whether any workspace has the feature.

For a function that sits entirely behind one feature, use the `withFeature(key)` tier. It is the `workspace` tier of [`createFunctions`](https://nuxt-backend.dev/docs/build/auth/access/functions) plus the feature: `ctx.user` and `ctx.workspace` as `workspace` injects them, and `feature_required` for a workspace whose plan lacks it. It comes from the same `createFunctions` call in `backend/functions.ts` as every other tier, with `billing` passed in ([Set up billing](https://nuxt-backend.dev/docs/build/billing/setup)):

```ts [backend/exports.ts]
import { v } from 'convex/values'
import { billing } from './billing'
import { withFeature, workspace } from './functions'

// The whole function is the feature's.
export const exportStory = withFeature('hd_export').action({
  args: { storyId: v.id('stories') },
  handler: async (ctx, { storyId }) => renderExport(ctx, ctx.workspace.id, storyId),
})

// One part of a function is.
export const storyStats = workspace.query({
  args: { storyId: v.id('stories') },
  handler: async (ctx, { storyId }) => ({
    views: await viewsOf(ctx, storyId),
    breakdown: await billing.hasFeature(ctx, 'hd_export') ? await breakdownOf(ctx, storyId) : null,
  }),
})
```

`renderExport`, `viewsOf` and `breakdownOf` are your own code.

The tier checks in the order a refusal should read: who the caller is (signed in, a member), then the feature, then a recent sign-in the function asks for. Someone who may not call it at all is never told to upgrade.

The plan it checks is the billing entity's, as billing resolves it: the active workspace, which is the `ctx.workspace` the handler gets, unless your `setupBilling({ resolveEntity })` names another. The tier is always the `workspace` tier, so with `billTo: 'user'` it still asks for a workspace member while it checks the user's own plan. To gate on a user's plan, or behind another tier, call `billing.requireFeature` in the handler:

```ts [backend/exports.ts]
import { billing } from './billing'
import { admin, authed } from './functions'

// billTo: 'user': the person's own plan, no workspace needed.
export const exportMine = authed.action({
  args: {},
  handler: async (ctx) => {
    await billing.requireFeature(ctx, 'hd_export')
    return renderAccountExport(ctx, ctx.user.id)
  },
})

// An administrator's function, on the plan of the workspace they act in.
export const queueReport = admin.query({
  args: {},
  handler: async (ctx) => {
    await billing.requireFeature(ctx, 'priority_queue')
    return queueReportOf(ctx)
  },
})
```

### The refusal

`feature_required` carries the feature and the plans on sale that include it, by catalog key, in pricing order (none when no plan on sale does). `getBackendError(error)` returns it as:

```ts
{ code: 'feature_required', data: { feature: 'hd_export', plans: ['creator', 'studio'] }, message: '…' }
```

It reads the same in the browser, in production too, and the `errors` labels word it ("Your plan doesn't include this. Upgrade to use it."). [Errors](https://nuxt-backend.dev/docs/reference/backend/errors#feature_required) lists its fields.

## Gate the UI

`useFeatures()` reads the same cache, live: a `benefit_grant.*` webhook updates every page that reads it.

```vue [app/pages/stories/[id].vue]
<script setup lang="ts">
const { has, hasPlan, isLoading } = useFeatures()
const { products } = useBilling()
</script>

<template>
  <ExportPanel v-if="has('hd_export')" />
  <StudioBadge v-if="products?.studio && hasPlan(products.studio.id)" />
</template>
```

`products` holds each product (`{ id, name }`) by catalog key, and is `undefined` while it loads. `isLoading` is `true` until the cache has loaded, and `error` holds why it could not be read (`{ code, data, message }`, see [Composable conventions](https://nuxt-backend.dev/docs/reference/nuxt/conventions)). While a read has failed, `has` and `hasPlan` say no: a gate closes rather than opens.

### `<Gate feature>`

`<Gate feature="hd_export">` renders its default slot only when the billing entity's plan grants the feature, and its `#fallback` slot when it doesn't. While the plan loads, and when it can't be read, it shows neither: never the content, and never a fallback that would offer a subscriber what they already have. The same component gates on a sign-in, a role, a workspace and a [quota](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas); its props and slots are on [Shell, gates and notices](https://nuxt-backend.dev/docs/reference/components/shell#gate).

```vue [app/pages/stories/[id].vue]
<template>
  <Gate feature="hd_export">
    <ExportPanel />
    <template #fallback>
      <UpgradePrompt feature="hd_export" />
    </template>
  </Gate>
</template>
```

To gate on a whole plan rather than a feature, read `useFeatures().hasPlan` as above.

## Offer the upgrade

`<UpgradePrompt>` says the plan lacks the feature and names the plans on sale that include it. It reads them from `getPricing`, by each plan's `featureKeys`, so it offers exactly what `requireFeature` names. It links to the first of them on the pricing page, `/pricing?plan=creator`, where `<PricingTable>` marks that plan's card (`data-requested`, and `plan.isRequested` in its slots). A workspace member who manages none of its billing gets no link: the prompt asks them to ask the owner or an admin. Its words are the [`upgrade` labels](https://nuxt-backend.dev/docs/build/ui/customize/labels#the-groups), and every region is a slot.

After a refusal from the server, hand the prompt the refusal's own plans:

```vue [app/components/ExportButton.vue]
<script setup lang="ts">
import { api } from '#backend/api'

const props = defineProps<{ storyId: string }>()
const exportStory = useAction(api.exports.exportStory)
const refusal = ref<ReturnType<typeof getBackendError>>(null)

async function run() {
  refusal.value = null
  try {
    await exportStory({ storyId: props.storyId })
  }
  catch (error) {
    refusal.value = getBackendError(error)
  }
}
</script>

<template>
  <button type="button" @click="run">Export</button>
  <UpgradePrompt
    v-if="refusal?.code === 'feature_required'"
    :feature="refusal.data.feature"
    :plans="refusal.data.plans"
  />
</template>
```

### Wait before asking again

A prompt that comes back on every click teaches people to close it without reading. `<UpgradePrompt :cooldown>` offers "Not now" and stays hidden for that long after someone dismisses it:

```vue [app/pages/strips/[id].vue]
<template>
  <Gate feature="hd_export">
    <ExportPanel />
    <template #fallback>
      <!-- Dismissed once, hidden for three days. -->
      <UpgradePrompt feature="hd_export" :cooldown="3 * 24 * 60 * 60 * 1000" />
    </template>
  </Gate>
</template>
```

`cooldown` is in milliseconds, and counts per feature for the signed-in person. The dismissal is kept in the browser: for the tab only, unless the person allowed the `preferences` purpose of optional storage, which keeps it in local storage ([Ask before optional storage](https://nuxt-backend.dev/docs/build/auth/accounts/consents#ask-before-optional-storage)). The gate itself never cools down: the content stays locked, and the server still refuses with `feature_required`. Only the prompt waits. A refusal from a click the person made shows the prompt again, since they asked for the feature.

## Quotas

A feature is on or off. A plan can also say how many of a thing a workspace may hold: 3 stories on Free, 50 on Creator. Those are quotas, declared in the same catalog, counted with `billing.requireQuota` in the mutation that makes the thing, and shown with `useFeatures().quota()`, `remaining()` and `<Gate quota>`. [Limit resources per plan](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas) covers them (experimental).

## Where grants come from

<table>
<thead>
  <tr>
    <th>
      Source
    </th>
    
    <th>
      Cache update
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Checkout completes
    </td>
    
    <td>
      <code>
        order.paid
      </code>
      
      , then <code>
        subscription.*
      </code>
      
       and <code>
        benefit_grant.created
      </code>
      
      , refresh the entity's plans, benefits and meters
    </td>
  </tr>
  
  <tr>
    <td>
      Plan change or cancellation
    </td>
    
    <td>
      <code>
        subscription.updated
      </code>
      
      , <code>
        subscription.canceled
      </code>
      
      , <code>
        subscription.revoked
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Benefit renamed or re-keyed in the dashboard
    </td>
    
    <td>
      <code>
        benefit.updated
      </code>
      
       patches the metadata snapshot in place
    </td>
  </tr>
  
  <tr>
    <td>
      Gift claimed
    </td>
    
    <td>
      The $0 claim order's <code>
        order.paid
      </code>
      
       refreshes the recipient's entity
    </td>
  </tr>
  
  <tr>
    <td>
      Webhooks not configured yet
    </td>
    
    <td>
      <code>
        syncEntitlements
      </code>
      
       (<code>
        useCredits().refresh()
      </code>
      
      ) on demand
    </td>
  </tr>
</tbody>
</table>

Fresh grants show in the DevTools [Billing tab](https://nuxt-backend.dev/docs/develop/devtools#billing) (Entitlements, by the same feature keys, and Quotas).

## What happens when…

- **The plan lacks the feature.** [`feature_required`](https://nuxt-backend.dev/docs/reference/backend/errors#feature_required), with the plans on sale that include it.
- **The caller may not call the function at all.** The tier refuses first (`unauthenticated`, `no_workspace`, `forbidden`), so nobody is told to upgrade for a function they can't use.
- **The cache can't be read.** `has` and `hasPlan` say no, and `<Gate>` shows neither its content nor its fallback.
- **A webhook is late.** The gate reads the last state Polar reported. A return from checkout refreshes it once.

## Limits

- **On or off.** A feature has no amount. Count things with [quotas](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas), and use with [credits](https://nuxt-backend.dev/docs/build/billing/credits).
- **Matched by key.** A benefit made in Polar's dashboard needs a `key` in its metadata, or it matches by its id.
- **The UI gate is a courtesy.** Only the server check protects the work.

## Test it

`createBackendMock` answers the feature read, so a test renders both sides of a gate:

```ts [test/app/export-gate.test.ts]
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { createBackendMock, resetBackendMock } from 'nuxt-backend/test-utils'
import { afterEach, expect, test } from 'vitest'
import ExportSection from '~/components/ExportSection.vue'

afterEach(() => resetBackendMock())

test('a plan without hd_export never renders the export panel', async () => {
  createBackendMock({ queries: { 'billing:getFeatures': { plans: [], benefits: [] } } })
  const section = await mountSuspended(ExportSection)
  expect(section.findComponent({ name: 'ExportPanel' }).exists()).toBe(false)
})
```

`ExportSection` is your component with the `<Gate feature="hd_export">` above. On the server, a `withFeature` function refuses a caller on Free with `feature_required`. In the demo, a [strip](https://nuxt-backend.dev/playground/strips) waiting to be drawn shows a `<Gate feature="priority_queue">`: Studio's line, or a link to the plans on Free.

## Related

- [Polar](https://nuxt-backend.dev/docs/services/polar): benefits, and what the sandbox grants.
- [Limit resources per plan](https://nuxt-backend.dev/docs/build/billing/subscriptions/quotas): how many of a thing a plan allows, refused the same way.
- [Protect backend functions](https://nuxt-backend.dev/docs/build/auth/access/functions): the `createFunctions` tiers `withFeature` builds on.
- [Errors](https://nuxt-backend.dev/docs/reference/backend/errors#feature_required): the refusal's fields.
- [Shell, gates and notices](https://nuxt-backend.dev/docs/reference/components/shell) and [`<UpgradePrompt>`](https://nuxt-backend.dev/docs/reference/components/billing#upgradeprompt): their props and slots.


## Sitemap

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