---
title: "Scope tables to a workspace"
description: "Keep each workspace's rows to its members: stamp the active workspace on every write, read through an index on it, check a row's workspace before you touch it by id, and gate writes by the member's role."
canonical_url: "https://nuxt-backend.dev/docs/build/data/read-write/workspace-scoped"
---
# Scope tables to a workspace

> Keep each workspace's rows to its members: stamp the active workspace on every write, read through an index on it, check a row's workspace before you touch it by id, and gate writes by the member's role.

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.

A Panels workspace keeps its strips to its members: the author's personal workspace, or one a small team shares. Convex has no notion of tenants, so every query decides what it reads. The package's `workspace` tier checks the caller's membership, fresh on every call, and hands you the active workspace; three habits do the rest. Write its id on every row, read through an index on it, and check a row's workspace before you touch it by its id.

## Before you start

- A table with a `workspaceId: v.string()` field and an index on it, as in [Your data](https://nuxt-backend.dev/docs/build/data/your-data#define-a-table).
- The `workspace` tier from `backend/functions.ts` ([Protect backend functions](https://nuxt-backend.dev/docs/build/auth/access/functions)).

## Write and list the active workspace's rows

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

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

export const list = workspace.query({
  args: {},
  handler: ctx => ctx.db.query('strips')
    .withIndex('by_workspaceId', q => q.eq('workspaceId', ctx.workspace.id))
    .order('desc')
    .take(50),
})
```

Never take the workspace from the arguments: a member of one workspace could pass another's id. `ctx.workspace` is the session's active workspace, and a person switches it with `useWorkspace()` ([Workspaces](https://nuxt-backend.dev/docs/build/auth/workspaces)). Every query on the page follows the switch.

## Check a row you reach by its id

A function that takes a row's id checks the row's `workspaceId` before it reads or writes it. Refuse with the same error whether the row is missing or belongs to another workspace, so the answer says nothing about other workspaces:

```ts [backend/strips.ts]
import { backendError } from 'nuxt-backend/functions'

export const rename = workspace.mutation({
  args: { id: v.id('strips'), title: v.string() },
  handler: async (ctx, { id, title }) => {
    const strip = await ctx.db.get('strips', id)
    if (strip?.workspaceId !== ctx.workspace.id) {
      throw backendError('forbidden', { reason: 'other_workspace' })
    }
    await ctx.db.patch('strips', id, { title })
  },
})
```

## Let only some members write

`ctx.workspace.role` is the caller's role in the active workspace: `owner`, `admin` or `member`. Read it where a write is for some members only, such as removing another member's strip:

```ts [backend/strips.ts]
export const remove = workspace.mutation({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = await ctx.db.get('strips', id)
    if (strip?.workspaceId !== ctx.workspace.id) throw backendError('forbidden', { reason: 'other_workspace' })
    const mine = strip.authorId === ctx.user.id
    if (!mine && ctx.workspace.role === 'member') throw backendError('forbidden', { reason: 'role' })
    await ctx.db.delete('strips', id)
  },
})
```

The page guard and `<Gate workspace>` show a page or a region only inside a workspace; the function's check is the one that holds. [Workspaces](https://nuxt-backend.dev/docs/build/auth/workspaces) lists what each built-in role may do with the workspace itself.

## When a workspace or an account goes

Your rows stay until your code deletes them. Delete a workspace's rows from a source in `backend/account.ts`, which an account's erasure runs for the workspaces that go with it: the personal one, and any it was the only member of. A row in a workspace that stays keeps its `authorId`. Clear or reassign that field in the same source when it names the person. [Export and erase account data](https://nuxt-backend.dev/docs/build/auth/accounts/data) shows the source's two functions.

## Show it in a page

The list follows the active workspace. When a person switches with `useWorkspace()`, the query re-runs for the new one:

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

definePageMeta({ auth: { workspace: true } })

const { isReady } = useAuth()
const strips = useQuery(api.strips.list, () => (isReady.value ? {} : 'skip'))
const { current } = useWorkspace()
</script>

<template>
  <main>
    <h1>{{ current?.name }}: strips</h1>
    <p v-if="strips === undefined" role="status">Loading strips…</p>
    <ul v-else>
      <li v-for="strip in strips" :key="strip._id">{{ strip.title }}</li>
    </ul>
  </main>
</template>
```

## What happens when…

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

<tbody>
  <tr>
    <td>
      The caller is signed out
    </td>
    
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#unauthenticated">
        <code>
          unauthenticated
        </code>
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      The session has no active workspace
    </td>
    
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#no_workspace">
        <code>
          no_workspace
        </code>
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      The caller left the workspace, or was removed, while the page was open
    </td>
    
    <td>
      <a href="https://nuxt-backend.dev/docs/reference/backend/errors#forbidden">
        <code>
          forbidden
        </code>
      </a>
      
       on the next call
    </td>
  </tr>
  
  <tr>
    <td>
      The row belongs to another workspace, or is gone
    </td>
    
    <td>
      <code>
        forbidden
      </code>
      
      , reason <code>
        other_workspace
      </code>
      
      , from your own check
    </td>
  </tr>
</tbody>
</table>

## Limits

- **Keep the index.** An index that starts with `workspaceId` keeps a read as small as the workspace, whatever the table's size.
- **A person's own settings** belong to the account, not a workspace: store them by `ctx.user.id` and read them in the `authed` tier.
- **Internal functions, jobs and migrations** have no active workspace and see every row. Keep cross-workspace work there, and check who may start it.
- **Built-in roles only.** Custom workspace roles wait for a later release ([Roadmap](https://nuxt-backend.dev/docs/start/roadmap)).

## Test it

```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('each workspace reads only its own strips', async () => {
  const t = testApp()
  const ada = await asUser(t)
  const grace = await asUser(t)
  const id = await ada.mutation(api.strips.create, { title: 'Monday' })
  expect(await grace.query(api.strips.list, {})).toEqual([])
  await expect(grace.mutation(api.strips.rename, { id, title: 'Mine now' }))
    .rejects.toMatchObject({ data: { code: 'forbidden' } })
})
```

## Related

- [Your data](https://nuxt-backend.dev/docs/build/data/your-data): the tables beside the component, and the tiers.
- [Protect backend functions](https://nuxt-backend.dev/docs/build/auth/access/functions): the `workspace` tier and its refusals.
- [Workspaces](https://nuxt-backend.dev/docs/build/auth/workspaces): the active workspace, members and the built-in roles.
- [Handle errors](https://nuxt-backend.dev/docs/build/data/read-write/errors): how a page reads `forbidden` and its reason.
- [Test backend functions](https://nuxt-backend.dev/docs/develop/testing/functions): `asUser` and two workspaces in one test.


## Sitemap

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