# Scoping Data to the Active Organization

> Read and change organization data in loaders, actions and API handlers with the kit's guards, and keep stale tabs from writing to the wrong organization.

*Canonical: https://makerkit.dev/docs/void-cloudflare/organizations/scoping-data*

---

There's no row-level security: every query that touches organization data filters by the active organization, and every loader, action and handler checks it itself. The layout and the middleware only decide what's shown; they are not the guard.

This page is part of the [Organizations documentation](./overview).

## The Helpers

The guards that read the request are in `apps/web/lib/organizations.server.ts`; `hasPermission` and the permission constants come from `@kit/organizations` (`packages/organizations`):

| Helper | Returns | Fails with |
|---|---|---|
| `getActiveOrganization({ c })` | The active `Membership` (`{ id, name, roles }`) or `null` | never |
| `requireActiveOrganization({ c })` | The active `Membership` | 404 without one (and the sign-in redirect without a session) |
| `requireOrganizationAction({ c, organizationId, permission })` | The active `Membership` | 409 `ORGANIZATION_CHANGED` if `organizationId` isn't the active one; 403 without the permission |
| `hasPermission(membership, permission)` | Whether any of the member's roles grants it (`@kit/rbac`) | never |

Never read `session.activeOrganizationId` or trust an organization id from the request: the helpers take the membership the middleware read from the database.

## A Loader

```ts
// pages/(app)/projects/index.server.ts
import { defineHandler, type InferProps } from 'void';
import { db, eq } from 'void/db';

import { requireActiveOrganization } from '#/lib/organizations.server.ts';
import { projects } from '#/db/schema.ts';

export type Props = InferProps<typeof loader>;

export const loader = defineHandler(async (c) => {
  // 404 in the personal context; the id comes from the database, not the URL
  const organization = requireActiveOrganization({ c });

  const rows = await db
    .select()
    .from(projects)
    .where(eq(projects.organizationId, organization.id));

  return { projects: rows };
});
```

## An Action

Every form for organization data sends the `organizationId` it was rendered for. If the user switched organization in another tab, the action answers 409 instead of writing to the new one:

```ts
// pages/(app)/projects/index.server.ts (continued)
import { defineHandler } from 'void';
import { db } from 'void/db';
import * as z from 'zod';

import { requireOrganizationAction } from '#/lib/organizations.server.ts';
import { projects } from '#/db/schema.ts';

const body = z.object({ organizationId: z.string(), name: z.string() });

export const actions = {
  createProject: defineHandler.withValidator({ body })(async (c, { body }) => {
    const organization = requireOrganizationAction({
      c,
      organizationId: body.organizationId,
      // your own resource, added in packages/rbac/src/rbac.config.ts
      permission: { resource: 'project', action: 'create' },
    });

    await db.insert(projects).values({
      organizationId: organization.id,
      name: body.name,
    });
  }),
};
```

```tsx
// the form, with useForm from @void/react
const form = useForm('/projects?createProject', {
  organizationId: organization.id,
  name: '',
});
```

Show `ORGANIZATION_CHANGED` as "reload the page" (the kit's forms use `OrganizationErrorMessage` from `@kit/organizations/ui`). Add your own resources and actions to `packages/rbac/src/rbac.config.ts` ([Roles and Permissions](../members-management/roles-permissions)).

## API Handlers

The middleware runs on `/api` too, so a handler uses the same helpers: `requireActiveOrganization({ c })` for reads, and an `organizationId` in the body with `requireOrganizationAction` for writes.

## Your Tables

Give organization data an `organizationId` column that references `organization.id`. With `onDelete: 'cascade'` the database removes the rows when the organization is deleted. For anything else (files in storage, rows in another system) use an [after-delete hook](./deleting#after-delete-hooks).

Cascade only tables with few rows per organization, like `projects` below. For a table that grows without bound (events, logs, messages, audit rows), a cascade would delete millions of rows in the same transaction as the organization: it holds locks that block migrations and writes, and floods the database with WAL and dead rows ([PlanetScale: I don't like DELETE CASCADE](https://planetscale.com/blog/i-dont-like-delete-cascade)). Give such a table an indexed `organizationId` with no foreign key and declare it a [purge target](../cleanup/purge-targets): after the organization is deleted, its rows go in the background in small batches. Reads are already filtered by the membership, so rows waiting for the purge are never shown.

Index every column that references another table: without an index, each parent delete scans the whole child table.

Every id in the kit is a `uuid`, a UUIDv7 made in the app, so ids sort by creation time. Give your tables the same id, and make columns that reference another table's id `uuid` too: Postgres refuses a foreign key from `text` to `uuid`. A UUIDv7 shows when the row was created, so an id that works as a secret (like an invitation link's) is a random v4, `crypto.randomUUID()`.

```ts
// apps/web/db/schema.ts
import { v7 as uuidv7 } from 'uuid';
import { pgTable, text, uuid } from 'void/schema-pg';

import { organization } from './auth-schema';

export const projects = pgTable('projects', {
  id: uuid('id').$defaultFn(uuidv7).primaryKey(),
  organizationId: uuid('organization_id')
    .notNull()
    .references(() => organization.id, { onDelete: 'cascade' }),
  name: text('name').notNull(),
});
```

## Common Pitfalls

- Filtering by an id from the URL or the form. Filter by the `Membership` the helper returned.
- Checking the permission only in the layout or by hiding a button. The action checks it again.
- A form without `organizationId`: a stale tab would write to whichever organization is active now.
- Reading `useShared().organization` on the server. It's the browser's copy; server code reads the request through the helpers.

---

**Next:** [Deleting an Organization →](./deleting)
