# App templates: SaaS, marketplace, chat
Source: https://sovaria.in/docs/app-templates

Start from a working backend — tables with row-level security, storage buckets and their rules, realtime — applied to your project in one step, plus a React starter app wired to it.

A template is a backend someone already got right: the tables for a common kind of app, the row-level security that keeps each user to their own rows, the buckets and realtime events the app needs, and a **React + Vite starter app** that uses all of it. Apply one to a project from **Templates** (console sidebar › **More**), the CLI or the SDK, read its SQL, and change it like any other migration.

(Diagram: What applying a template does)

## The templates

| Template | Tables | What it shows |
|---|---|---|
| **SaaS starter** (`saas`) | `organizations`, `memberships`, `invitations`, `projects` | Multi-tenant rows: members see their organization's data; owners and admins manage members and invitation links (`accept_invitation(token)`); the creator becomes owner by trigger. |
| **Marketplace** (`marketplace`) | `listings`, `orders`, `reviews` | A public catalog, photos in the public bucket `listing-images` (sellers upload into their own folder), orders priced by a trigger so a client can't send its own total, reviews only by buyers. |
| **Chat** (`chat`) | `rooms`, `room_members`, `messages` | Public and private rooms, attachments in the private bucket `chat-attachments`, and realtime change events on `messages` and `rooms` so the app refreshes live. |

## Apply one

1. **Check the project** — A dry run lists every step and any table the project already has. It changes nothing. With a conflict, use a new project or an environment, or rename the existing table first.
2. **Apply** — Each step runs with **your own permissions**, exactly as if you made the change by hand: the migration needs database admin, buckets storage admin, access rules (bucket, function and channel) policies write, realtime project settings. Plan limits and the audit log apply.
3. **Get the starter app** — Download it from the template's card or with the CLI; its `.env` holds your project URL and anon key, so `npm install && npm run dev` runs it against your project.

CLI:
```bash
sov templates list
sov templates show chat --sql      # the SQL its migration runs
sov templates apply chat           # checks first, then asks
sov templates app chat             # ./sovaria-chat with .env filled in
cd sovaria-chat && npm install && npm run dev
```

JavaScript:
```ts
const check = await sov.api.templates.apply({ name: 'chat', dryRun: true })
// { ok: true, conflicts: [], steps: [{ type: 'migration', what: 'template chat: …', status: 'would apply' }, …] }
const done = await sov.api.templates.apply({ name: 'chat' })
done.steps.map((s) => `${s.type}: ${s.status}`)   // applied | skipped | failed (with detail)
```

Python:
```python
check = await client.api.templates.apply("chat", dry_run=True)
done = await client.api.templates.apply("chat")
```

HTTP:
```bash
curl -X POST "$SOVARIA_API/api/v1/governance/tenants/$ORG/projects/$PROJECT/templates/chat/apply" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"dry_run": true}'
```

## How it works

- The schema is one **migration** named after the template, with a down script: it shows under **Migrations** (sidebar › More) and can be reverted there. Applying again skips a migration that is already applied and a bucket that exists.
- Applying stops at the first refused step and says why; the steps before it stay applied.
- Every table **forces row-level security**. App users get only the rows the policies allow; the project team (console, service key) bypasses them. Helpers such as `is_member(org)` look memberships up with row security off for that one lookup, so a policy can use them without calling itself.
- Bucket rules are ordinary storage policies (`[bucket:<name>] own-folder` and so on) under Access › Policies, so you can change them like any other. So are the rules that let signed-in users call the template's functions (`[function:join_room]`, `[function:accept_invitation]`, decided as `fn:<name>`) and listen to its change events (`[channel:db.table.messages]`, subscribe only).
- Templates can live side by side in one project as long as their tables don't clash.

## The starter app

Each starter is a small React + Vite + TypeScript app on `@sovaria/sdk`: sign-up and sign-in, then every query through `sov.data.sql(...)` as the signed-in user, so row-level security decides what they see. The chat app listens on `db.table.messages` and refetches; marketplace photos use `sov.storage.publicUrl`. Read `src/App.tsx` to see each flow end to end.

> **Note:** The anon key in `.env` is meant for browser apps: it only identifies the project, and every query runs as the signed-in user. Never put the service key in a frontend.

## Plans

Templates are on every plan. What a template creates counts like anything you create by hand: tables and storage toward the database and storage limits, its access rules (up to five, for chat) toward the plan's access policies, realtime events toward the realtime quota.
