---
title: "Protect backend functions"
description: "Declare each Convex function at the access tier it needs, from one createFunctions call: signed in, a workspace member, an administrator, a role of yours, or a workspace whose plan has a feature."
canonical_url: "https://nuxt-backend.dev/docs/build/auth/access/functions"
---
# Protect backend functions

> Declare each Convex function at the access tier it needs, from one createFunctions call: signed in, a workspace member, an administrator, a role of yours, or a workspace whose plan has a feature.

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.

- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/functions.ts)

Every Convex function you export can be called by anyone who reaches your deployment. So declare each one at the tier it needs. `backend/functions.ts` calls `createFunctions` once and exports one builder per tier, and each builder checks the caller before your handler runs. A function's access is part of how you write it, and a forgotten check can't hide in a handler.

## Create the tiers

The scaffold writes `backend/functions.ts`:

```ts [backend/functions.ts]
import { createFunctions } from 'nuxt-backend/functions'
import { billing } from './billing'
import { rateLimiter } from './rateLimiter'
import { components } from './_generated/api'
import { action, mutation, query } from './_generated/server'

export const { authed, workspace, admin, withRole, withFeature, setUserRole } = createFunctions(
  { query, mutation, action },
  { components, billing, rateLimiter },
)
```

Each tier is a drop-in `{ query, mutation, action }`. Write your functions with it instead of `_generated/server`:

```ts [backend/strips.ts]
import { v } from 'convex/values'
import { authed, workspace } from './functions'

export const mine = authed.query({
  args: {},
  handler: async ctx => ctx.db.query('strips')
    .withIndex('authorId', q => q.eq('authorId', ctx.user.id))
    .take(50),
})

export const create = workspace.mutation({
  args: { title: v.string() },
  handler: async (ctx, { title }) =>
    ctx.db.insert('strips', { title, authorId: ctx.user.id, workspaceId: ctx.workspace.id }),
})
```

## The tiers

<table>
<thead>
  <tr>
    <th>
      Tier
    </th>
    
    <th>
      Lets in
    </th>
    
    <th>
      Adds to <code>
        ctx
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        authed
      </code>
    </td>
    
    <td>
      A signed-in person who is not banned. Queries read the token. Mutations and actions read the account fresh, so a ban lands on the next write.
    </td>
    
    <td>
      <code>
        ctx.user
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        workspace
      </code>
    </td>
    
    <td>
      A member of the active workspace, read fresh on every call, so a removed member is refused at once.
    </td>
    
    <td>
      <code>
        ctx.user
      </code>
      
      , <code>
        ctx.workspace
      </code>
      
       (<code>
        { id, slug, name, role }
      </code>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        admin
      </code>
    </td>
    
    <td>
      An app-wide administrator, the role read fresh on every call. Its writes refuse an administrator's visit to another account, and take a <a href="https://nuxt-backend.dev/docs/build/auth/access/step-up">
        recent sign-in
      </a>
      
      .
    </td>
    
    <td>
      <code>
        ctx.user
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        withRole(role)
      </code>
    </td>
    
    <td>
      A person with an app-wide role of yours, such as <code>
        withRole('editor')
      </code>
      
      .
    </td>
    
    <td>
      <code>
        ctx.user
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        withFeature(key)
      </code>
    </td>
    
    <td>
      A <code>
        workspace
      </code>
      
       member whose plan includes the feature. Others are refused <code>
        feature_required
      </code>
      
      , with the plans that include it (<a href="https://nuxt-backend.dev/docs/build/billing/subscriptions/feature-gating#enforce-it-on-the-server">
        Gate features by plan
      </a>
      
      ).
    </td>
    
    <td>
      <code>
        ctx.user
      </code>
      
      , <code>
        ctx.workspace
      </code>
    </td>
  </tr>
</tbody>
</table>

`ctx.user` holds `id`, `email`, `name` and `role`, and `signInMethod`: how the person signed in to this session, `'passkey'` or `'email-otp'`. It is the session's own method, so a code used in another browser never changes it. It is `null` while an administrator visits the account. A refusal is a [catalog error](https://nuxt-backend.dev/docs/reference/backend/errors) the page reads with `getBackendError`: `unauthenticated` when signed out, `forbidden` with a reason otherwise, `no_workspace` without an active workspace.

`setUserRole` is an internal mutation, never callable from a browser. It makes your first administrator ([Run the admin console](https://nuxt-backend.dev/docs/build/auth/admin#make-the-first-administrator)).

## Its options

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      What it does
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        components
      </code>
    </td>
    
    <td>
      Your generated <code>
        components
      </code>
      
      : the tiers read the <code>
        backend
      </code>
      
       component's tables.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        billing
      </code>
    </td>
    
    <td>
      Your <code>
        setupBilling
      </code>
      
       instance. It enables <code>
        withFeature
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rateLimiter
      </code>
      
      , <code>
        limits
      </code>
    </td>
    
    <td>
      Your <code>
        setupRateLimiter
      </code>
      
       instance, and a limit name per tier: <code>
        { authed: 'write', workspace: 'write' }
      </code>
      
      , as the scaffold has it, spends the <code>
        write
      </code>
      
       limit, keyed by user, on every mutation and action of those tiers (<code>
        withRole
      </code>
      
       spends <code>
        authed
      </code>
      
      's, <code>
        withFeature
      </code>
      
       <code>
        workspace
      </code>
      
      's). Declare <code>
        write
      </code>
      
       in <code>
        backend/rateLimiter.ts
      </code>
      
       (<a href="https://nuxt-backend.dev/docs/ship/security/rate-limits">
        Tune rate limits
      </a>
      
      ).
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        adminRoles
      </code>
    </td>
    
    <td>
      The roles the <code>
        admin
      </code>
      
       tier lets in. Default <code>
        ['admin']
      </code>
      
      .
    </td>
  </tr>
</tbody>
</table>

To keep [aggregate](https://nuxt-backend.dev/docs/build/data/read-write/aggregates) triggers running on every write, pass your `withTriggers`-wrapped `mutation` in place of the generated one.

## Ask more of one function

Two options sit beside `args` and `handler` in a function's definition:

- **recentSignIn**: `true` takes a sign-in from the last ten minutes, a number takes one from that many seconds. The `admin` tier's writes take it by default, and `recentSignIn: false` lifts it for a routine one ([Require a recent sign-in](https://nuxt-backend.dev/docs/build/auth/access/step-up#ask-in-your-own-functions)).
- **impersonation: 'refused'**: refuses an administrator's visit to the account (`forbidden`, reason `impersonating`). Use it where a person's money or access is at stake ([Impersonation](https://nuxt-backend.dev/docs/build/auth/admin/impersonation)).

```ts [backend/strips.ts]
import { v } from 'convex/values'
import { workspace } from './functions'

export const publish = workspace.mutation({
  recentSignIn: true,
  impersonation: 'refused',
  args: { stripId: v.id('strips') },
  handler: async (ctx, { stripId }) => {
    await ctx.db.patch('strips', stripId, { publishedAt: Date.now() })
  },
})
```

## Which one to reach for

- **Data a person owns:** `authed`, and filter by `ctx.user.id`.
- **Data a workspace owns:** `workspace`, and filter by `ctx.workspace.id` ([Scope tables to a workspace](https://nuxt-backend.dev/docs/build/data/read-write/workspace-scoped)).
- **A step that needs a passkey sign-in:** check `ctx.user.signInMethod === 'passkey'` in the handler, and refuse any other session with a `forbidden` reason of your own.
- **A step only a workspace's owner may take:** `workspace`, then check `ctx.workspace.role` in the handler and `throw backendError('forbidden', { reason: 'role' })`.
- **Operations on other people's accounts, or anything that moves money or mails typed addresses:** `admin`.
- **A role of your own across the app:** `withRole('editor')`.
- **A function a plan's feature unlocks:** `withFeature('hd-export')`.

A function nobody outside the deployment should call is an `internalQuery`, `internalMutation` or `internalAction` instead. The scaffold sends its emails that way.

## What happens when…

<table>
<thead>
  <tr>
    <th>
      Refused with
    </th>
    
    <th>
      When
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#unauthenticated">
        <code>
          unauthenticated
        </code>
      </a>
    </td>
    
    <td>
      Nobody is signed in.
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#forbidden">
        <code>
          forbidden
        </code>
      </a>
      
      , reason <code>
        banned
      </code>
    </td>
    
    <td>
      The account is banned. Writes read it fresh, so a ban lands on the next one.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
      
      , reason <code>
        role
      </code>
    </td>
    
    <td>
      The caller lacks the tier's role: <code>
        admin
      </code>
      
      , or the one <code>
        withRole
      </code>
      
       names.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
      
      , reason <code>
        impersonating
      </code>
    </td>
    
    <td>
      An administrator's visit calls an <code>
        admin
      </code>
      
       write, or a function with <code>
        impersonation: 'refused'
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#no_workspace">
        <code>
          no_workspace
        </code>
      </a>
    </td>
    
    <td>
      A <code>
        workspace
      </code>
      
       or <code>
        withFeature
      </code>
      
       function, called without an active workspace the caller belongs to.
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#feature_required">
        <code>
          feature_required
        </code>
      </a>
    </td>
    
    <td>
      A <code>
        withFeature
      </code>
      
       function, and the workspace's plan lacks the feature. <code>
        data.plans
      </code>
      
       lists those that have it.
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#reauthentication_required">
        <code>
          reauthentication_required
        </code>
      </a>
    </td>
    
    <td>
      A <code>
        recentSignIn
      </code>
      
       function, with an older sign-in.
    </td>
  </tr>
  
  <tr>
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#rate_limited">
        <code>
          rate_limited
        </code>
      </a>
    </td>
    
    <td>
      The tier's <code>
        limits
      </code>
      
       entry ran out for this caller.
    </td>
  </tr>
</tbody>
</table>

The page reads each one with `getBackendError` ([Handle errors](https://nuxt-backend.dev/docs/build/data/read-write/errors)).

## Test it

`asUser` signs a test in as a fresh account with its own workspace ([Test backend functions](https://nuxt-backend.dev/docs/develop/testing/functions)):

```ts [backend/strips.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 strip belongs to the caller\'s workspace', async () => {
  const t = testApp()
  const ada = await asUser(t)
  await ada.mutation(api.strips.create, { title: 'Monday' })
  await expect(t.mutation(api.strips.create, { title: 'Anonymous' })).rejects.toThrow()
})
```

## Related

- [Give people roles](https://nuxt-backend.dev/docs/build/auth/access/roles): the roles the tiers read.
- [Require a recent sign-in](https://nuxt-backend.dev/docs/build/auth/access/step-up): `recentSignIn`, and what the person sees.
- [Protect pages and routes](https://nuxt-backend.dev/docs/build/auth/access/pages): the same checks for the screen.
- [Handle errors](https://nuxt-backend.dev/docs/build/data/read-write/errors): reading a refusal in the page.


## Sitemap

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