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

# Multi-Tenancy

> How Terra organizes forms into workspaces, folders, and agencies

# Multi-Tenancy

> Terra supports multiple organizations through a flexible folder/agency model.

## Organization Structure

```mermaid theme={null}
flowchart TD
    Org[Organization] --> F1[Folder: Housing]
    Org --> F2[Folder: Food]
    F1 --> Form1[Rental Assistance]
    F1 --> Form2[Emergency Housing]
    F2 --> Form3[SNAP Application]

    Agency[External Agency] --> Client1[Client A]
    Agency --> Client2[Client B]
    Client1 --> F1
```

## Folders (Workspaces)

Folders provide logical grouping with:

* Custom branding (logo, colors)
* Custom domain
* Team access control
* Shared settings

```sql theme={null}
CREATE TABLE folders (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  slug TEXT UNIQUE,
  custom_domain TEXT,
  branding JSONB DEFAULT '{}'
);
```

## Custom Domains

Domains are resolved in middleware:

```typescript theme={null}
// src/middleware.ts
const host = request.headers.get("host");
const folder = await getFolderByDomain(host);

if (folder) {
  // Rewrite to folder context
  return NextResponse.rewrite(
    new URL(`/workspace/${folder.id}${pathname}`, request.url)
  );
}
```

**Domain hierarchy:**

1. Form-level domain (highest priority)
2. Folder-level domain
3. App domain (fallback)

## Agencies

Agencies are external partners managing multiple clients:

```sql theme={null}
CREATE TABLE agencies (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL
);

CREATE TABLE agency_clients (
  agency_id UUID REFERENCES agencies(id),
  folder_id UUID REFERENCES folders(id)
);
```

This enables a single partner to manage forms across multiple programs.

***

<CardGroup cols={2}>
  <Card title="Authorization" icon="shield" href="/core-systems/identity/authorization">
    Permission model
  </Card>

  <Card title="Custom Domains" icon="globe" href="/operations/custom-domains">
    DNS configuration
  </Card>
</CardGroup>
