@supatype/cli 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/cli-version-embedded.js +1 -1
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +2 -0
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-generator.d.ts +2 -0
  7. package/dist/client-generator.d.ts.map +1 -1
  8. package/dist/client-generator.js +1 -1
  9. package/dist/client-generator.js.map +1 -1
  10. package/dist/commands/admin.d.ts +4 -0
  11. package/dist/commands/admin.d.ts.map +1 -1
  12. package/dist/commands/admin.js +10 -2
  13. package/dist/commands/admin.js.map +1 -1
  14. package/dist/commands/cloud.d.ts.map +1 -1
  15. package/dist/commands/cloud.js +6 -2
  16. package/dist/commands/cloud.js.map +1 -1
  17. package/dist/commands/dev.d.ts.map +1 -1
  18. package/dist/commands/dev.js +2 -0
  19. package/dist/commands/dev.js.map +1 -1
  20. package/dist/commands/diff.d.ts +32 -0
  21. package/dist/commands/diff.d.ts.map +1 -1
  22. package/dist/commands/diff.js +17 -8
  23. package/dist/commands/diff.js.map +1 -1
  24. package/dist/commands/generate.d.ts +5 -0
  25. package/dist/commands/generate.d.ts.map +1 -1
  26. package/dist/commands/generate.js +11 -4
  27. package/dist/commands/generate.js.map +1 -1
  28. package/dist/commands/init.d.ts.map +1 -1
  29. package/dist/commands/init.js +4 -1
  30. package/dist/commands/init.js.map +1 -1
  31. package/dist/commands/logs.d.ts +27 -0
  32. package/dist/commands/logs.d.ts.map +1 -1
  33. package/dist/commands/logs.js +66 -11
  34. package/dist/commands/logs.js.map +1 -1
  35. package/dist/commands/mcp.d.ts +7 -0
  36. package/dist/commands/mcp.d.ts.map +1 -0
  37. package/dist/commands/mcp.js +19 -0
  38. package/dist/commands/mcp.js.map +1 -0
  39. package/dist/commands/push.d.ts +106 -2
  40. package/dist/commands/push.d.ts.map +1 -1
  41. package/dist/commands/push.js +139 -43
  42. package/dist/commands/push.js.map +1 -1
  43. package/dist/commands/status.d.ts +41 -0
  44. package/dist/commands/status.d.ts.map +1 -1
  45. package/dist/commands/status.js +107 -58
  46. package/dist/commands/status.js.map +1 -1
  47. package/dist/generated/llms-docs.d.ts +2 -0
  48. package/dist/generated/llms-docs.d.ts.map +1 -0
  49. package/dist/generated/llms-docs.js +5 -0
  50. package/dist/generated/llms-docs.js.map +1 -0
  51. package/dist/generated/release-images.d.ts +4 -4
  52. package/dist/generated/release-images.js +2 -2
  53. package/dist/local-secrets.d.ts +12 -0
  54. package/dist/local-secrets.d.ts.map +1 -1
  55. package/dist/local-secrets.js +21 -5
  56. package/dist/local-secrets.js.map +1 -1
  57. package/dist/mcp/docs-search.d.ts +20 -0
  58. package/dist/mcp/docs-search.d.ts.map +1 -0
  59. package/dist/mcp/docs-search.js +112 -0
  60. package/dist/mcp/docs-search.js.map +1 -0
  61. package/dist/mcp/server.d.ts +19 -0
  62. package/dist/mcp/server.d.ts.map +1 -0
  63. package/dist/mcp/server.js +125 -0
  64. package/dist/mcp/server.js.map +1 -0
  65. package/dist/mcp/tools.d.ts +59 -0
  66. package/dist/mcp/tools.d.ts.map +1 -0
  67. package/dist/mcp/tools.js +80 -0
  68. package/dist/mcp/tools.js.map +1 -0
  69. package/dist/model-hooks.d.ts +2 -1
  70. package/dist/model-hooks.d.ts.map +1 -1
  71. package/dist/model-hooks.js +4 -1
  72. package/dist/model-hooks.js.map +1 -1
  73. package/dist/model-summary.d.ts +13 -0
  74. package/dist/model-summary.d.ts.map +1 -0
  75. package/dist/model-summary.js +55 -0
  76. package/dist/model-summary.js.map +1 -0
  77. package/dist/pull-utils.d.ts +1 -0
  78. package/dist/pull-utils.d.ts.map +1 -1
  79. package/dist/pull-utils.js +62 -6
  80. package/dist/pull-utils.js.map +1 -1
  81. package/dist/push-project.d.ts +94 -0
  82. package/dist/push-project.d.ts.map +1 -0
  83. package/dist/push-project.js +187 -0
  84. package/dist/push-project.js.map +1 -0
  85. package/dist/push-refusal.d.ts +5 -0
  86. package/dist/push-refusal.d.ts.map +1 -1
  87. package/dist/push-refusal.js +13 -0
  88. package/dist/push-refusal.js.map +1 -1
  89. package/dist/runtime-routes.d.ts.map +1 -1
  90. package/dist/runtime-routes.js +13 -0
  91. package/dist/runtime-routes.js.map +1 -1
  92. package/dist/schema-ast-v2.d.ts +2 -0
  93. package/dist/schema-ast-v2.d.ts.map +1 -1
  94. package/dist/schema-ast-v2.js +2 -0
  95. package/dist/schema-ast-v2.js.map +1 -1
  96. package/dist/self-host-compose.d.ts +2 -0
  97. package/dist/self-host-compose.d.ts.map +1 -1
  98. package/dist/self-host-compose.js +63 -3
  99. package/dist/self-host-compose.js.map +1 -1
  100. package/dist/type-extractor.d.ts.map +1 -1
  101. package/dist/type-extractor.js +5 -0
  102. package/dist/type-extractor.js.map +1 -1
  103. package/dist/type-resolver.d.ts.map +1 -1
  104. package/dist/type-resolver.js +1 -0
  105. package/dist/type-resolver.js.map +1 -1
  106. package/dist/ui/runtime/command-chrome.d.ts.map +1 -1
  107. package/dist/ui/runtime/command-chrome.js +2 -0
  108. package/dist/ui/runtime/command-chrome.js.map +1 -1
  109. package/package.json +7 -5
@@ -0,0 +1,2 @@
1
+ export declare const LLMS_FULL_TEXT = "# Supatype: full context for language models\n\nDocs version: Supatype 0.11.0 (released 2026-11-29). Engine v0.12.0, server v2.7.0, Postgres 17.2.16, Deno 2.9.8.\n\n> Zero drift: one set of TypeScript types runs the whole stack, database to component. One schema derives the Postgres tables, migrations, row-level security, REST and GraphQL APIs, auth, storage, realtime, Studio editing views and the typed client. Self-hostable. SDKs MIT, CLI and services Apache 2.0, API server MIT, Postgres image PostgreSQL License, schema engine source-available under BSL 1.1.\n\nThis file is the expanded companion to https://www.supatype.com/llms.txt: a summary first, then the full text of every docs and guide page. Prefer linking agents here when they need product facts without scraping HTML.\n\n## What it is\n\nSupatype lets developers define backend data models as TypeScript `Model<>` types. That schema is the contract. From it, the platform generates and keeps in step:\n\n- PostgreSQL tables, indexes and migrations, with a recorded rollback and a risk class for every change (safe, cautious, destructive). After the transaction commits, new indexes on tables with rows are built `CONCURRENTLY` and new constraints are validated online\n- Row-level security policies from access rules on models (`Public`, `LoggedIn`, `Owner<>`, `OwnerFrom<>`, `Role<>`, combined with `Any<>`, `All<>`, `Not<>`); field rules mask or refuse single columns\n- REST (PostgREST) and GraphQL (pg_graphql) APIs, both running as the caller so row-level security applies\n- The typed client and framework bindings your components use\n- Auth (email and password, magic links, OAuth providers, MFA)\n- Storage buckets from `Bucket<>` types, with accept lists, size limits, access rules, image transforms and time-limited signed URLs\n- Realtime change subscriptions, presence and broadcast; each event, deletes included, reaches only subscribers allowed to read that row\n- Studio: a schema-generated admin and CMS (lists, forms, rich text, blocks, media library, drafts, versions, live preview, SQL runner, migration history). Four roles on self-host: admin, developer, editor and viewer (Cloud adds owner and billing). Admins and developers work with full access by default. Editors and viewers work in Studio mode, where the app's row rules are skipped and its field rules and masks still apply\n\n\"Zero drift\" means: change a field once and every layer follows; rename a field and the TypeScript build fails instead of production.\n\n## What it is not\n\n- Not a proprietary document store: data lives in standard Postgres, and a `pg_dump` takes it anywhere.\n- Not \"SQL first, then generate types\". Types are upstream; SQL is generated.\n- Not a migration tool that guesses. Renames are declared (`supatype rename`, recorded in `supatype/renames.json`); an undeclared drop is refused until you consent.\n\n## How developers use it\n\n1. Install the CLI with `npm install -g @supatype/cli` (on Linux and macOS, also `curl -fsSL https://supatype.com/install.sh | bash` or `brew install supatype/tap/supatype`) and create a project with `supatype init`.\n2. Author models in `schema/index.ts`.\n3. Run `supatype dev`. It starts the stack in Docker Compose (or natively), applies the schema, and on every save migrates the database and regenerates the typed client. It keeps running; use a second terminal for other commands. It stops with its stack when the process that started it exits (a killed script, a cancelled CI job), as on Ctrl+C; to leave a stack running with nothing attached, use `supatype self-host compose up -d`. If `dev` itself is killed (its process ended, or its window closed before it finished stopping), the stack can be left running: the next `supatype dev` offers to stop it, and `supatype self-host compose down` stops it now.\n4. Apply the schema to another database (staging, production, a self-hosted server) with `supatype push`. `supatype diff` previews a change; `supatype migrate` writes the SQL without applying it.\n5. Deploy: self-host with `supatype self-host compose up` on a server you own, or Supatype Cloud (`supatype link`, `supatype deploy`), which is in closed beta: request access at https://www.supatype.com/#cloud.\n6. Bring an existing database: `supatype pull --out schema/index.ts` drafts the types from it; `supatype adopt` hands Supatype tables that already exist under the schema's names.\n\n## Stack notes\n\n- Schema engine: a Rust binary the CLI downloads from releases.supatype.com. It plans and applies migrations, policies and grants, waits at most a few seconds for table locks, and builds indexes and validates constraints online on tables with rows.\n- Gateway: Kong in front of PostgREST, `supatype-server` (Go: auth and the gateway), storage, realtime and the Deno functions worker. The gateway decides CORS: the site URL, `api.corsOrigins` and a list saved in Studio; `*` only when written.\n- Extensions (PostGIS, pgvector, unaccent, pgcrypto) are created in the `extensions` schema; their functions are not API endpoints, so expose one through a SQL function of your own. REST is PostgREST 14.18, which needs a JWT secret of at least 32 characters.\n- Realtime: a WAL-based service (`supatype/realtime`) reading logical replication; it judges every event, deletes included, against the schema's generated read rules.\n- Images: `supatype/postgres` (Postgres 17 with PostGIS, pgvector, pg_graphql and others), `supatype/server`, `supatype/realtime`, `supatype/storage`, `supatype/studio`, `supatype/functions-worker`, `supatype/schema-engine`, `supatype/control-plane`.\n\n## Building an app: key facts\n\nSchema (https://www.supatype.com/docs/schema.html):\n- Models are `Model<Fields, Meta>` types exported from `schema/index.ts`, imported from `@supatype/types`. The table name is the type name in snake case (`BlogPost` is `blog_post`); `tableName` overrides it.\n- Fields are required unless wrapped in `Optional<>`. Plain `string`, `number` (float) and `boolean`, a union of string literals for an enum, and `Int`, `UUID`, `Timestamp`, `JSON<T>`, `RichText`, `Blocks<T>`, `Slug<\"title\">`, `ImageAsset<Bucket>`, `SupatypeAuthUserId`. `Identity<>` declares an identity column and `Generated<T, \"expr\">` a stored generated column.\n- A model index can name its method with `using` (`\"gist\"`, `\"hnsw\"` and others). An `hnsw` index uses cosine distance unless `distance` is `\"l2\"` or `\"innerProduct\"`.\n- `Blocks<T>` entries are `{ type, data }`, with the block's fields under `data`. `supatype push` moves rows written in the pre-0.7.0 flat shape.\n- `RelatedTo<M>` adds `<field>_id`, nullable unless `{ required: true }`, `onDelete` default `\"restrict\"`. `HasMany` and `HasOne` add no column. `ManyToMany` makes one junction per pair, named from both tables in alphabetical order (`post_tag`).\n- Access rules per `read`, `create`, `update`, `delete`: `Public`, `LoggedIn`, `Private`, `Owner<\"col\">`, `OwnerFrom<\"rel\">`, `Role<\"name\">` (reads `app_metadata.role`), `Any`, `All`, `Not`, and comparisons `Eq`, `Neq`, `Gt`, `Gte`, `Lt`, `Lte`, `Like`. An operation with no rule is denied.\n- Field rules go in `access.fields`; an unreadable column comes back `null`. A model with `versions` cannot have field rules.\n- `versions: { drafts: true }`: the model's table holds the published record; drafts and history are in `<table>_versions`; direct API updates of the live row are refused (`42501`).\n- `SupatypeAuthUserId` has no foreign key unless `onDelete` (`\"cascade\"`, `\"restrict\"`, `\"setNull\"`) is set; with an `Owner<\"col\">` create rule it defaults to the caller's id.\n- Renames are recorded with `supatype rename` in `supatype/renames.json`. `supatype push --yes` does not ask about renames.\n\nClient (https://www.supatype.com/docs/client.html):\n- Import `createClient` from the generated `supatype/generated/client.ts`, with no type argument. It knows which models keep drafts.\n- On a drafts model, `update` saves a draft; `update(data, { publish: true })` also publishes; `.draft()` reads drafts; `rpc(\"publish\", { model_table, record_id }, { schema: \"supatype\" })` publishes.\n- Realtime: `from(table).subscribe(cb, { event })`. Functions: `functions.invoke(name, { body })`. `error` is a `SupatypeError` (an `Error`) with `message` and, when known, `code`, `status`, `details`, `hint` and `field`. A cached read reports `meta.cacheStatus` (`HIT`, `MISS` or `BYPASS`) on the result, not at its top level. `global(name)` reads and updates a singleton model's one row. Auth calls and storage object calls (upload, download and the rest) throw on a network failure.\n- `BigInt` columns read as `bigint`; `Decimal` and `Money` read as strings, so no digits are lost.\n- GraphQL: `graphql<T>(query, variables)`. Rich text, blocks and json fields come back as objects, not the JSON strings pg_graphql sends: the client reads the schema once per role and decodes every `JSON` scalar field the query selects, through aliases, fragments, relations and lists. A field it cannot place stays as returned. Relation fields use the schema's names (`talks`, not `talkCollection`) from the first push on 0.7.0.\n\nSeeding (https://www.supatype.com/docs/seeding.html):\n- `seeds/*.ts` run alphabetically, each exporting `default async function seed({ db, expr, log }: SeedContext)` from `@supatype/cli/seed`. The builder records writes; the engine applies each file in one transaction.\n- Prefer `upsert({ where, data })` keyed by a primary or unique key. Nested `create` children under an upsert are added only when no identical child exists.\n- `RichText` accepts a plain string. `expr.default()` (`{ \"$default\": true }`) resets a column to its default. Relations take `{ connect: { key: value } }`.\n- Seeds cannot create sign-in users: create them with `supatype admin create-user` or the auth API, then reference their ids. Many-to-many rows go through `db.$sql`. Its string params bind as `text`, so cast them where the column needs another type, as in `$1::uuid`.\n- Blocks values are `{ type, data }`.\n\nStudio roles (https://www.supatype.com/docs/studio-roles.html):\n- Self-host roles: admin, developer, editor, viewer. Only admins give or change Studio roles, and a developer cannot change an admin's account.\n- Admins and developers work with full access (service role, no rules or masks). Editors and viewers work in Studio mode: the app's row rules are skipped, field rules and masks apply.\n- Try it, GraphQL and Invoke offer \"Send as\": Me (default), Anonymous, Service role (admins and developers only), or a pasted token.\n- Grant a role in Studio under Authentication > Users (Studio access), or with `supatype admin create-user --role <role>` and `supatype admin set-role`.\n\n## Differentiators vs common alternatives\n\n| Alternative | Typical gap vs Supatype |\n|-------------|-------------------------|\n| Supabase | Strong Postgres platform; types are introspected after the fact, RLS is hand-written SQL, and the Studio is a database console rather than a CMS |\n| Payload CMS | Strong CMS; you assemble auth, storage, realtime and the database yourself |\n| Prisma | Schema to types and migrations; you still write access rules and the API |\n| Convex / Firebase | Type-safe DX; not Postgres, no SQL |\n\n## Public URLs\n\n- Site: https://www.supatype.com/\n- LLM index: https://www.supatype.com/llms.txt\n- This file: https://www.supatype.com/llms-full.txt\n- Licensing: https://www.supatype.com/licensing.html\n- Upgrade notes for 0.7.0: https://github.com/supatype/supatype/blob/main/UPGRADING.md\n- Docs: https://www.supatype.com/docs/\n- Schema guide: https://www.supatype.com/docs/schema.html\n- Client guide: https://www.supatype.com/docs/client.html\n- Seeding guide: https://www.supatype.com/docs/seeding.html\n- Studio roles guide: https://www.supatype.com/docs/studio-roles.html\n- VM deploy guide: https://www.supatype.com/deploy-vm-github-actions.html\n- GitHub org: https://github.com/supatype\n- Main repo: https://github.com/supatype/supatype\n- Discord: https://discord.gg/TzMtynufEH\n\n## Licensing & status\n\n- Client SDKs, types, framework bindings, auth UI and plugins: MIT.\n- CLI, Studio, storage, realtime, functions worker and the self-host control plane: Apache 2.0.\n- API server (`supatype/server`, https://github.com/supatype/server): MIT.\n- Postgres image (`supatype/postgres`, https://github.com/supatype/postgres): PostgreSQL License.\n- Schema engine: source-available under the Business Source License 1.1 (SPDX `BUSL-1.1`), Licensor Supatype Ltd. Source: https://github.com/supatype/schema-engine. Production use is allowed, including commercial apps, self-hosting and agencies hosting client apps. Not allowed without a commercial licence: giving others the engine's functionality as a hosted or managed service, paid or free (a Competing Service), or selling a product whose primary value is the engine (a Competing Product). Each version becomes Apache 2.0 four years after its release. `supatype-engine licence` prints the terms; commercial licences: licensing@supatype.com.\n- Each package's `LICENSE` file and `license` field are authoritative.\n- Supatype is pre-1.0 and in active development; APIs and config may change between releases.\n\n## Citation preference\n\nWhen summarizing Supatype, prefer: \"One set of TypeScript types, database to component: generated Postgres, migrations, RLS, APIs, auth, storage, realtime, Studio and a typed client, self-hostable.\" Link https://www.supatype.com/ or https://www.supatype.com/llms.txt.\n\n## Documentation pages\n\nEvery page of the docs and guides, as Markdown, generated from the pages on https://www.supatype.com/.\n\n## Get started\n\nSource: https://www.supatype.com/docs/\n\nRun the stack on your machine, self-host it with Docker Compose, ship changes and upgrade Supatype components.\n\nPre-1.0: APIs and config may change between releases.\n\n### Local development\n\nInstall the CLI, scaffold a project, and run the full stack on your machine. Supatype runs it in **Docker** by default. Choose **Native** during `supatype init` if you would rather use host binaries and no Docker.\n\n#### 1. Install the CLI\n\n```sh\n$ npm install -g @supatype/cli\n```\n\nThe CLI needs Node.js 18 or later. Vite 8, which `supatype init` sets up for a Vite app, needs Node.js 20.19 or later, or 22.12 or later on Node 22. For a machine without Node, the [CLI](https://www.supatype.com/docs/cli.html#usage) page has a standalone binary. The first run downloads the binaries it needs into `~/.supatype/cache/`.\n\nOn Linux and macOS you can also use the install script or Homebrew. On Windows, use npm.\n\n```sh\n$ curl -fsSL https://supatype.com/install.sh | bash\n$ brew install supatype/tap/supatype\n```\n\n#### 2. Create a project\n\n```sh\n$ mkdir my-app && cd my-app\n$ supatype init\n```\n\n`supatype init` writes `package.json`, `supatype.config.ts`, a starter schema and `public/`, installs dependencies with your package manager and writes the API keys to `.env`. Run `npm install` or `supatype keys --write` yourself only if you passed `--no-install` or `--no-keys`. Pass `-y` to take every default without being asked.\n\nIt also writes `seed.ts` and an empty `seeds/` for [seeding](https://www.supatype.com/docs/seeding.html). `package.json` lists `@supatype/cli` and `@supatype/types` as dev dependencies, because they run only at build time. The passwords and the JWT secret in `.env` are random for each project.\n\n#### 3. Start the stack\n\n```sh\n$ supatype dev\n```\n\n`supatype dev` applies your schema when it starts, then watches it: each save migrates the database and regenerates the typed client. It keeps running, so use a second terminal for other commands. `supatype push` applies the schema to another database, such as a server you deploy to.\n\nIt stops with its stack when the process that started it exits, as it does on Ctrl+C: a script that is killed, or a cancelled CI job, leaves nothing running. To leave a stack running with nothing attached, use `supatype self-host compose up -d`.\n\nA script that starts `dev` in the background should `exec` it, so the process ID the script holds is `dev` itself and stopping it stops the stack cleanly:\n\n```sh\n(cd my-app && exec npx supatype dev) &\nDEV_PID=$!\n# ... run your tests ...\nkill \"$DEV_PID\"; wait \"$DEV_PID\"\n```\n\nIf `dev` itself is killed (its process ended, or its window closed before it finished stopping), the stack can be left running. The next `supatype dev` finds it and offers to stop it, and `supatype self-host compose down` stops it now.\n\nThe gateway serves REST at `/rest/v1/`, auth at `/auth/v1/`, storage and realtime. With Docker it listens on `http://localhost:<gateway-port>`: init picks a free port per project and writes the URL to `.env` as `API_EXTERNAL_URL` (the port alone is `SUPATYPE_KONG_PORT`). With Native it listens on `http://localhost:18471`, `server.port` in `supatype.config.ts`.\n\nFor direct SQL, Docker publishes Postgres on `127.0.0.1` at `SUPATYPE_DEV_DB_PORT` (54329 unless set), and `dev` points `DATABASE_URL` in `.env` at it. Native Postgres listens on port 5432 and checks passwords: connect as `postgres` with `POSTGRES_PASSWORD` from `.env`, or run `supatype pg psql`, which passes it for you.\n\n#### 4. Sign in to Studio\n\nWhen the stack is up, `supatype dev` prints a **Services running** panel with each address. With Docker, Studio is at `/studio/` on the gateway: `http://localhost:<gateway-port>/studio/`.\n\nIf you asked `init` for an admin, it wrote `SUPATYPE_ADMIN_EMAIL` and `SUPATYPE_ADMIN_PASSWORD` to `.env`. The first `supatype dev` or `supatype push` that finds no Studio admin creates one from them with the `admin` role, then removes the password from `.env`. Sign in with that email and password. To add one later, run `supatype admin create-user --email you@example.com`, which asks for the password.\n\n#### 5. Know what init scaffolded\n\n`schema/index.ts` starts with two models:\n\n- `Profile`: one row per signed-in user, keyed by the auth user id. Any signed-in user can read profiles, and only the owner can create, update or delete theirs.\n- `SiteSettings`: a singleton with a `site_name`, readable by everyone and editable by admins in Studio under Settings.\n\n#### 6. Add a model\n\nAdd a `Post` to `schema/index.ts` and save. The running `supatype dev` migrates the database and regenerates the typed client. There is nothing to push locally.\n\n`schema/index.ts`:\n\n```ts\nimport type { Model, UUID, SupatypeAuthUserId, Slug, Unique, Public, Owner } from \"@supatype/types\"\n\nexport type Post = Model<{\n id: UUID\n title: string\n slug: Unique<Slug<\"title\">>\n body: string\n author_id: SupatypeAuthUserId\n}, {\n access: { read: Public; create: Owner<\"author_id\">; update: Owner<\"author_id\">; delete: Owner<\"author_id\"> }\n}>\n```\n\nMerge the new names into the file's existing `import type` line. The table is `post`. See [Schema](https://www.supatype.com/docs/schema.html) for field types, relations and access rules.\n\nA change that would lose data, such as dropping a column, is never applied silently: `dev` asks first. To rename a column or table rather than drop it, see [Renames](https://www.supatype.com/docs/schema.html#renames).\n\n#### 7. Query it\n\nInstall the client first with `npm install @supatype/client`: the generated file builds on it. Then create the client once, from the generated file, with the URL and key `init` wrote to `.env`:\n\n`src/supatype.ts`:\n\n```ts\nimport { createClient } from \"../supatype/generated/client\"\n\nexport const supatype = createClient({\n url: import.meta.env.VITE_SUPATYPE_URL,\n anonKey: import.meta.env.VITE_SUPATYPE_ANON_KEY,\n})\n```\n\n`src/posts.ts`:\n\n```ts\nimport { supatype } from \"./supatype\"\n\nconst { data: posts, error } = await supatype.from(\"post\").select(\"id, title, slug\")\nif (error) throw new Error(error.message)\n```\n\nThe result is typed from your schema. The [Client](https://www.supatype.com/docs/client.html) page covers filters, writes, auth, storage and realtime.\n\n#### Serve your frontend dev server at `/`\n\nKeep the committed `supatype.config.ts` pointing at your production build, and proxy to Vite or Next from a gitignored `supatype.local.config.ts`:\n\n`supatype.local.config.ts`:\n\n```ts\n// supatype.local.config.ts (your machine only)\nexport default {\n app: { mode: \"proxy\", upstream: \"http://localhost:5173\" },\n}\n```\n\nRestart `supatype dev` after changing config. The APIs stay on their own paths.\n\n### Self-hosting\n\nRun the whole platform on a server you own with Docker Compose. The project layout is the same one you use locally, so the repository you develop in is the one you deploy.\n\n#### 1. Prepare the server\n\nUbuntu 22.04 or similar, Docker with Compose v2, Node.js (18 or later for the CLI, 20.19 or later, or 22.12 or later on Node 22, to build a Vite 8 app), and the CLI:\n\n```sh\n$ npm install -g @supatype/cli\n```\n\n#### 2. Scaffold and set secrets\n\n```sh\n$ mkdir my-app && cd my-app\n$ supatype init\n```\n\n`init` installs dependencies and writes generated secrets and API keys to `.env`. Set your public URLs there.\n\n> **CACHE PASSWORD:** When the cache runs inside Postgres, as it does by default, `supatype/postgres` 17.2.13 and later require a password for it, `SUPATYPE_KEYSPACE_PASSWORD` in `.env`. Every `supatype self-host compose` command writes a random one there when it is missing, and never replaces one you set. The compose file requires it, so `docker compose` run by hand without it stops with `SUPATYPE_KEYSPACE_PASSWORD is missing from .env`. To change it, put the new one in `.env` and run `supatype self-host compose up -d`. Password files, rotation with no restart and a second keyspace for the response cache are in [self-hosting configuration](https://www.supatype.com/docs/self-hosting/configuration.html#cache).\n\n#### 3. Start Compose\n\n```sh\n$ supatype self-host compose up -d\n$ supatype push\n```\n\n`compose up` writes the compose file itself, so there is no separate render step. Once the stack answers, it creates the storage buckets the schema declares and the first admin user, as `supatype dev` does. The gateway listens on `http://<your-host>:<gateway-port>`, the port in `SUPATYPE_KONG_PORT` in `.env` (18473 when it is unset), with Studio at `/studio/`. For HTTPS on your own domain, see step 5: the gateway serves it itself, with no reverse proxy.\n\n> **REST BEFORE THE FIRST PUSH:** Until the first `supatype push`, every REST request answers `503` with `PGRST002`: PostgREST will not serve until the schemas it exposes exist, and the push creates them. After a push PostgREST can take up to about 30 seconds to notice, so `push` waits (at most 40 seconds) until REST answers, printing one line while it does.\n\n> **ALLOWED ORIGINS:** Browsers may call the API from the origin of `SITE_URL` and from the origins in `api.corsOrigins` (`supatype.config.ts`) or `SUPATYPE_CORS_ALLOW_ORIGINS` (`.env`). Any other origin is refused. Owners, admins and developers can change the list in Studio, on the Settings page's CORS tab: a saved list is kept in the database and replaces the default until it is reset. The site URL stays allowed whatever is saved. `*` allows every origin, and only when you write it.\n\n> **PORTS:** Only the gateway is published on every interface, at `SUPATYPE_KONG_PORT`, or on ports 80 and 443 once HTTPS is on. Postgres (`SUPATYPE_DB_PORT`, default 5432), the API server (`SUPATYPE_SERVER_PORT`, default 9999) and SeaweedFS (`SUPATYPE_SEAWEEDFS_PORT`, default 8333, when the stack runs one) bind `127.0.0.1`, so they are reachable from the server itself and nowhere else. To reach them from other machines, set `SUPATYPE_PUBLISH_ADDRESS=0.0.0.0` (or one interface's address) in `.env` and run `supatype self-host compose up -d`. Put a firewall in front first. `supatype init` lists these variables, commented out, in `.env`.\n\nImages come from Docker Hub, and each CLI release runs the exact images it was tested with, never `:latest`: `supatype/studio`, `supatype/storage`, `supatype/realtime`, `supatype/functions-worker` and `supatype/control-plane` at the CLI's own version, and `supatype/schema-engine`, `supatype/server` and `supatype/postgres` at the releases pinned for it. The stack also runs `postgrest/postgrest`, `kong` and SeaweedFS, and Valkey when the cache does not run inside Postgres. Upgrading the CLI moves them; `supatype update` pulls the new tags. To run another image, set its `SUPATYPE_*_IMAGE` in `.env` (for example `SUPATYPE_SERVER_IMAGE=supatype/server:v2.3.0`), or pin `versions.engine`, `versions.server` or `versions.postgres` in `supatype.config.ts`.\n\nTo run on a Postgres you already have, such as RDS or Cloud SQL, set `database: { external: { url: process.env.DATABASE_URL! } }` in `supatype.config.ts`. The stack then starts no `db` service, and every service connects there. It needs Postgres 17 or later. Field-level access rules are enforced through generated views instead of the planner rewrite in `supatype/postgres`. Realtime needs `wal_level = logical`, a free replication slot, the `wal2json` plugin and a role with `REPLICATION`. `supatype db check --connection \"$DATABASE_URL\"` reports what a database lacks, and `--emit` prints the SQL that fixes what it can.\n\nEvery function is handed two addresses. `ctx.url` is for calling the API from inside the function. Under Docker it is `http://kong:8100`, which no browser can open. `ctx.publicUrl` is the project's public address, `API_EXTERNAL_URL` in `.env`, for links you give to people.\n\nFunctions get no database connection by default. Setting `SUPATYPE_FUNCTIONS_DB_URL` in `.env` hands every function that URL as `ctx.dbUrl`: a raw Postgres connection as whichever role it names. Row rules and field masking apply for that role exactly as they would for a request: a superuser or a role with `BYPASSRLS` (the admin role, `service_role`) skips both, any other role is held to them. Point it at a least-privilege login role that is neither, granted only what your functions need, never the admin URL, for example `postgresql://functions_reader:<password>@db:5432/<POSTGRES_DB>`. The database is the value of `POSTGRES_DB` in your `.env` (`supatype init` sets it to the project name; the stack default is `supatype`).\n\n#### 4. Serve a static app\n\n```sh\n$ supatype app add --static ./public\n```\n\nThis writes `app.mode: \"static\"` to `supatype.config.ts`. Commit it. It is a one-time step, not something to repeat on the server.\n\nOn the server, build the app with `supatype build` rather than `npm run build`. It runs the same build script with the API URL and anon key from `.env`, and stops before building when either is missing. [Deploy your frontend](https://www.supatype.com/docs/deploying-your-frontend.html) covers building on other hosts.\n\n#### 5. Turn on HTTPS\n\nPoint an A record for your domain at the server and open ports 80 and 443. Then:\n\n```sh\n$ supatype add domain example.com --email you@example.com\n$ supatype self-host compose up -d\n```\n\n`add domain` sets `server.mode: \"standalone\"`, `server.domain` and `server.tls` in `supatype.config.ts`. Commit it. On the next `compose up` the gateway listens on ports 80 and 443 instead of `SUPATYPE_KONG_PORT`, and gets and renews a Let's Encrypt certificate for the domain itself, accepting Let's Encrypt's terms under the email you gave. The app, the APIs and Studio all share the one domain.\n\nSet `API_EXTERNAL_URL` and `SITE_URL` in `.env` to `https://example.com`: values in `.env` win over the HTTPS default. Certificates are kept in the stack's key-value store (the `valkey-data` volume, or the database when the cache is `pg_keyspace`), so they survive restarts. Port 80 also still answers plain HTTP: nothing redirects it to HTTPS.\n\n`supatype dev` never turns HTTPS on, so the same committed config still runs on `http://localhost`.\n\n> **RATHER NOT RUN IT YOURSELF?:** Supatype Cloud runs the same stack for you, and it is in closed beta. [Request access](https://www.supatype.com/#cloud), or [book a call](https://www.supatype.com/#contact) about self-hosting with support.\n\n### Deploy changes\n\nLocal and self-hosted environments read the same committed config. What differs between machines lives in files you do not commit.\n\n#### Which file holds what\n\n| File | Holds | Commit |\n| --- | --- | --- |\n| `supatype.config.ts` | Schema path, app routing, version pins | Yes |\n| `supatype.local.config.ts` | Overrides for your machine, such as the dev proxy | No |\n| `supatype/renames.json` | Renames recorded with `supatype rename` | Yes |\n| `.env` | `DATABASE_URL`, JWT keys, `API_EXTERNAL_URL` | No |\n\n#### What to run when something changes\n\n| Change | Local | Self-hosted |\n| --- | --- | --- |\n| Schema | `supatype push` | `supatype push` |\n| Frontend | Nothing with the dev proxy. Otherwise `npm run build` | `supatype build`, then `compose up -d` |\n| `supatype.config.ts` | Restart `supatype dev` | `compose up -d` |\n| `.env` | Restart `supatype dev` | `compose up -d`, or `compose restart <service>` for one service |\n\n> **ONE SERVICE:** `supatype self-host compose restart server` recreates just that service with the current config and `.env`. Use it rather than typing a `docker compose` command yourself: the CLI renders the compose file first, so it always names this project's folders where they are now.\n\n#### A typical server deploy\n\n```sh\n$ cd my-app\n$ git pull\n$ npm install # if package.json changed\n$ supatype push # schema migrations\n$ supatype build # the build script, with .env's API URL and anon key\n$ supatype self-host compose up -d\n```\n\n> **NOTE:** `DATABASE_URL` in `.env` belongs to `supatype dev`. Self-host commands such as `push`, `seed` and `admin` connect to the Compose Postgres on `SUPATYPE_DB_PORT` (5432 unless you set it) for their own run, without rewriting it, so they use the same database as the stack.\n\n### Upgrading Supatype\n\nMoving to newer Supatype components is separate from deploying your own changes. It takes four commands.\n\n```sh\n$ npm install -g @supatype/cli@latest # or supatype self-update\n$ supatype update # pull the new images\n$ supatype self-host compose up -d # run them\n$ supatype push # apply the schema they expect\n```\n\n`supatype update` never updates the CLI itself, so update it first. The image pins come from the CLI version, so under Docker it looks up the latest CLI release and, when yours is behind, prints the upgrade command for how you installed it before carrying on. `supatype update --check` reports the running and latest versions without pulling, and the check is skipped with a warning when offline or on a CLI built from source. Under Docker, `update` renders the compose file and pulls the images. It does not restart anything, which is why `compose up -d` follows.\n\nThe push is the step that is easy to miss. Grants, policies, functions and buckets are generated from your schema and only reach the database through `push`, so new images on an older database can refuse rules until it runs. The upgrade is finished after the push, not before.\n\n> **403S AFTER AN UPGRADE:** This is the usual cause. The storage service logs the reason and names `supatype push` as the fix.\n\n> **0.7.0:** Upgrading from 0.6.0? Deploy the new realtime image before the first push, and upgrade the CLI with the engine. The [upgrade notes](https://github.com/supatype/supatype/blob/main/UPGRADING.md) cover ownership checks, declared renames, identity columns and the rest. CORS changed too: outside dev, only the origin of `SITE_URL` and the origins you list are allowed. If your app is served from another origin, add it to `api.corsOrigins` before you upgrade.\n\n### Running in production\n\nA self-hosted stack is a Compose project, so you run it with the CLI and standard Postgres tools. Run these in the project directory on the server.\n\n#### Health and logs\n\n```sh\n$ supatype status # each service and whether it is running\n$ supatype self-host compose status # Compose's own view, with health\n$ supatype logs --service server --since 1h\n$ supatype self-host compose logs # every service, followed\n```\n\n`supatype logs` shows up to 100 lines per service from the past 5 minutes (`--since` changes that), then keeps following until you press Ctrl+C. Ask for a service that does not exist and it lists the ones that do. Postgres has a health check, and the services that use it wait until it passes.\n\n> **AFTER A REBOOT:** The generated Compose file sets no restart policy except on `server`, which retries a failed start five times. Docker does not bring the stack back after the server reboots, so run `supatype self-host compose up -d` again, or from a boot-time unit of your own.\n\n#### Backups\n\nThere is no backup command for a Compose stack. Use `pg_dump` 17 or later on the server, against `DATABASE_URL` from `.env`, which reaches the Compose Postgres on `127.0.0.1`. The dump holds every schema, including auth users, storage metadata and migration history.\n\n```sh\n$ export DATABASE_URL=\"$(grep '^DATABASE_URL=' .env | cut -d= -f2-)\"\n$ pg_dump -Fc -f backup-$(date +%F).dump \"$DATABASE_URL\"\n$ pg_restore --clean --if-exists -d \"$DATABASE_URL\" backup-2026-10-28.dump\n```\n\nStored files are not in the database. With the built-in storage they live in the `storage-data` volume, named `supatype-<project>_storage-data` in `docker volume ls`. Back that up with your usual volume tooling. `supatype self-host compose down` keeps both volumes, and only `down --volumes` deletes them.\n\n#### Roll back a bad push\n\n```sh\n$ supatype migrations list # what was applied, when and by whom\n$ supatype rollback # undo the last applied migration\n```\n\n`rollback` runs the reverse SQL stored with the last migration in one transaction and marks it rolled back. It then offers to restore your schema files from the snapshot stored with the migration before it, so the next push does not apply the change again. Pass `--sync-schema` to restore without asking, or `--no-sync-schema` to revert the database only. Commit the restored files.\n\n> **DROPPED DATA:** A rollback cannot bring back a table or column the push dropped, or data a type change discarded. Restore those from a backup. Run `supatype diff` before a push to see what it will change.\n\n## Schema\n\nSource: https://www.supatype.com/docs/schema.html\n\nYour schema is a set of TypeScript types in `schema/index.ts`. Supatype builds the tables, access rules, APIs and the typed client from it.\n\nPre-1.0: APIs and config may change between releases.\n\n### Models\n\nEach exported `Model<>` type is a table. Import the types from `@supatype/types`.\n\nNothing in `schema/index.ts` runs. The CLI reads it as type declarations, so a model is an `export type`, never an `export const`, and there is no builder function to call.\n\n`schema/index.ts`:\n\n```ts\nimport type { Model, UUID, Optional, Public, LoggedIn } from \"@supatype/types\"\n\nexport type Post = Model<{\n id: UUID\n title: string\n published: boolean\n published_at: Optional<string>\n}, {\n access: { read: Public; create: LoggedIn; update: LoggedIn; delete: LoggedIn }\n}>\n```\n\nThe table name is the type name in snake case: `Post` becomes `post`, `BlogPost` becomes `blog_post`. Set `tableName` in the second argument to choose another.\n\nAn `id: UUID` field becomes the primary key, and the database fills it in. A model with no `id` field and no `PrimaryKey<>` gets one anyway: an `id UUID` primary key filled by `gen_random_uuid()`. Wrap another field in `PrimaryKey<>` to key the model by it instead.\n\nA key you type yourself, such as `slug: PrimaryKey<string>`, is fixed forever. It can never be changed, by Studio, the API or anything else, because drafts, relations and URLs all point at it. To let editors rename a record, keep the hidden `id` and add a unique lookup field: `id: UUID` and `slug: Unique<Slug<\"title\">>`. A push that would create a new model with a typed key is refused, with a message naming the model, unless the key is wrapped in `NaturalKey<>`. Use `NaturalKey<>` only for a value that truly never changes, such as an ISO country code. A model already in the database is left as it is. On an empty database, such as a fresh environment or CI, an existing model with `PrimaryKey<string>` counts as new: change it to `NaturalKey<string>`, which changes nothing in the database.\n\nThe second argument also takes these options:\n\n| Option | Does |\n| --- | --- |\n| `label`, `labelPlural` | Names the model in Studio |\n| `indexes` | Adds indexes, see below |\n| `versions` | Keeps drafts and history, see [below](https://www.supatype.com/docs/schema.html#drafts) |\n| `singleton: true` | Keeps one row, such as site settings. The table is `_global_` plus the snake case name, unless you set `tableName` |\n| `constraints` | Checks the database runs on every write, in the access rule language, such as `Lte<\"starts_at\", \"ends_at\">`. They cannot name the caller or the clock |\n| `searchable` | The fields the search box in Studio's list looks in |\n| `timestamps`, `softDelete` | Adds `created_at` and `updated_at` columns, or a `deleted_at` column. Left out, they follow the fields the model declares |\n| `autoLocalize: true` | Makes copy fields localized by default. Wrap one in `NotLocalized<>` to opt out |\n| `hooks`, `validate` | Runs an edge function before or after an API write, or to check one field. They do not run for direct SQL or seeds |\n| `cache` | Says how reads of the model may be cached |\n\nAn index is `{ fields: [\"a\", \"b\"] }`, with `unique: true` and `name` if you need them. `using` picks the method: `\"btree\"` (the default), `\"gin\"`, `\"gist\"`, `\"hnsw\"` or `\"brin\"`. An `\"hnsw\"` index is for `Vector` fields only. Its `distance` is `\"cosine\"` (the default), `\"l2\"` or `\"innerProduct\"`. A `distance` on any other index is refused.\n\n`supatype dev` applies each save. `supatype push` applies the schema to another database. `supatype diff` shows the change without applying it.\n\n### Field types\n\nEvery field is required (`NOT NULL`) unless you wrap it in `Optional<>`. Use `Optional<>`, not `?`.\n\n| Write | Stores |\n| --- | --- |\n| `string` | text |\n| `number`, `Float` | a floating point number |\n| `Int`, `SmallInt`, `BigInt`, `Decimal<10, 2>`, `Money` | exact numbers |\n| `boolean` | true or false |\n| `Timestamp`, `DateTime`, `DateOnly` | a time with zone, or a date |\n| `UUID` | a Postgres `uuid` |\n| `Email`, `URL`, `Color`, `PhoneNumber`, `Markdown` | text. The database checks the format of `Email` and `URL` |\n| `\"news\" \\| \"guide\"` | text limited to those values by a check |\n| `string[]` | an array |\n| `JSON<T>` | JSONB, typed as `T` in the client |\n| `Code`, `Currency`, `Duration`, `Button` | JSONB with a typed shape, such as `{ amount, code }` for `Currency` |\n| `Vector<1536>` | a pgvector embedding with that many dimensions |\n| `GeoPoint`, `Geo` | a PostGIS `geography` point |\n| `IPAddress`, `CIDR`, `MacAddress`, `Bytea`, `XML`, `TSVector`, `TSQuery` | the matching Postgres type: `inet`, `cidr`, `macaddr`, `bytea`, `xml`, `tsvector`, `tsquery` |\n| `RichText`, `Blocks<T>`, `Slug<\"title\">` | content fields, see [below](https://www.supatype.com/docs/schema.html#content) |\n| `ImageAsset<Bucket>`, `FileAsset` | a file in a storage bucket |\n| `SupatypeAuthUserId` | the id of a sign-in user, see [below](https://www.supatype.com/docs/schema.html#owners) |\n\nWrap a field to add more:\n\n| Wrap | Does |\n| --- | --- |\n| `Unique<T>`, `Indexed<T>` | Adds a unique constraint, or an index |\n| `Default<T, value>` | Sets the column's default |\n| `ServerDefault<T>` | Says the database fills the column, by a trigger or default. Inserts may leave it out |\n| `MinLength<T, n>`, `MaxLength<T, n>` | Bounds the length of text |\n| `MinItems<T, n>`, `MaxItems<T, n>` | Bounds how many items an array, JSON array or `Blocks` field holds |\n| `Between<T, min, max>` | Bounds a number or a date |\n| `Searchable<T>` | Adds the field to the search box in Studio's list |\n| `Localized<T>` | Stores one value per locale, such as `{ \"en\": \"Hello\", \"de\": \"Hallo\" }` |\n\nThree wrappers shape a field in Studio. `EditorReadOnly<T>` is shown but not editable there, and the API can still write it. `Computed<T>` is filled by the database and read-only in Studio. `ComputedFrom<string, \"title\">` is prefilled from the fields it names on a new record, until the editor changes it.\n\nFor translated content, declare the locales once, such as `export type Locales = LocaleConfig<[\"en\", \"fr\"], \"en\">`, and wrap a field in `Localized<T>`. It is stored as JSONB keyed by locale: `{ \"en\": \"Hello\", \"fr\": \"Bonjour\" }`. `LocalizedModel<>` localizes a model's text fields for you, and `NotLocalized<T>` opts one back out. There is no locale setting in `supatype.config.ts`.\n\nWrap the fields in `WithTimestamps<{ ... }>` to add `created_at` and `updated_at`, which the database fills in.\n\nWith the Native provider, `supatype dev` stores `Vector<>` and `Geo` fields as JSONB, because its Postgres has no pgvector or PostGIS. Use Docker to work with them locally.\n\n### Identity and generated columns\n\nAn integer field can be an identity column. `Int<{ identity: \"always\" }>`, or `Identity<number>`, is `GENERATED ALWAYS AS IDENTITY`. An insert cannot give it a value. `BigInt<{ identity: \"by-default\" }>`, or `Identity<bigint, \"by-default\">`, takes a value when an insert gives one.\n\n`AutoIncrement<number>` is `Identity<number, \"by-default\">`. Before 0.7.0 it was a `SERIAL`. A serial column pushed then is left as it is.\n\n`Generated<T, \"sql\">` is a stored generated column, such as `Generated<string, \"lower(name)\">`. Most types also take it as an option: `Float<{ generated: \"price * quantity\" }>`.\n\n`schema/index.ts`:\n\n```ts\nimport type { Model, PrimaryKey, Int, Float, Generated } from \"@supatype/types\"\n\nexport type LineItem = Model<{\n id: PrimaryKey<Int<{ identity: \"always\" }>>\n price: Float\n quantity: Int\n total: Generated<Float, \"price * quantity\">\n}>\n```\n\nA column cannot be both. Neither takes a `Default<>`. The generated client leaves generated columns and `\"always\"` identities out of inserts and updates. A `\"by-default\"` identity is optional on insert. Removing either is destructive, so the push asks first or needs `--yes`.\n\n### Relations\n\n`RelatedTo<Model>` adds a foreign key column named after the field plus `_id`. The field `author` becomes the column `author_id`. The column can be null unless you pass `{ required: true }`.\n\n`onDelete` takes `\"cascade\"`, `\"setNull\"`, `\"restrict\"` or `\"noAction\"`. It defaults to `\"restrict\"`: deleting an author with posts is refused. `onUpdate` takes the same values and defaults to `\"cascade\"`.\n\n`HasMany<Model>` and `HasOne<Model>` are the other side of a `RelatedTo`. They add no column. They let the client and seeds reach the related rows.\n\n`ManyToMany<Model>` makes one junction table for the pair, whichever side declares it. It is named from both tables in alphabetical order, so posts and tags share `post_tag`. Pass `{ through: \"name\" }` to choose the name.\n\n`schema/index.ts`:\n\n```ts\nimport type {\n Model, UUID, SupatypeAuthUserId, Timestamp, RichText, Slug, Unique, Optional, Int,\n RelatedTo, HasMany, ManyToMany, Owner, Role, LoggedIn, Public, Any, Lte, Now,\n Bucket, BucketPublic, BucketLoggedIn, BucketOwner, ImageAsset, Block, Blocks, Default,\n} from \"@supatype/types\"\n\nexport type Author = Model<{\n id: SupatypeAuthUserId\n name: string\n bio: Optional<string>\n posts: HasMany<Post>\n}, {\n access: { read: Public; create: Owner<\"id\">; update: Owner<\"id\">; delete: Owner<\"id\"> }\n}>\n\nexport type Tag = Model<{\n id: UUID\n name: Unique<string>\n}, {\n access: { read: Public; create: Role<\"admin\">; update: Role<\"admin\">; delete: Role<\"admin\"> }\n}>\n\nexport type Post = Model<{\n id: UUID\n title: string\n slug: Unique<Slug<\"title\">>\n body: RichText\n sections: Optional<Blocks<HeroBlock | ProseBlock>>\n kind: \"news\" | \"guide\"\n cover: Optional<ImageAsset<Covers>>\n author: RelatedTo<Author, { required: true; onDelete: \"cascade\" }>\n tags: ManyToMany<Tag>\n comments: HasMany<Comment>\n views: Default<Int, 0>\n published_at: Optional<Timestamp>\n}, {\n versions: { drafts: true }\n access: {\n read: Any<[Lte<\"published_at\", Now>, Owner<\"author_id\">]>\n create: Owner<\"author_id\">\n update: Owner<\"author_id\">\n delete: Any<[Owner<\"author_id\">, Role<\"admin\">]>\n }\n}>\n\nexport type Comment = Model<{\n id: UUID\n post: RelatedTo<Post, { required: true; onDelete: \"cascade\" }>\n user_id: SupatypeAuthUserId<{ onDelete: \"cascade\" }>\n body: string\n}, {\n access: { read: Public; create: Owner<\"user_id\">; update: Owner<\"user_id\">; delete: Owner<\"user_id\"> }\n}>\n```\n\nThe other pages use this schema in their examples. `HeroBlock`, `ProseBlock` and `Covers` are defined further down.\n\n### Access rules\n\nEach model has a rule for `read`, `create`, `update` and `delete`. The rules become Postgres row level security, so they hold for REST, GraphQL, realtime and the client alike.\n\nAn operation with no rule is denied. A model with no `access` at all is not reachable through the API.\n\n| Rule | Who passes |\n| --- | --- |\n| `Public` | Everyone, signed in or not |\n| `LoggedIn` | Any signed-in user |\n| `Private` | Nobody through the API |\n| `Owner<\"author_id\">` | The user whose id is in that column. Use `\"id\"`, a `SupatypeAuthUserId` field, or a relation's `_id` column. `Owner<Post, \"author_id\">` also names the model, so the editor checks the field |\n| `OwnerFrom<\"post\">` | The owner of the related row, one relation deep |\n| `Role<\"admin\">` | A user whose `app_metadata.role` is `admin` |\n| `Any<[A, B]>`, `All<[A, B]>`, `Not<A>` | Either rule, both rules, or the opposite |\n| `Eq`, `Neq`, `Gt`, `Gte`, `Lt`, `Lte`, `Like` | A comparison, such as `Lte<\"published_at\", Now>` |\n| `In<\"site_id\", Rows<\"user_sites\", \"site_id\", Eq<\"user_id\", AuthUid>>>` | The column's value is in the set: rows of another table, `Values<[\"draft\", \"review\"]>`, or a claim holding an array |\n| `Exists<Rows<...>>` | The set is not empty, whatever the row holds |\n\nIn a comparison, a plain string names a column. Wrap a constant in `Literal<>`. `Now`, `AuthUid` and `Claim<\"app_metadata.plan\">` are also available. `IsNull<\"col\">` and `NotNull<\"col\">` test for null.\n\nA time can be relative to now. `Ago<30, \"days\">` and `FromNow<7, \"days\">` take one amount and one unit. `StartOf<\"day\">` is the start of the day, week, month or year. `After<Now, { days: 30 }>` and `Before<StartOf<\"day\">, { hours: 9 }>` add or take away several units at once. So `Gte<\"created_at\", Ago<30, \"days\">>` passes rows from the last 30 days.\n\nSince 0.7.0 a push refuses an owner rule that could never match. An `Owner` on a relation must reach, through one relation at most, a model keyed by a `SupatypeAuthUserId` or one with its own `Owner` rule. On a plain `UUID` field it still works, with a warning.\n\n`Role<>` reads the user's `app_metadata.role`, which only the auth admin API can set. It is not the Studio role.\n\n### Field rules and masking\n\nA field rule limits who can read or write one column. Declare it under `access.fields`.\n\n`schema/index.ts`:\n\n```ts\nexport type Profile = Model<{\n id: SupatypeAuthUserId\n display_name: string\n email: string\n}, {\n access: {\n read: Public\n create: Owner<\"id\">\n update: Owner<\"id\">\n delete: Owner<\"id\">\n fields: { email: { read: Any<[Owner<\"id\">, Role<\"moderator\">]>; write: Owner<\"id\"> } }\n }\n}>\n```\n\nA caller who may not read the column still gets the row, with the value masked as `null`. A write the rule refuses fails with error `42501`.\n\nName a relation by its column, such as `author_id`.\n\n> **NOT WITH VERSIONS:** A model with `versions` cannot have field rules. Old versions are stored as JSON snapshots, where a column rule cannot be enforced. The schema is refused and the message asks you to drop one of the two.\n\n### Auth user ids\n\n`SupatypeAuthUserId` holds the id of a sign-in user. Use it for owner columns.\n\nWhen the `create` rule is `Owner<\"col\">` and the column has no default, the column defaults to the caller's own user id. So a client can leave it out on insert.\n\nBy default there is no foreign key to the user. Deleting a user leaves their rows as they were. Add `onDelete` to get one:\n\n| `onDelete` | When the user is deleted |\n| --- | --- |\n| `\"cascade\"` | Their rows are deleted too |\n| `\"restrict\"` | Deleting the user is refused while they own rows |\n| `\"setNull\"` | The column is set to null. The field must be `Optional<>` |\n\nThe push that adds the key refuses if existing rows name a user that does not exist. Its message says how many rows and how to remove them. It also refuses if the database has no `auth.users` table, which Supatype's auth server creates. Start the auth server against the database once, or remove `onDelete` so the field holds an id with no foreign key.\n\n### Drafts and versions\n\n`versions: { drafts: true }` keeps drafts and a history of each record. `versions: true` is short for the same. `keep` sets how many versions to keep (default 20).\n\nThe model's own table holds the published record. That is what `read` rules and the public API see. Drafts and old versions live in `post_versions`.\n\nPublishing copies a draft into the live table. It also sets `published_at` if it is empty. The `update` rule decides who may publish.\n\nA direct API update of the live row is refused with error `42501`. Save a draft with the client's `update`, then publish, or pass `{ publish: true }` to do both. See [Client](https://www.supatype.com/docs/client.html#drafts).\n\n`versions: { drafts: false }` keeps history only. Writes go straight to the live row.\n\nThe `read` rule does not decide who sees a draft. The record's creator sees it. So do the Studio roles in `publishing.draft_visibility` in `supatype.config.ts` (default admin, developer and editor), and anyone with a signed preview link.\n\n### Slugs, rich text and blocks\n\n`Slug<\"title\">` fills itself from `title` when you leave it empty. While it still holds the generated value, it follows the title when the title changes. Set it yourself to keep a URL fixed. Add `Unique<>` if it must be unique.\n\n`RichText` stores a rich text document. When you write, a plain string is accepted and becomes one paragraph. A read always returns the document.\n\n`Blocks<T>` is a list of sections an editor arranges in Studio. Each block is `Block<\"name\", { fields }>`:\n\n`schema/index.ts`:\n\n```ts\nexport type HeroBlock = Block<\"hero\", { heading: string; image: Optional<ImageAsset<Covers>> }>\nexport type ProseBlock = Block<\"prose\", { body: RichText }>\n```\n\nEach entry is stored as `{ \"type\": \"hero\", \"data\": { \"heading\": \"Hi\" } }`. A renderer switches on `type` and reads `data`. Rich text inside a block is not converted from a string, so write the full document there.\n\nA third argument, `{ label, icon }`, sets how Studio shows the block, such as `Block<\"hero\", { heading: string }, { label: \"Hero banner\" }>`. Both are optional.\n\nBefore 0.7.0 a block's fields sat beside `type`. `supatype push` moves entries stored that way under `data`, and `supatype diff` shows how many are pending. Push before anyone opens those records in Studio. See [Upgrading](https://www.supatype.com/docs/#upgrading).\n\n### Storage buckets\n\n`schema/index.ts`:\n\n```ts\nexport type Covers = Bucket<\"covers\", {\n accessMode: \"public\"\n accept: [\"image/png\", \"image/jpeg\", \"image/webp\"]\n maxSize: \"5MB\"\n access: { read: BucketPublic; create: BucketLoggedIn; update: BucketOwner; delete: BucketOwner }\n}>\n```\n\nA bucket has the same four rules as a model. `update` means overwriting a file. The rules are `BucketPublic`, `BucketLoggedIn`, `BucketOwner` (the uploader), `BucketRole<\"name\">` and `BucketPrivate`.\n\nA rule you leave out is refused for everyone but the service role, and the push warns about it. `accessMode: \"public\"` serves files on a public URL whatever `read` says.\n\n`ImageAsset<Covers>` on a model stores a reference to a file in that bucket.\n\n### Renames\n\nA push never guesses a rename. Renaming a field in the schema looks like a drop and an add.\n\nIn a terminal, `supatype push` and `supatype dev` ask, for example \"Was post.title renamed to post.headline? (recorded in supatype/renames.json)\". Answer yes and it records the rename. Without a terminal the push stops and prints the `supatype rename` command to run.\n\n```sh\n$ supatype rename post.title post.headline # a column\n$ supatype rename post article # a table\n```\n\nRenames are recorded in `supatype/renames.json`. Commit it. Every push replays it, so each database gets the same rename. `supatype rename --prune` removes entries the target database has already applied. Point it at a database with `--connection`, `--env` or `--direct`, as for a push.\n\n> **CAREFUL:** `supatype push --yes` does not ask about renames. An unrecorded rename is then pushed as a drop and an add, and the column's data is lost. Record renames first.\n\n### What a push refuses\n\n| Push stops when | To go on |\n| --- | --- |\n| A change can lose data, such as a drop | Answer yes in a terminal, or pass `--yes` in CI |\n| A table the schema names exists but Supatype did not create it | `supatype adopt`, or give the model another `tableName`. The push offers to adopt in a terminal |\n| A change rewrites or scans a table of more than 100,000 rows, which locks it while it runs | Answer yes in a terminal, or pass `--yes` |\n| Policies, grants, labels or row level security were changed outside Supatype | `--overwrite-drift` puts Supatype's back. To keep the hand edits, run `supatype doctor --rebaseline --accept-access-drift` |\n| A versioned model has field rules | Remove one of the two |\n| An `onDelete` key would point at missing users | Delete or fix those rows |\n| An `onDelete` key needs `auth.users` and the database has none | Start the auth server against the database once, or remove `onDelete` |\n| The schema has identity or generated columns and the engine is older than 0.7.0 | Run `supatype update` |\n| A `JSON` field changed to `Blocks` holds values that are not objects | Change or remove those values, then push again |\n\n`--yes` does not override hand-edited access rules. Only `--overwrite-drift` does. Objects that Supatype did not create are never dropped or taken over.\n\n### Server logic in a Postgres function\n\nThe schema declares tables and [access rules](https://www.supatype.com/docs/schema.html#access). It has no place for your own SQL, so logic that must run as one step in the database, such as checking a price and raising it in one transaction, is a Postgres function that you create yourself and call with `supatype.rpc()`. \"No raw SQL\" means the access rules are typed, not that the database is closed to you.\n\n`place_bid.sql`:\n\n```sql\nCREATE FUNCTION public.place_bid(lot_id uuid, amount numeric)\nRETURNS public.lot\nLANGUAGE plpgsql\nSECURITY INVOKER\nSET search_path = ''\nAS $$\nDECLARE\n current_lot public.lot;\nBEGIN\n -- Lock the row, so two bids at once are checked one after the other.\n SELECT * INTO current_lot FROM public.lot WHERE id = lot_id FOR UPDATE;\n IF NOT FOUND THEN\n RAISE EXCEPTION 'no such lot';\n END IF;\n IF amount <= current_lot.price THEN\n RAISE EXCEPTION 'bid must be above %', current_lot.price;\n END IF;\n UPDATE public.lot SET price = amount WHERE id = lot_id RETURNING * INTO current_lot;\n RETURN current_lot;\nEND;\n$$;\n\nGRANT EXECUTE ON FUNCTION public.place_bid(uuid, numeric) TO authenticated;\nNOTIFY pgrst, 'reload schema';\n```\n\n- **Lock what you check.** `SELECT ... FOR UPDATE` makes a second caller wait until the first transaction ends, so the check and the update cannot interleave.\n- **`SECURITY INVOKER` or `DEFINER`.** An invoker function runs as the caller, so the [row rules](https://www.supatype.com/docs/schema.html#access) and [field masking](https://www.supatype.com/docs/schema.html#field-rules) on every table it touches apply as they would for a request. That is the default, and the one to use. A definer function runs as the role that created it, which skips both, so it must do its own checks (for example against `auth.uid()`) and should be written with great care.\n- **`SET search_path = ''`.** It stops a caller shadowing a table or function with one of their own. Name every object with its schema, as above. It matters most for a definer function.\n- **Grant it.** The API roles can call only what you grant: `GRANT EXECUTE ... TO authenticated`, or `anon` for a signed-out caller.\n- **Create it.** Run the SQL with `psql` against your database, or in Studio's [SQL runner](https://www.supatype.com/docs/studio.html#sql). `NOTIFY pgrst, 'reload schema'` makes the API pick the function up straight away.\n- **Call it.** `rpc` sends the named arguments, and a `RAISE EXCEPTION` comes back as `error`.\n\n`typescript`:\n\n```ts\nconst { data: lot, error } = await supatype.rpc(\"place_bid\", { lot_id: lotId, amount: 120 })\n```\n\n> **NOT MANAGED:** Supatype does not manage this function. A push neither applies it nor changes or drops it: it leaves a function it did not make alone. But nothing else carries it either. `supatype dev --reset-db` removes the database volume and the function with it. A new environment does not get it, so run the SQL again there, or keep it in a file your own deploy step applies. On Supatype Cloud, run it in each environment's SQL runner. It is not in the schema, so it is not in the generated types: `rpc` takes the name and arguments you give it. Managed functions are planned for after the beta.\n\n#### Run a function on a schedule\n\nThe image ships `pg_cron`, so a Postgres function can run on a timer. Write the function as above (here, one that closes every lot whose end time has passed), then schedule it by hand.\n\n```sh\n$ psql \"$DATABASE_URL\"\n\nSELECT cron.schedule('close-lots', '* * * * *', $$SELECT public.close_ended_lots()$$);\nSELECT jobid, jobname, schedule, command, username, database FROM cron.job;\nSELECT status, return_message, start_time FROM cron.job_run_details ORDER BY runid DESC LIMIT 5;\nSELECT cron.unschedule('close-lots');\n```\n\n- **Where it runs.** In your project's database, the one named by `POSTGRES_DB`, as the role that called `cron.schedule`. With the admin URL that role is `supatype_admin`, a superuser, so the job is not held to row rules and field masking, and the function should do its own checks.\n- **Who can schedule.** The admin role can. Studio's SQL runner connects as `supatype_sql_editor`, which has no access to the `cron` schema: `cron.schedule` there fails with `permission denied for schema cron`. Use `psql` with the admin URL.\n- **List and remove.** `cron.job` lists the jobs, `cron.job_run_details` says whether each run succeeded, and `cron.unschedule('name')` removes one.\n\n> **NOT MANAGED:** The job is not in the schema. A push does not apply it, `supatype dev --reset-db` removes it with the database volume, and a new environment does not get it: schedule it in each environment by hand. Declared jobs are planned for after the beta. This was run against the `supatype/postgres` image a release pins; Supatype Cloud databases have not been checked.\n\nThe same pattern serves a query the REST filters cannot express. The [geography example](https://www.supatype.com/docs/schema/fields.html) adds a `places_within` function the same way.\n\n## Client\n\nSource: https://www.supatype.com/docs/client.html\n\n`@supatype/client` talks to your project's REST, auth, storage, realtime and functions. Its types come from your schema, so a wrong table or column fails the build.\n\nPre-1.0: APIs and config may change between releases.\n\n### Create the client\n\nImport `createClient` from the client file the CLI generates, not from `@supatype/client` directly. The generated file tells the client which models keep drafts.\n\n`src/supatype.ts`:\n\n```ts\nimport { createClient } from \"../supatype/generated/client\"\n\nexport const supatype = createClient({\n url: import.meta.env.VITE_SUPATYPE_URL,\n anonKey: import.meta.env.VITE_SUPATYPE_ANON_KEY,\n})\n```\n\nEvery page in these docs imports the client from this one file. In development, `supatype init`, `supatype dev` and `supatype keys` write the local stack's `VITE_SUPATYPE_URL` and `VITE_SUPATYPE_ANON_KEY`, with `PUBLIC_`, `NEXT_PUBLIC_` and `EXPO_PUBLIC_` copies for other frameworks, to `.env.development.local`. Vite, Next.js and Expo read that file in development only, so a production build never ships them. Read these rather than copying a URL from an example: `init` picks a free gateway port for each project, kept in `.env` as `API_EXTERNAL_URL`.\n\nA production build gets your deployment's values from `supatype build`, which runs your build command with them, or from the host's settings. When Supatype serves the app, the page can read them from the server instead, with `<script src=\"/supatype-env.js\" vite-ignore></script>` in `index.html` (`vite-ignore` keeps `vite build` from warning that it cannot bundle it); a Next.js app serves the same script from a route ([Frameworks: Next.js](https://www.supatype.com/docs/frameworks.html#nextjs)). For each value the build did not carry, the client reads the one that script set, at its first request. It never guesses the address from the page. `createClient` itself never throws, so a page that creates the client at module scope still prerenders. The first request made with no address or no anon key throws a `MissingClientValuesError` naming what is missing and the variables to set, rather than returning it as `{ data: null, error }`. [Deploy your frontend](https://www.supatype.com/docs/deploying-your-frontend.html) covers each host.\n\n`supatype.url` and `supatype.anonKey` are the address and anon key the client uses: the ones given to `createClient`, else the ones the page set (see above), read each time you ask. Each is an empty string while neither has one, and neither throws. Use `anonKey` for a call the client does not make, such as opening a second connection or a plain `fetch` to the API.\n\nThe session is saved and restored by default. A restored session keeps the user as it was, including `isAnonymous`, `identities` and `factors`, so a guest is still a guest after a reload. Pass `auth: { persistSession: false }` to keep it in memory only.\n\n`createClient` takes these options as well as `url` and `anonKey`:\n\n| Option | What it does |\n| --- | --- |\n| `serviceRoleKey` | Bypasses row-level security. Use it only on a server or in a trusted tool, and never ship it to a browser. |\n| `headers` | Headers sent with every request. Pass a function to have it read on each request. |\n| `auth.storageKey` | Key the session is saved under. Default `\"supatype.auth.session\"`. |\n| `auth.storage` | Your own session store with `getItem`, `setItem` and `removeItem`, such as AsyncStorage in React Native. |\n| `auth.cookiePrefix` | Prefix of the auth cookie `@supatype/ssr` reads. Default `\"st\"`. |\n| `timeout`, `retry` | See [Timeouts and retries](https://www.supatype.com/docs/client.html#timeouts-and-retries). |\n| `initialSession` | A session to start with. `@supatype/ssr` uses it to hand a cookie session to the client. |\n| `queryCache` | The in-memory cache for `.cache()` reads. Default: one shared cache. |\n\n### Generated types\n\n`supatype dev`, `supatype push` and `supatype generate` write these files. Do not edit them.\n\n| File | Holds |\n| --- | --- |\n| `supatype/generated/client.ts` | The `createClient` to import, the table types, the columns that keep exact values and the models that keep drafts. It also re-exports `@supatype/client` |\n| `supatype/generated/index.d.ts` | Row, insert and update types for each table |\n| `types/database.ts` | The `Database` type, for code that wants the raw shapes |\n\nTables are named as in the database: `post`, `comment`, `post_tag`. Calling `createClient` with no type argument picks up the generated types. To type a client against a schema you do not generate, such as a second project or a test double, pass the database type: `createClient<MyDatabase>({ ... })`.\n\nExact numbers keep every digit when you import from the generated `client.ts`. A `BigInt` column reads as a `bigint`. `Decimal` and `Money` columns read as strings.\n\nA number too large for JavaScript, in a column the client does not know, returns an error that names the column. This usually happens in an embed: select the column directly instead. This covers a number inside an array too, at any depth, such as a json column holding `[9007199254740993]`. `BigInt[]` and `Decimal[]` columns the generated types describe keep every element exact instead.\n\n### Read rows\n\n`typescript`:\n\n```ts\nconst { data: posts, error } = await supatype\n .from(\"post\")\n .select(\"id, title, slug, author(name), comment(body)\")\n .order(\"published_at\", { ascending: false })\n .limit(10)\n\nif (error) throw new Error(error.message)\nfor (const post of posts ?? []) console.log(post.title, post.author?.name)\n```\n\n`select` takes a list of columns. The result type follows the list. `*` selects every column.\n\nName a related table to embed it: `author(name)` follows `author_id`, and `comment(body)` lists a post's comments. A many-to-many relation embeds through its junction table: `select(\"title, tag(name)\")`.\n\nA to-one embed can be `null`. Write `author!inner(name)` to keep only posts that have one. Rename an embed with `writer:author(name)`.\n\n`single()` returns one row and errors when there is not exactly one. `maybeSingle()` returns `null` for no row.\n\n`typescript`:\n\n```ts\nconst { data: post } = await supatype.from(\"post\").select(\"*\").eq(\"slug\", \"hello-world\").maybeSingle()\nconsole.log(post?.title)\n```\n\n#### Linking many-to-many rows\n\nA many-to-many link is a row in the junction table, and you write it like any other row. The junction is named after the two tables, sorted and joined with `_` (`lot_tag` for `lot` and `tag`), with a `<model>_id` column for each end. It is in the generated types, so `from(\"lot_tag\")` is typed. Nested `connect` and `set` writes are not supported yet.\n\n`typescript`:\n\n```ts\n// add a link, and several at once\nawait supatype.from(\"lot_tag\").insert({ lot_id: lot.id, tag_id: tag.id })\nawait supatype.from(\"lot_tag\").insert(tags.map((t) => ({ lot_id: lot.id, tag_id: t.id })))\n\n// list a lot's tags, or the links themselves\nconst { data } = await supatype.from(\"lot\").select(\"title, tags:tag(name)\").eq(\"id\", lot.id)\nconst { data: links } = await supatype.from(\"lot_tag\").select(\"tag_id\").eq(\"lot_id\", lot.id)\n\n// remove a link\nawait supatype.from(\"lot_tag\").delete().eq(\"lot_id\", lot.id).eq(\"tag_id\", tag.id)\n```\n\nWho may write a link follows from its two ends. A link is readable by a caller who can read both rows, and writable by a caller who can read both and may update the model that owns the link: the one whose own `ManyToMany` field names the junction (either one, when both declare it). A refused insert returns an error. A delete the caller may not make removes no row and returns no error, so ask for the deleted rows with `.select()` if you need to know. See [Access Rules](https://www.supatype.com/docs/schema/access-rules.html#many-to-many-junction-tables).\n\n`count` is `null` unless you ask for it:\n\n`typescript`:\n\n```ts\nconst { count } = await supatype.from(\"post\").select(\"id\", { count: \"exact\" }).eq(\"kind\", \"news\")\nconsole.log(count)\n```\n\n### Filters\n\n| Filter | Matches |\n| --- | --- |\n| `eq`, `neq` | equal, not equal |\n| `gt`, `gte`, `lt`, `lte` | greater or less than |\n| `like`, `ilike` | a pattern, `ilike` ignores case |\n| `in` | any of a list |\n| `is` | `null`, `true` or `false` |\n| `contains`, `containedBy` | an array, range or jsonb column that holds the value, or is held by it |\n| `not`, `or`, `match` | negation, either filter, several equalities |\n\n`typescript`:\n\n```ts\nawait supatype.from(\"post\").select(\"id\").in(\"kind\", [\"news\", \"guide\"]).is(\"published_at\", null)\nawait supatype.from(\"post\").select(\"id\").ilike(\"title\", \"%hello%\").range(0, 19)\n```\n\nReads also take `order`, `limit` and `range`. Filters work on `update` and `delete` too.\n\n### Cache a read\n\n`.cache({ ttl })` keeps a read's result in the client's memory for `ttl` milliseconds. Add `server: true` to cache it on the server as well, for a model that declares a `cache`; add `public: true` to share one entry between users when the model allows it.\n\n`typescript`:\n\n```ts\nconst { data, meta } = await supatype\n .from(\"post\")\n .select(\"id, title\")\n .cache({ ttl: 30_000, server: true }) // milliseconds\n\nconsole.log(meta?.cacheStatus) // \"HIT\", \"MISS\" or \"BYPASS\"\n```\n\nThe cache status is `meta.cacheStatus`, on the result next to `data` and `error`: it is not a field of the result itself. It is `\"HIT\"` when a cache answered and `\"MISS\"` when the read went to the database. `\"BYPASS\"` appears only when the server says so in its `X-Supatype-Cache-Status` header. A model with no server cache, or a project with caching off, sends no header, and the read reports `\"MISS\"`. A read that did not call `.cache()` has no `meta.cacheStatus`, and `meta` itself can be absent.\n\n### Globals\n\nA singleton model (`singleton: true`) holds one row that always exists, such as site settings. `global(name)` reads and updates it without a filter. `name` is the model's snake case name, as in `_global_site_settings`; for a model that sets its own `tableName`, use `from(tableName)` instead.\n\n`typescript`:\n\n```ts\nconst { data: settings } = await supatype.global<{ title: string }>(\"site_settings\").get()\nawait supatype.global(\"site_settings\").update({ title: \"New title\" })\n```\n\n`get()` returns the row, or `null`. `update(fields)` changes only the fields you name and returns the row. Both return `{ data, error }`, and the model's access rules apply as for any other read or write.\n\n### Insert, update, delete\n\n`typescript`:\n\n```ts\nconst { data: created, error: insertError } = await supatype\n .from(\"post\")\n .insert({ title: \"Draft idea\", body: \"Plain text is fine.\", kind: \"guide\", author_id: userId })\n .select(\"id\")\n .single()\nif (insertError || !created) throw new Error(insertError?.message ?? \"insert failed\")\n\nawait supatype.from(\"comment\").update({ body: \"Edited\" }).eq(\"id\", commentId)\nawait supatype.from(\"comment\").delete().eq(\"id\", commentId)\n```\n\nA write returns no rows unless you add `.select()`: without it, `data` is `null`. Returning a row needs permission to read it, so leave `.select()` off when the access rules let the caller create a row but not read it. On a write, `single()` and `maybeSingle()` work only after `.select()`. On a delete, `.select()` returns the rows it deleted. `upsert` inserts or updates by primary key.\n\nAn update or delete with no filter is refused, so `.delete()` alone returns an error instead of emptying the table. The `supatype/postgres` image loads `pg_safeupdate`, which raises `DELETE requires a WHERE clause` (or the same for `UPDATE`). To change every row, add a filter that matches all of them, such as `.not(\"id\", \"is\", null)`.\n\nA `RichText` field takes a plain string on write.\n\nSome owner columns can be left out. A `SupatypeAuthUserId` field that the `create` rule names in `Owner<>`, and that has no default of its own, defaults to the caller. A relation's key, such as `author_id`, is not filled in, so send it.\n\n### Drafts and publishing\n\nOn a model with `versions: { drafts: true }`, `update` saves a draft. The live row does not change until the record is published.\n\n`typescript`:\n\n```ts\n// Save a draft\nawait supatype.from(\"post\").update({ title: \"Better title\" }).eq(\"id\", postId)\n\n// Save and publish in one call\nawait supatype.from(\"post\").update({ title: \"Final title\" }, { publish: true }).eq(\"id\", postId)\n\n// Read drafts\nconst { data: drafts } = await supatype.from(\"post\").draft().select(\"id, title\").eq(\"id\", postId)\n\n// Publish the saved draft\nawait supatype.rpc(\"publish\", { model_table: \"post\", record_id: postId }, { schema: \"supatype\" })\n```\n\n`insert` on a drafts model creates a draft record. Publish it to make it live. A plain `select()` reads the live table, which holds the published values.\n\n`{ publish: true }` is only accepted on drafts models, and only when the client comes from the generated file.\n\n### Auth\n\n`typescript`:\n\n```ts\nawait supatype.auth.signUp({ email: \"alex@example.com\", password: \"a-long-password\" })\n\nconst { data, error: signInError } = await supatype.auth.signInWithPassword({\n email: \"alex@example.com\",\n password: \"a-long-password\",\n})\nif (signInError) throw new Error(signInError.message)\nconsole.log(data.session?.user.id)\n\nconst { data: { session } } = await supatype.auth.getSession()\nconsole.log(session?.accessToken)\n\nconst { data: { subscription } } = supatype.auth.onAuthStateChange((event, current) => {\n console.log(event, current?.user.email)\n})\nsubscription.unsubscribe()\n\nawait supatype.auth.signOut()\n```\n\nOnce signed in, every request carries the user's token, so access rules see them. `onAuthStateChange` calls back at once with the current state, then on each change.\n\nWhen the project asks new users to confirm their email, `signUp` returns `session: null` and does not sign the user in. They sign in once they have confirmed.\n\n`getUser()` fetches the user from the server. Magic links, OAuth, one-time codes and MFA are on `supatype.auth` too, and so is SAML single sign-on: `signInWithSSO({ domain })` or `signInWithSSO({ providerId })` sends the browser to the organisation's identity provider, with PKCE by default. See [Single sign-on](https://www.supatype.com/docs/sso.html#sign-in).\n\n### Storage\n\n`typescript`:\n\n```ts\nconst bucket = supatype.storage.from(\"covers\")\n\nconst { data: upload, error: uploadError } = await bucket.upload(`${userId}/cover.png`, file, {\n contentType: \"image/png\",\n upsert: true,\n})\nif (uploadError || !upload) throw new Error(uploadError?.message ?? \"upload failed\")\n\nconst { data: { publicUrl } } = bucket.getPublicUrl(upload.path)\nconst { data: signed } = await bucket.createSignedUrl(upload.path, 60)\nconsole.log(publicUrl, signed?.signedUrl)\n```\n\n`getPublicUrl` works for public buckets. `createSignedUrl` gives a link that expires after the number of seconds you pass. `download`, `list` and `remove` are on the bucket too.\n\nAn `ImageAsset` or `FileAsset` column holds `{ bucket, path }`, not a URL. `publicUrl` builds the URL from it, and returns `null` for an empty column:\n\n`typescript`:\n\n```ts\nconst { data: post } = await supatype.from(\"post\").select(\"title, cover\").eq(\"slug\", \"hello-world\").maybeSingle()\nconst coverUrl = supatype.storage.publicUrl(post?.cover)\n```\n\nThe bucket's access rules from the schema decide who may upload, overwrite and delete.\n\n### Realtime\n\n`typescript`:\n\n```ts\nconst sub = supatype.from(\"comment\").subscribe((change) => {\n console.log(change.eventType, change.new, change.old)\n}, { event: \"INSERT\" })\n\nsub.unsubscribe()\n```\n\nEach change reaches only subscribers allowed to read that row. `event` is `INSERT`, `UPDATE`, `DELETE` or `*`. For broadcast and presence, use `supatype.realtime.channel(name)`.\n\n### Functions\n\n`typescript`:\n\n```ts\nconst { data: reply, error: fnError } = await supatype.functions.invoke(\"hello\", { body: { name: \"Alex\" } })\nif (fnError) console.error(fnError.code, fnError.message)\nconsole.log(reply)\n```\n\nThe call goes to `/functions/v1/hello` with the user's token. A JSON response is parsed. Function names and bodies are not typed. `invoke` also takes `method` (default `POST`), `headers` and `idempotent`. Only a `GET` is retried on a transient failure, because a `POST` may already have run. Pass `idempotent: true` when running the function twice is harmless.\n\n`typescript`:\n\n```ts\nawait supatype.functions.invoke(\"stats\", { method: \"GET\", headers: { \"x-region\": \"eu\" } })\n```\n\nInside a function, `ctx.url` is the API's internal address, for calls the function makes. `ctx.publicUrl` is the public address, for links you give to people.\n\n`supatype.rpc(name, params, options)` calls a Postgres function. Its options are `count`, `head`, `schema` for a function outside the default schema, and `idempotent`. A function is not part of the schema: see [Server logic in a Postgres function](https://www.supatype.com/docs/schema.html#server-logic) for writing one and what Supatype does not manage.\n\n### GraphQL\n\n`typescript`:\n\n```ts\nimport type { TableRow } from \"../supatype/generated/client\"\n\ntype Post = TableRow<\"post\">\ntype Author = TableRow<\"author\">\ntype PostPage = {\n postCollection: { edges: { node: Pick<Post, \"title\" | \"body\"> & { author: Pick<Author, \"name\"> } }[] }\n}\n\nconst { data, error } = await supatype.graphql<PostPage>(`{\n postCollection(first: 10) { edges { node { title body author { name } } } }\n}`)\nif (error) throw new Error(error.message)\nconst first = data?.postCollection.edges[0]?.node\nconsole.log(first?.author.name, first?.body.root.children?.[0])\n```\n\nThe query goes to `/graphql/v1` as the signed-in user, under the same access rules as REST. Pass variables as the second argument, and `{ idempotent: true }` as the third to retry a read on a transient failure.\n\nRich text, blocks and json fields come back as objects and arrays, not strings. pg_graphql types every json and jsonb column with its `JSON` scalar and sends it as a JSON-encoded string, so the client reads the schema once per role, finds each field of that type in your query, and decodes it. Aliases, named and inline fragments, nested relations and lists all decode. A field the client cannot place stays exactly as returned: one added since the schema was read (it reads the schema again on the next call), a document with more than one operation, or a schema it could not read.\n\nThe type argument names the answer's shape and is not checked at runtime. Build it from the generated `TableRow` types so `body` is typed as the rich text document it now is. Variables you send are not encoded: a json argument still takes a string.\n\nRelation fields use your schema's names. The side that holds the key takes the relation field's name, so `author` above. The other side takes its `HasMany` or `HasOne` field's name, so an author's posts are `posts`. A list is still a connection, read through `edges { node }`. REST embeds are named as before.\n\n> **CHANGED IN 0.7.0:** GraphQL used to name relations after the tables they join, such as `postCollection` for an author's posts. The next `supatype push` writes the schema's names, and a query that still uses an old name fails with `Unknown field`. A few ambiguous relations keep pg_graphql's own name.\n\nUsing another GraphQL client? `readGraphqlSchema` reads the `data` of an introspection answer to `GRAPHQL_SCHEMA_QUERY`, and `decodeGraphqlJsonFields(query, data, schema)` decodes an answer the same way. Read the schema again when it returns `schemaIsStale: true`.\n\n### Errors\n\nQueries, `rpc`, `functions.invoke`, auth and most storage calls return `{ data, error }`. Check `error` before using `data`.\n\n`error` is a `SupatypeError`, an `Error` with `message` and, when known, `code`, `status`, `details` and `hint`, so `error instanceof SupatypeError` holds and `String(error)` reads `SupatypeError: <message>`. Its own fields are only those, so spreading it or turning it into JSON gives exactly them. A failure in transit is the SDK error the client threw, such as a `NetworkError` (`error instanceof NetworkError`); those are `SupatypeCodedError`s, which always carry a `code` and a `helpUrl`. When a field validator refused the write, `field` names the column, so you can mark that input.\n\nAn insert an access rule refuses returns code `42501`. An update or delete that the rules hide matches no rows and returns no error. `single()` with no row returns `PGRST116`.\n\nWhen the server refuses a request with 401, the client sends it again only if the token expired or was invalid (`PGRST301`, `PGRST303` or \"JWT expired\"), the caller is signed in, and refreshing the session gave a new token. Any other 401 is returned as `error` after one try, including an anon write that an access rule refuses.\n\n> **NETWORK FAILURES:** A network failure on a query, `rpc`, `graphql` or a function call comes back as `error` with a code: `NETWORK_TIMEOUT`, `NETWORK_CONNECTION_REFUSED`, `NETWORK_DNS_FAILURE` or `NETWORK_ERROR`. A read still answered 429 after its last retry has code `RATE_LIMITED`. Most auth and storage calls throw instead, so wrap them in `try` when the network may fail. Three return the failure as `error` like a query: `storage.listBuckets`, `storage.createBucket` and `auth.refreshSession`. `auth.signOut` ignores a network failure and clears the session on this device anyway.\n\n### Timeouts and retries\n\nEvery HTTP request the client makes (tables, `rpc`, `graphql`, `functions`, auth and storage, uploads included) is aborted after `timeout` milliseconds, 30000 by default. Raise it for large uploads on slow links. The realtime socket is not an HTTP request and is not covered.\n\nOnly requests that are safe to send twice are retried:\n\n- `GET` and `HEAD` requests: table selects, storage downloads, `auth.getUser()`, and an `rpc` call with `head: true`.\n- The two reads storage sends as `POST`: `list` and `createSignedUrl`.\n- An `rpc`, `graphql` or `functions.invoke` call you pass `idempotent: true`.\n\nInserts, updates, upserts, deletes, uploads, sign-in and sign-up, and any `rpc`, `graphql` or function call without `idempotent: true` are sent once: a write that failed in flight may already have been applied, and sending it again could apply it twice. A 429 on one of these comes back as the server's own error.\n\nA retried request is retried up to 3 times, after 200 ms, 1 s and 3 s, on a dropped connection or a 5xx. A 429 waits for its `Retry-After` (5 seconds when the header is absent). A timeout and a 4xx are never retried. `retry: false` turns retries off for every request.\n\n`typescript`:\n\n```ts\nconst { data, error } = await supatype.rpc(\n \"search_posts\",\n { query: \"supatype\" },\n { idempotent: true }, // the function only reads, so a retry is harmless\n)\n```\n\n## Frameworks\n\nSource: https://www.supatype.com/docs/frameworks.html\n\nSupatype has bindings for React, Vue, Svelte and Solid, a React Native helper, and a server helper for Next.js. Each one wraps the client you already create, so everything on the [Client](https://www.supatype.com/docs/client.html) page still applies.\n\n### Packages\n\n| Package | Exports |\n| --- | --- |\n| `@supatype/react` | `SupatypeProvider`, `useSupatype`, `useQuery`, `useMutation`, `useFunction`, `useAuth`, `useSubscription`, `useChannel`, `useRealtimeConnection`, `useLivePreview`, `RichText` |\n| `@supatype/vue` | `supatypePlugin`, `useSupatype`, `useQuery`, `useMutation`, `useFunction`, `useAuth`, `useSubscription`, `useChannel`, `useRealtimeConnection` |\n| `@supatype/svelte` | `setSupatypeClient`, `getSupatypeClient`, `createQuery`, `createMutation`, `createFunction`, `createAuth`, `createSubscription`, `createChannel`, `createRealtimeConnection` |\n| `@supatype/solid` | `SupatypeContext`, `useSupatype`, `createQuery`, `createMutation`, `createFunction`, `createAuth`, `createSubscription`, `createChannel`, `createRealtimeConnection` |\n| `@supatype/react-native` | `createNativeClient`, `secureStoreAdapter`, `asyncStorageAdapter`, `openOAuth`, `createAuthUrlListener` |\n| `@supatype/ssr` | `createServerClient`, and `GET` from `@supatype/ssr/next` |\n\n`supatype init` adds `@supatype/client` to your app, and `@supatype/ssr` as well in a Next.js app. Add the binding for your framework yourself, on the same release as `@supatype/client`:\n\n```sh\n$ npm install @supatype/react # React and Next.js\n$ npm install @supatype/vue\n$ npm install @supatype/svelte\n$ npm install @supatype/solid\n$ npm install @supatype/react-native @supatype/react # React Native, then:\n$ npx expo install expo-secure-store expo-web-browser expo-linking\n```\n\nWith pnpm, Yarn or Bun, use that tool's add command instead.\n\nEvery example below imports the client from `src/supatype.ts`, created once as shown in [Client: Create the client](https://www.supatype.com/docs/client.html#setup). With Vite, read the names `supatype dev` writes for development and `supatype build` sets for a production build:\n\n`src/supatype.ts`:\n\n```ts\nimport { createClient } from \"../supatype/generated/client\"\n\nexport const supatype = createClient({\n url: import.meta.env.VITE_SUPATYPE_URL,\n anonKey: import.meta.env.VITE_SUPATYPE_ANON_KEY,\n})\n```\n\nA build made without the values, such as a plain `vite build` that Supatype serves, reads them from `/supatype-env.js`, so `index.html` needs `<script src=\"/supatype-env.js\" vite-ignore></script>` in its head. `init` adds it only to an `index.html` it writes itself; in a Vite app that already had one, add the tag yourself, as [Deploy your frontend: Supatype hosts it](https://www.supatype.com/docs/deploying-your-frontend.html#supatype-hosts) shows.\n\nSign-in screens are covered on [Auth: Pre-built UI](https://www.supatype.com/docs/auth.html#ui), and the subscription hooks on [Realtime: Framework hooks](https://www.supatype.com/docs/realtime.html#hooks). This page does not repeat them.\n\n### React\n\nWrap your app in `SupatypeProvider` and pass the client. Every hook reads the client from it and throws when there is no provider above it.\n\n`src/Posts.tsx`:\n\n```tsx\nimport { SupatypeProvider, useQuery, useMutation, useFunction } from \"@supatype/react\"\nimport { supatype } from \"./supatype\"\n\nfunction Posts() {\n const { data: posts, loading, error, refetch } = useQuery(\"post\", {\n select: \"id, title, slug\",\n order: { column: \"title\" },\n limit: 20,\n })\n const { mutate: removePost } = useMutation(\"post\", \"delete\")\n const { invoke: greet, data: reply } = useFunction<{ greeting: string }>(\"greet\")\n\n if (loading) return <p>Loading</p>\n if (error) return <p>{error.message}</p>\n return (\n <ul>\n {posts?.map((post) => (\n <li key={post.id}>\n {post.title}\n <button onClick={async () => { await removePost(undefined, { filter: { id: post.id } }); refetch() }}>Delete</button>\n </li>\n ))}\n <button onClick={() => greet({ name: \"Alex\" })}>{reply?.greeting ?? \"Say hello\"}</button>\n </ul>\n )\n}\n\nexport function App() {\n return <SupatypeProvider client={supatype}><Posts /></SupatypeProvider>\n}\n```\n\n#### useQuery\n\n`useQuery(table, options)` returns `data`, `error`, `count`, `loading` and `refetch`. It runs again when the options change, and when a different user signs in or out.\n\n| Option | What it does |\n| --- | --- |\n| `select` | The select expression. Default `*`. |\n| `filter` | Equality filters, one per column. |\n| `order` | `{ column, ascending }`. Ascending by default. |\n| `limit`, `offset` | Paging. An `offset` with no `limit` reads 100 rows, in every binding. |\n| `enabled` | `false` skips the query. |\n| `refetchInterval` | Runs the query again every so many milliseconds. |\n| `cache` | The same cache options as the client's `.cache()`. |\n| `draft` | Reads saved drafts instead of published rows, on a model with drafts. See [Drafts and publishing](https://www.supatype.com/docs/client.html#drafts). |\n\nFor anything `filter` cannot say, such as ranges or embeds with conditions, use the client directly through `useSupatype()`.\n\n#### useMutation and useFunction\n\n`useMutation(table, operation)` takes `\"insert\"`, `\"update\"`, `\"delete\"` or `\"upsert\"` and returns `mutate`, `loading` and `error`. `mutate(data, { filter, publish, select })` takes the rows to write; `filter` picks the rows for an update or delete, and `publish: true` publishes the drafts an update saves. Without `select`, the written rows are not returned and `data` is `null`, so call `refetch` on your query afterwards. To get them back, pass `select: true` for every column or a column string such as `select: \"id,title\"`, written as `.select()` takes it. Returning rows needs permission to read them as well as write them.\n\n`mutate` resolves with `{ data, error, count }`. There are no `onMutate`, `onSuccess` or `onError` callbacks, so an optimistic update and its rollback are yours to write.\n\n`useFunction(name)` returns `invoke`, `data`, `error` and `loading`. `invoke(body, { method, headers })` calls `supatype.functions.invoke`. See [Functions: Call a function](https://www.supatype.com/docs/functions.html#call).\n\n`useAuth()` returns `user`, `session`, `loading`, `error`, `signUp`, `signIn` (email and password), `signInWithOAuth`, `signInWithOtp` and `signOut`, and re-renders when the session changes. For anything else, such as MFA or a password reset, call `useSupatype().auth`. See [Auth](https://www.supatype.com/docs/auth.html).\n\n#### Live preview\n\nStudio can show your app in a pane beside the edit form and stream the unsaved values into it as the editor types. Tell Studio where a record's page lives in `supatype.config.ts`:\n\n`supatype.config.ts`:\n\n```ts\nexport default defineConfig({\n // ...\n admin: { livePreview: { Post: { urlPattern: \"https://example.com/preview/{slug}\" } } },\n})\n```\n\nA path such as `\"/preview/{slug}\"` is enough when the same deployment serves your app (`app.mode` set to `static` or `proxy`). With `app.mode: \"none\"`, `supatype push` refuses a path and wants the full URL.\n\nOn that page, `useLivePreview` returns the live values while Studio is sending them and your own data otherwise:\n\n`src/PostPreview.tsx`:\n\n```tsx\nimport { useLivePreview, RichText } from \"@supatype/react\"\nimport type { TableRow } from \"@supatype/client\"\n\nexport function PostPreview({ post }: { post: TableRow<\"post\"> }) {\n const { data, isPreview } = useLivePreview({ initialData: post })\n return (\n <article>\n {isPreview && <p>Preview</p>}\n <h1>{data.title}</h1>\n <RichText content={data.body} />\n </article>\n )\n}\n```\n\nA message is applied only when it comes from the window framing the page, at a Studio origin. By default that is the origin of the provider's client URL, since Studio is served at `/studio/` on your API. If Studio is served somewhere else, or the page has no provider, pass `studioOrigin` with one URL or a list. Messages from any other origin are ignored with a console warning. `model` limits the hook to messages for one model.\n\nThis is the unsaved form state. To show the last saved draft instead, use `useQuery` with `draft: true`.\n\n#### RichText\n\n`RichText` renders a saved rich text field as React elements. Text is rendered as text, never as HTML, and links keep only a safe `href`. It works in Server Components and Client Components. Props are `content`, `className`, and `as` to choose the wrapper: `div` (the default), `article`, `section`, `aside` or `main`. A `null` content renders nothing.\n\n### Vue\n\nInstall the plugin with your client. The composables must be called inside `setup`.\n\n`src/main.ts`:\n\n```ts\nimport { createApp } from \"vue\"\nimport { supatypePlugin } from \"@supatype/vue\"\nimport { supatype } from \"./supatype\"\nimport App from \"./App.vue\"\n\ncreateApp(App).use(supatypePlugin, supatype).mount(\"#app\")\n```\n\n`src/Posts.vue`:\n\n```vue\n<script setup lang=\"ts\">\nimport { useQuery, useMutation } from \"@supatype/vue\"\n\nconst { data: posts, loading, refetch } = useQuery(\"post\", { columns: \"id, title\", limit: 20 })\nconst { mutate: removePost } = useMutation(\"post\", \"delete\")\n\nasync function remove(id: string) {\n await removePost(undefined, { filter: { id } })\n await refetch()\n}\n</script>\n\n<template>\n <p v-if=\"loading\">Loading</p>\n <ul v-else>\n <li v-for=\"post in posts\" :key=\"post.id\">\n {{ post.title }} <button @click=\"remove(post.id)\">Delete</button>\n </li>\n </ul>\n</template>\n```\n\nResults are refs. The query runs when the component mounts. To sort, page or filter from component state, pass the options as a ref or a getter, such as `useQuery(\"post\", () => ({ limit: 20, offset: page.value * 20 }))`; the query runs again whenever they change. `enabled` may be a ref; the query runs again when it turns `true`. `useFunction(name)` returns `invoke(body)`, `data`, `error` and `loading`.\n\n### Svelte\n\nSet the client once in a parent component. The `create*` functions read it from context, so call them during component setup, then read the stores with `$`.\n\n`src/App.svelte`:\n\n```svelte\n<script lang=\"ts\">\n import { setSupatypeClient } from \"@supatype/svelte\"\n import { supatype } from \"./supatype\"\n import Posts from \"./Posts.svelte\"\n\n setSupatypeClient(supatype)\n</script>\n\n<Posts />\n```\n\n`src/Posts.svelte`:\n\n```svelte\n<script lang=\"ts\">\n import { createQuery } from \"@supatype/svelte\"\n\n const { data: posts, loading } = createQuery(\"post\", { columns: \"id, title\", limit: 20 })\n</script>\n\n{#if $loading}\n <p>Loading</p>\n{:else}\n <ul>{#each $posts ?? [] as post (post.id)}<li>{post.title}</li>{/each}</ul>\n{/if}\n```\n\n`createQuery` fetches as soon as it is created and returns readable stores plus `refetch`. To sort, page or filter from component state, pass the options as a store; the query runs again whenever it changes. From `$state`, `toStore(() => ({ limit: 20, offset: page * 20 }))` from `svelte/store` makes one. `createMutation` and `createFunction` work like the Vue versions.\n\n### Solid\n\nProvide the client with `SupatypeContext.Provider`. Results are accessors, so call them to read.\n\n`src/App.tsx`:\n\n```tsx\nimport { For, Show } from \"solid-js\"\nimport { SupatypeContext, createQuery } from \"@supatype/solid\"\nimport { supatype } from \"./supatype\"\n\nfunction Posts() {\n const { data: posts, loading } = createQuery(\"post\", { columns: \"id, title\", limit: 20 })\n return (\n <Show when={!loading()} fallback={<p>Loading</p>}>\n <ul><For each={posts() ?? []}>{(post) => <li>{post.title}</li>}</For></ul>\n </Show>\n )\n}\n\nexport function App() {\n return <SupatypeContext.Provider value={supatype}><Posts /></SupatypeContext.Provider>\n}\n```\n\nThe query runs on mount. To sort, page or filter from a signal, pass the options as a function, such as `createQuery(\"post\", () => ({ limit: 20, offset: page() * 20 }))`; the query runs again whenever the signals it reads change. `createMutation` and `createFunction` work like the Vue versions.\n\n#### How Vue, Svelte and Solid differ from React\n\n- The query option is `columns`, not `select`. `refetchInterval`, `cache` and `draft` are React only.\n- `mutate(data, { filter, select })` takes `filter` and `select` as React's does, but not `publish`. Without `select`, `data` is `null`.\n- `invoke` takes a body only, so the call is always a `POST`.\n- `signIn` and `signUp` take `(email, password)` rather than an object, `signInWithOAuth(provider)` sends the browser to the provider, and there is a `resetPassword(email)`.\n- There is no live preview hook or rich text component.\n\nAll four bindings run the query again when a different user signs in or out.\n\n### React Native\n\n`createNativeClient` is `createClient` with session storage that survives app restarts. Pass `expo-secure-store` (recommended) or AsyncStorage; without either it throws. Use the `EXPO_PUBLIC_` values `supatype keys` writes.\n\n`src/supatype.ts`:\n\n```ts\nimport * as SecureStore from \"expo-secure-store\"\nimport * as Linking from \"expo-linking\"\nimport { createNativeClient, createAuthUrlListener } from \"@supatype/react-native\"\n\nexport const supatype = createNativeClient({\n url: process.env.EXPO_PUBLIC_SUPATYPE_URL!,\n anonKey: process.env.EXPO_PUBLIC_SUPATYPE_ANON_KEY!,\n secureStore: SecureStore,\n})\n\n// Finish sign-ins that come back through a deep link, on cold and warm start.\nexport const stopAuthLinks = createAuthUrlListener(supatype, { linking: Linking, pathIncludes: \"auth/callback\" })\n```\n\nWrap the app in `SupatypeProvider` from `@supatype/react` and use the same hooks as on the web. The native client does not read sessions from a URL by itself, which is why the listener is there.\n\n`openOAuth(client, { provider, redirectTo, webBrowser })` runs an OAuth sign-in in `expo-web-browser` with PKCE and returns the session, or `cancelled: true` when the user closes the browser. The ready-made native screens are on [Auth: Pre-built UI](https://www.supatype.com/docs/auth.html#ui).\n\n### Next.js\n\n`next build` prerenders pages before any deployment's values exist, so a Next.js app takes them when it runs instead. One route serves the browser client its address and anon key on each page load, from `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` in the server's environment, and the server client reads the same two variables. The same build then runs against whichever deployment it is started for. `supatype init` writes both pieces into an App Router app:\n\n`app/supatype-env.js/route.ts`:\n\n```ts\nexport { GET } from \"@supatype/ssr/next\"\n```\n\n`app/layout.tsx`:\n\n```tsx\nimport Script from \"next/script\"\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <body>\n <Script src=\"/supatype-env.js\" strategy=\"beforeInteractive\" />\n {children}\n </body>\n </html>\n )\n}\n```\n\nThe route needs no segment config, and must not export `dynamic`: Next 16 with `cacheComponents` on, as a new create-next-app has it, refuses that with a 500. `GET` reads the request, which is what makes Next 14 and Next 16 with `cacheComponents` render it per request instead of prerendering it with the build machine's values; Next 15, and Next 16 without `cacheComponents`, render every `GET` per request anyway. A route written by `init` 0.9.1 has the line `export const dynamic = \"force-dynamic\"`. `supatype generate`, which the project's `prepare` script runs on every `npm install`, replaces that route with the current one while it is still as `init` wrote it, and prints `updated`; a route changed since is left alone, with a warning to delete the line. Upgrade `@supatype/ssr` with the CLI: the route needs 0.9.2 or later. The route answers `window.__SUPATYPE_ENV__ = {\"url\":\"...\",\"anonKey\":\"...\"};` with `Cache-Control: no-cache`, as the Supatype server's own `/supatype-env.js` does. It answers 404 only when `SUPATYPE_PUBLIC_ENV` is `false`, and, when `SUPATYPE_URL` or `SUPATYPE_ANON_KEY` is unset or `SUPATYPE_ANON_KEY` holds a service role key, 200, not cached, with a script that sets only `error` to a reason naming every variable to fix, which the browser client throws on its first request. The browser client, created with `NEXT_PUBLIC_SUPATYPE_URL` and `NEXT_PUBLIC_SUPATYPE_ANON_KEY` left unset at build time, reads what the script set at its first request. How to set the two variables on each host is in [Deploy your frontend: Next.js](https://www.supatype.com/docs/deploying-your-frontend.html#nextjs).\n\nIn a Pages Router app, `init` writes nothing and prints the steps instead: create the same route file under `app/supatype-env.js/`, beside `pages/`; in `pages/_document.tsx`, import `Script` from `next/script` and put the same `<Script>` tag inside `<Head>`; then add `@supatype/ssr` to the app's dependencies. For a static export (`output: \"export\"` in `next.config`), which cannot serve a route, `init` writes neither piece and prints `supatype build -- next build`, or Supatype hosting, whose server answers `/supatype-env.js` itself.\n\n#### The browser client\n\nCreate the browser client once, from the generated file, for client components to import. Pass it the two `NEXT_PUBLIC_` names with no default. In `next dev` they come from `.env.development.local`. In a production build they are unset, so the client reads what `/supatype-env.js` set; a default would be fixed into the build and win over the route's values.\n\n`lib/supatype.ts`:\n\n```ts\nimport { createClient } from \"../supatype/generated/client\"\n\nexport const supatype = createClient({\n url: process.env.NEXT_PUBLIC_SUPATYPE_URL,\n anonKey: process.env.NEXT_PUBLIC_SUPATYPE_ANON_KEY,\n})\n```\n\nWhen the app is in `src/app/`, put it at `src/lib/supatype.ts` and import `\"../../supatype/generated/client\"`. The root layout is a Server Component, so give the provider a client component of its own, and wrap `{children}` in the layout's `<body>` with it, after the `<Script>` tag:\n\n`app/providers.tsx`:\n\n```tsx\n\"use client\"\n\nimport type { ReactNode } from \"react\"\nimport { SupatypeProvider } from \"@supatype/react\"\nimport { supatype } from \"@/lib/supatype\"\n\nexport function Providers({ children }: { children: ReactNode }) {\n return <SupatypeProvider client={supatype}>{children}</SupatypeProvider>\n}\n```\n\n`app/posts/post-list.tsx`:\n\n```tsx\n\"use client\"\n\nimport { useQuery } from \"@supatype/react\"\n\nexport function PostList() {\n const { data: posts, loading, error } = useQuery(\"post\", { select: \"id, title\", limit: 20 })\n if (loading) return <p>Loading</p>\n if (error) return <p>{error.message}</p>\n return <ul>{posts?.map((post) => <li key={post.id}>{post.title}</li>)}</ul>\n}\n```\n\nEvery hook in the [React](https://www.supatype.com/docs/frameworks.html#react) section works the same way in a client component. The session it signs in is the one the server client below reads from the cookie.\n\n#### Server components, route handlers and middleware\n\nIn the browser the client copies the session into a cookie named `st-auth-token` (path `/`, `SameSite=Lax`, `Secure` on HTTPS). `createServerClient` from `@supatype/ssr` reads that cookie on the server and builds a client signed in as the same user. Given only its options, it takes the address and anon key from `SUPATYPE_URL` and `SUPATYPE_ANON_KEY`, read on each call, and where one is unset, from `NEXT_PUBLIC_SUPATYPE_URL` or `NEXT_PUBLIC_SUPATYPE_ANON_KEY`. With neither, its first request throws an error saying it is running on a server and naming `SUPATYPE_URL` and `SUPATYPE_ANON_KEY`. Pass them first, as `createServerClient(url, anonKey, options)`, to use others.\n\nPut the helper in the folder that holds `app/`: `supatype-server.ts` at the project root for a create-next-app made without `src/`, or `src/supatype-server.ts` when the app is in `src/app/`. create-next-app points the `@/*` import alias at that folder, so `@/supatype-server` finds it in both layouts.\n\n`supatype-server.ts`:\n\n```ts\nimport { cookies } from \"next/headers\"\nimport { connection } from \"next/server\"\nimport { createServerClient } from \"@supatype/ssr\"\n\n// Server Components: no setAll, so the client never refreshes the session.\nexport async function serverClient() {\n const store = await cookies()\n // Render at request time: the client reads the clock to check the session's expiry.\n await connection()\n return createServerClient({ cookies: { getAll: () => store.getAll() } })\n}\n\n// Route Handlers and Server Actions: a refreshed session goes back to the browser.\nexport async function writableServerClient() {\n const store = await cookies()\n return createServerClient({\n cookies: {\n getAll: () => store.getAll(),\n setAll: (cookiesToSet) => cookiesToSet.forEach(({ name, value, options }) => store.set(name, value, options ?? {})),\n },\n })\n}\n```\n\n`app/posts/page.tsx`:\n\n```tsx\nimport { RichText } from \"@supatype/react\"\nimport { serverClient } from \"@/supatype-server\"\n\nexport default async function Page() {\n const supatype = await serverClient()\n const { data: posts } = await supatype.from(\"post\").select(\"id, title, body\")\n return posts?.map((post) => <RichText key={post.id} content={post.body} as=\"article\" />)\n}\n```\n\nA Route Handler uses `writableServerClient()` the same way. Middleware can write cookies, so refresh the session there, before the page renders, and check the user with the auth server:\n\n`middleware.ts`:\n\n```ts\nimport { NextResponse, type NextRequest } from \"next/server\"\nimport { createServerClient } from \"@supatype/ssr\"\n\nexport async function middleware(request: NextRequest) {\n const response = NextResponse.next()\n const supatype = createServerClient({\n cookies: {\n getAll: () => request.cookies.getAll(),\n setAll: (cookiesToSet) => cookiesToSet.forEach(({ name, value, options }) => response.cookies.set(name, value, options ?? {})),\n },\n })\n const { data } = await supatype.auth.getUser()\n if (!data.user) return NextResponse.redirect(new URL(\"/sign-in\", request.url))\n return response\n}\n\nexport const config = { matcher: [\"/account/:path*\"] }\n```\n\nWhat the cookie handling does and does not do:\n\n- Without `setAll`, as in a Server Component, the client never refreshes the session: an expired access token is sent as it is, and the API refuses it. A refresh there would spend the browser's refresh token and keep the new one to itself, so the browser's own next refresh would be refused. Do not pass a `setAll` that does nothing to get round this.\n- With `setAll`, the client refreshes an expired access token when a request it makes finds it expired, and writes every change to the session (a refresh, a sign-in, a sign-out) back through `setAll`.\n- A cookie whose access token has expired is kept only when it has a refresh token. Otherwise the server client runs as an anonymous caller.\n- Telling whether it has expired reads the clock, so `serverClient()` awaits `connection()` from `next/server` first, which renders the component at request time. Without it, Next 16 with `cacheComponents` logs `Next.js encountered the unstable value Date.now() while prerendering` for every page that uses it. `connection()` is in Next 15 and later; on Next 14 leave that line out.\n- The cookie is decoded, not verified. Queries made with it are checked by the API, so access rules hold. But do not trust `auth.getSession()` on the server to decide who someone is: call `auth.getUser()`, which asks the auth server, as the middleware above does.\n- Decoding uses `atob` and `TextDecoder`, not Node's `Buffer`, so it works on the edge runtime too.\n- Set `cookiePrefix` on both sides if you change the client's `auth.cookiePrefix`. The default is `st`.\n- The server client is built from `@supatype/client`, not your generated client file, so `update(..., { publish: true })` is not accepted on it.\n\nIn development, `supatype dev`, `init` and `keys --write` write a local stack's `SUPATYPE_URL` and `SUPATYPE_ANON_KEY`, with the `NEXT_PUBLIC_` copies, to `.env.development.local`, which Next.js reads in development only, so the route answers in `next dev`. A value fixed into the build that way always wins over the route's.\n\n## Auth\n\nSource: https://www.supatype.com/docs/auth.html\n\nAuth is built into the Supatype server. It signs users in, issues the tokens every request carries, and those tokens are what your schema's access rules check.\n\n### How it runs\n\nThe auth service is part of `supatype-server`, the same process that serves REST, GraphQL, storage and functions. It answers under `/auth/v1` on your project's API URL. It keeps its users, identities and sessions in the `auth` schema of your project's database and runs its own migrations when the server starts.\n\n- `supatype dev` with `database.provider: \"docker\"` (what `supatype init` writes): the server runs in the Compose stack behind Kong. Your API URL is `API_EXTERNAL_URL` in the project's `.env`.\n- `supatype dev` with `database.provider: \"native\"`: the server runs as a local process on `server.port`, `18471` by default.\n- Self-host: `supatype self-host compose up` runs the same server image. It needs `JWT_SECRET` in `.env` and fills in a blank `ANON_KEY` or `SERVICE_ROLE_KEY` from it. See [Self-hosting](https://www.supatype.com/docs/#self-host).\n\nIn local dev, sign-ups are confirmed automatically, so a new user gets a session straight away with no email round trip. A self-hosted stack sends a confirmation link instead. See [Email sign-in and confirmation](https://www.supatype.com/docs/auth.html#email-settings).\n\n> **NOTE:** Who may open Studio, and what they may do there, is decided by Studio roles. See [Studio roles](https://www.supatype.com/docs/studio-roles.html).\n\n### Sign-in methods\n\nEach method below is a call on `supatype.auth`. The [client page](https://www.supatype.com/docs/client.html#auth) shows the common ones in use.\n\n| Method | Client call | Default |\n| --- | --- | --- |\n| Email and password | `signUp`, `signInWithPassword` | On |\n| Magic link or email code | `signInWithOtp({ email })`, then `verifyOtp` for a code | On, needs a mail provider to deliver |\n| Phone code (SMS, or WhatsApp with Twilio) | `signInWithOtp({ phone })`, `verifyOtp` | Off, needs an SMS provider |\n| OAuth | `signInWithOAuth({ provider })` | Off until a provider is configured |\n| Provider ID token (native Apple or Google sign-in) | `signInWithIdToken` | Off until the provider is configured |\n| Anonymous | `signInAnonymously` | Off |\n| SAML single sign-on, by email domain | `signInWithSSO({ domain })` or `signInWithSSO({ providerId })` | Off until `auth.sso.saml.enabled`. See [Single sign-on](https://www.supatype.com/docs/sso.html) |\n\nPassword reset is `resetPasswordForEmail`, and `updateUser` changes the email, password or user metadata of the signed-in user. Passwords must be at least 6 characters unless you raise `SUPATYPE_PASSWORD_MIN_LENGTH`.\n\n`signUp` takes `options.data` for user metadata, which comes back on `user.userMetadata`.\n\n`signInWithOtp` creates the user when they do not exist, unless you pass `options.createUser: false`. For a phone, pass `phone` and optionally `options.channel` (`\"sms\"` or `\"whatsapp\"`), then call `verifyOtp` with `type: \"sms\"`. `resend({ type, email })` or `resend({ type, phone })` sends a confirmation or code again, where `type` is `\"signup\"`, `\"sms\"`, `\"email_change\"` or `\"phone_change\"`.\n\nFor a password reset, wait for `initialize()` on the page the link opens, then call `updateUser({ password })`. A recovery link, or `verifyOtp` with `type: \"recovery\"`, emits `PASSWORD_RECOVERY` once the session exists.\n\n#### Auth errors\n\nAuth calls put the auth server's code in `error.code`, beside `message` and `status`. Branch on the code, not the message: `invalid_credentials`, `email_not_confirmed`, `weak_password`, `user_already_exists`, `email_exists`, and `otp_expired` for an expired link. `error.code` is absent only when the answer carried none, such as a gateway's HTML error page.\n\n#### Multi-factor\n\n`supatype.auth.mfa` has `enroll`, `challenge`, `verify`, `challengeAndVerify` and `unenroll`. TOTP authenticator apps are on by default. Phone factors are off by default and need an SMS provider.\n\n`enroll({ factorType: \"totp\" })` returns the factor's `id` and a QR code (`totp.qrCode`) and URI (`totp.uri`) to show the user. `challengeAndVerify({ factorId, code })` is `challenge` then `verify` in one call. Call the two separately when the code arrives later, as an SMS does. A verify raises the session to AAL2 and emits `MFA_CHALLENGE_VERIFIED`. `listFactors()` returns every factor in `all` and the verified ones in `totp` and `phone`. `getAuthenticatorAssuranceLevel()` reports the current and next level.\n\n#### Anonymous users\n\nAn anonymous sign-in creates a real user with a user id and a session. Turn it on with `SUPATYPE_EXTERNAL_ANONYMOUS_USERS_ENABLED=true`. Because the user has an id, an anonymous user passes `LoggedIn` and can own rows. The token carries `is_anonymous: true`.\n\n`signInAnonymously({ options: { data, captchaToken } })` takes optional metadata and a captcha token, and the user comes back with `isAnonymous: true`. The flag survives a reload: a restored session keeps it, and a session saved without it takes it from the token's `is_anonymous` claim.\n\n#### Keep anonymous users out\n\nTo let only registered users do something, test the claim as well as the sign-in:\n\n`typescript`:\n\n```ts\nimport type { All, Claim, Eq, Literal, LoggedIn } from \"@supatype/types\"\n\ntype Registered = All<[LoggedIn, Eq<Claim<\"is_anonymous\">, Literal<\"false\">>]>\n```\n\nUse it like any rule, for example `access: { read: LoggedIn, create: Registered }`, so a guest can read but only a registered user can create. The auth server puts `is_anonymous` in every access token it issues, `true` for a guest and `false` for a real account, so the rule admits exactly the users who signed up or added an email or phone. A token without the claim, such as one minted by your own code, is denied.\n\nWrite the literal as the string `\"false\"`: a claim is read as text, and that form works on every engine version. `Literal<false>` means the same thing on engines after 0.9.0, which read the claim as a JSON boolean when it is compared with a boolean. Engine 0.9.0 and earlier refuse it at push with `operator does not exist: text = boolean`.\n\nAnonymous users do not last forever. When the auth server's database cleanup is on (`SUPATYPE_DB_CLEANUP_ENABLED=true`, off by default), it deletes every anonymous user 30 days after the account was created, even one still in use. Rows whose user field declares `onDelete: \"cascade\"` are deleted with it, a `\"setNull\"` field is cleared, and a field without `onDelete` keeps an id that no longer matches a user. Prompt guests to add an email or phone before then: once they do, `is_anonymous` is `false` and the cleanup leaves them alone.\n\n### OAuth providers\n\nEach provider is switched on with environment variables named after it. For GitHub:\n\n`.env`:\n\n```ini\nSUPATYPE_EXTERNAL_GITHUB_ENABLED=true\nSUPATYPE_EXTERNAL_GITHUB_CLIENT_ID=your-client-id\nSUPATYPE_EXTERNAL_GITHUB_SECRET=your-client-secret\nSUPATYPE_EXTERNAL_GITHUB_REDIRECT_URI=<your API URL>/auth/v1/callback\n```\n\nThe redirect URI is the auth service's callback: `/auth/v1/callback` on your API URL. Your API URL is `API_EXTERNAL_URL` in `.env`: under Docker, the project's gateway (`http://localhost:` and its `SUPATYPE_KONG_PORT`); with the native provider, the server itself (`http://localhost:18471` unless you set `server.port`). Register the same URL with the provider. A provider with no client id, secret or redirect URI is refused when someone tries to use it.\n\nSupported provider names: `apple`, `azure`, `bitbucket`, `discord`, `facebook`, `figma`, `fly`, `github`, `gitlab`, `google`, `kakao`, `keycloak`, `linkedin_oidc`, `notion`, `slack_oidc`, `snapchat`, `spotify`, `twitch`, `twitter`, `x`, `workos` and `zoom`. The auth server also accepts `vercel_marketplace`, and the older `linkedin` and `slack`, which the `_oidc` versions replace. Upper-case the name for the variable, so `linkedin_oidc` becomes `SUPATYPE_EXTERNAL_LINKEDIN_OIDC_ENABLED`.\n\n#### The sign-in round trip\n\n`typescript`:\n\n```ts\nconst { data, error } = await supatype.auth.signInWithOAuth({\n provider: \"github\",\n options: { redirectTo: \"http://localhost:5173/auth/callback\" },\n})\nif (error) throw new Error(error.message)\nwindow.location.assign(data.url)\n\n// On /auth/callback\n// The client finishes the sign-in in the URL when it starts; initialize() waits for that.\nconst { error: callbackError } = await supatype.auth.initialize()\nif (callbackError) console.error(callbackError.message)\n```\n\n`signInWithOAuth` returns the URL; it does not navigate for you. `redirectTo` must be on the same host as `SITE_URL`, a loopback address, or match an entry in `SUPATYPE_URI_ALLOW_LIST` (comma-separated, globs allowed). Anything else sends the user to `SITE_URL` instead. An app on another domain, or a mobile deep link, needs an allow list entry.\n\nThe web default is the implicit flow, which returns tokens in the URL fragment. Pass `flowType: \"pkce\"` in the options for a code exchange instead; mobile apps should always use PKCE. The client finishes either from the URL when it starts, and removes the tokens from the address bar; `initialize()` resolves once it has, with any `error` the provider sent back. Do not call `getSessionFromUrl` as well: the URL no longer carries the tokens by then, so it answers with an error.\n\n`exchangeCodeForSession(code)` does the PKCE exchange on its own. `options.scopes` asks the provider for extra scopes.\n\n### Sessions and tokens\n\nA session is a short-lived access token and a refresh token.\n\n- The access token is a JWT signed with `JWT_SECRET`, valid for one hour. The client sends it as `Authorization: Bearer` on every request.\n- The client refreshes it about a minute before it expires, and again on load if a saved session has already expired. If the refresh fails, the session is cleared rather than kept with a dead token.\n- Refresh tokens rotate: each refresh issues a new one.\n- `signOut` takes no arguments. It ends every session the user has on the server, not just this device's, and clears it locally.\n\nIn the browser the session is saved to `localStorage` under `supatype.auth.session` and mirrored to a cookie named `st-auth-token`, which `@supatype/ssr` reads on the server. Set `auth: { persistSession: false }`, `storageKey` or `cookiePrefix` on `createClient` to change this. On React Native, `createNativeClient` from `@supatype/react-native` stores the session in `expo-secure-store` or AsyncStorage.\n\n#### Auth events\n\n`onAuthStateChange` calls back at once with `SIGNED_IN` or `SIGNED_OUT`, then on each of these:\n\n| Event | When |\n| --- | --- |\n| `SIGNED_IN` | A session starts while signed out |\n| `SIGNED_OUT` | The session is cleared |\n| `TOKEN_REFRESHED` | The session is replaced while signed in |\n| `USER_UPDATED` | `updateUser` succeeded. The session passed to the callback carries the updated user |\n| `PASSWORD_RECOVERY` | A password reset link or code produced a session, after its `SIGNED_IN` |\n| `MFA_CHALLENGE_VERIFIED` | An MFA verify raised the session to AAL2 |\n\n#### What the token says\n\n| Claim | Meaning |\n| --- | --- |\n| `sub` | The user id |\n| `role` | The database role the API runs the request as: `authenticated` for a signed-in user |\n| `email`, `phone` | The user's contact details |\n| `app_metadata` | Set only through the admin API. Holds the application role that `Role<>` checks |\n| `user_metadata` | Set by the user, for example through `signUp` options or `updateUser`. Never trust it for access |\n| `aal`, `amr` | Assurance level and how the user signed in, for MFA |\n| `session_id`, `is_anonymous` | The session, and whether the user signed in anonymously |\n\nRequests made with only the anon key have no user. Requests made with the service role key pass every access rule; keep that key on the server.\n\n### Access rules\n\nThe access rules you declare in the schema compile to Postgres row level security that reads the verified token. Every request runs with the token's claims available to the database, so the same rule holds for REST, GraphQL and realtime. The rules themselves are listed on the [schema page](https://www.supatype.com/docs/schema.html#access).\n\n`schema/index.ts`:\n\n```ts\nimport type { Model, UUID, SupatypeAuthUserId, Public, LoggedIn, Owner } from \"@supatype/types\"\n\nexport type Profile = Model<{\n id: SupatypeAuthUserId\n display_name: string\n}, {\n access: { read: Public; create: Owner<\"id\">; update: Owner<\"id\">; delete: Owner<\"id\"> }\n}>\n\nexport type Bookmark = Model<{\n id: UUID\n owner_id: SupatypeAuthUserId\n post_id: UUID\n}, {\n access: { read: Owner<\"owner_id\">; create: LoggedIn; update: Owner<\"owner_id\">; delete: Owner<\"owner_id\"> }\n}>\n```\n\nA profile keyed on the user id lets each user write only their own row. Bookmarks are private to whoever saved them.\n\n#### What the rules become\n\nThe engine installs a small set of SQL functions in the `auth` schema, and every policy calls them:\n\n| Rule or function | SQL |\n| --- | --- |\n| `auth.uid()` | The token's `sub` as a `uuid`, or `NULL` when there is no user |\n| `auth.role()` | `app_metadata.role`, falling back to the top-level `role` claim, then `anon` |\n| `auth.claim(path)` | A nested claim by dotted path, used by `Claim<>` |\n| `LoggedIn` | `(SELECT auth.uid()) IS NOT NULL` |\n| `Owner<\"owner_id\">` | `(SELECT auth.uid()) = \"owner_id\"` |\n| `Role<\"admin\">` | `(SELECT auth.role()) = 'admin'` |\n\nBecause `auth.uid()` is `NULL` for a request with no user, an owner rule never matches an anonymous request, even on a row whose owner column is empty. The calls are wrapped in `SELECT` so Postgres evaluates them once per query rather than once per row.\n\nTo give a user an application role for `Role<>`, set `app_metadata.role` through the auth admin API with the service role key. Users cannot set it themselves.\n\n### Pre-built UI\n\nTwo packages give you ready-made sign-in screens. Both use `useAuth()` from `@supatype/react`, so they must sit inside a `<SupatypeProvider>`.\n\n| Package | Components |\n| --- | --- |\n| `@supatype/react-auth` | `LoginForm`, `SignUpForm`, `ForgotPasswordForm`, `UpdatePasswordForm`, `MagicLinkForm`, `OAuthButton`, `SSOForm` (see [Single sign-on](https://www.supatype.com/docs/sso.html#sign-in)) |\n| `@supatype/react-native-auth` | `LoginForm`, `SignUpForm`, `MagicLinkForm`, `OAuthButton`, `ResetPassword`, `AuthGate`, `AuthThemeProvider` |\n\n#### Web\n\n`src/SignIn.tsx`:\n\n```tsx\nimport { SupatypeProvider } from \"@supatype/react\"\nimport { LoginForm, OAuthButton } from \"@supatype/react-auth\"\nimport { supatype } from \"./supatype\"\n\nexport function SignIn() {\n return (\n <SupatypeProvider client={supatype}>\n <LoginForm onSuccess={() => window.location.assign(\"/\")} />\n <OAuthButton provider=\"github\" redirectTo=\"http://localhost:5173/auth/callback\" />\n </SupatypeProvider>\n )\n}\n```\n\nThe web forms are plain, unstyled markup: pass `className` and `labels` to fit your app. `OAuthButton` has a default style and an icon for GitHub, Google and Apple, which a `className` replaces. It sends the browser to the provider; the client finishes the sign-in on your callback page by itself, and `initialize()` tells you how it went.\n\n#### React Native\n\n`App.tsx`:\n\n```tsx\nimport * as SecureStore from \"expo-secure-store\"\nimport * as WebBrowser from \"expo-web-browser\"\nimport * as Linking from \"expo-linking\"\nimport { SupatypeProvider } from \"@supatype/react\"\nimport { createNativeClient } from \"@supatype/react-native\"\nimport { AuthGate, LoginForm, OAuthButton } from \"@supatype/react-native-auth\"\n\nconst client = createNativeClient({\n url: process.env.EXPO_PUBLIC_SUPATYPE_URL!,\n anonKey: process.env.EXPO_PUBLIC_SUPATYPE_ANON_KEY!,\n secureStore: SecureStore,\n})\nconst redirectTo = Linking.createURL(\"auth/callback\")\n\nexport default function App() {\n return (\n <SupatypeProvider client={client}>\n <AuthGate fallback={<><LoginForm /><OAuthButton provider=\"google\" redirectTo={redirectTo} webBrowser={WebBrowser} /></>}>\n <>{/* your signed-in screens */}</>\n </AuthGate>\n </SupatypeProvider>\n )\n}\n```\n\n`AuthGate` renders its children only when there is a session, and `fallback` otherwise. The native `OAuthButton` uses PKCE and opens the provider in `expo-web-browser`. Wrap the tree in `AuthThemeProvider` to change colours and spacing.\n\n### Configuration\n\n#### Email delivery\n\nConfirmation, magic link and reset emails go through the `email` block in `supatype.config.ts`:\n\n`supatype.config.ts`:\n\n```ts\nemail: {\n provider: \"smtp\", // \"console\" | \"smtp\" | \"resend\" | \"ses\"\n smtp: { host: \"smtp.example.com\", port: 587, user: \"apikey\", pass: process.env.SMTP_PASS, admin_email: \"no-reply@example.com\" },\n},\n```\n\n> **CONSOLE SENDS NOTHING:** `console`, the default, logs that a message would have been sent but leaves out the body, so the link is not in the log. To try magic links or password reset, configure a real provider.\n\nOn a self-hosted stack, for Resend set `email.resend_api_key` and `email.resend_from` in the `email` block above (a value set by hand in `.env` is replaced from `supatype.config.ts`). For SES set `email.ses_from`; credentials come from the environment's AWS configuration.\n\nOn Supatype Cloud there is no `.env` and no ambient AWS configuration, so SES takes all of its settings from the `email` block, and a push that leaves one out is refused:\n\n`supatype.config.ts`:\n\n```ts\nemail: {\n provider: \"ses\",\n ses_from: \"no-reply@example.com\", // required: the sender address, verified in SES\n ses_access_key_id: env(\"SES_ACCESS_KEY_ID\"), // required: name an environment variable, never the key itself\n ses_secret_access_key: env(\"SES_SECRET_ACCESS_KEY\"), // required, the same way\n ses_region: \"eu-west-2\", // optional\n},\n```\n\nWithout `ses_from` the server cannot send, so mail would be dropped while requests still succeed. That is why Cloud refuses the push and names `email.ses_from`.\n\n#### Email sign-in and confirmation\n\nTwo keys under `auth.email` in `supatype.config.ts` decide what email-and-password sign-in does:\n\n`supatype.config.ts`:\n\n```ts\nauth: {\n email: { enabled: true, enableConfirmations: true },\n},\n```\n\n- `enabled`, default `true`. `false` turns email-and-password sign-up and sign-in off at the auth server, and magic links and password recovery with them, for a project that signs in only with OAuth or SAML.\n- `enableConfirmations`: whether a new sign-up has to click a link in an email before it can sign in. Unset, a self-hosted stack (`supatype self-host compose`) sends the link and local dev, Docker or native, confirms the sign-up at once. `true` or `false` sets it for every stack.\n\n`supatype dev` and `supatype self-host compose` pass both to the auth server on every start, as `SUPATYPE_EXTERNAL_EMAIL_ENABLED` and `SUPATYPE_MAILER_AUTOCONFIRM`. Either variable set in the project's `.env` wins over the config for that stack; the CLI never writes them there. Studio shows each under **Authentication > Configuration**, with the key that sets it.\n\n#### Rate limits\n\n`auth.rateLimits` caps how often one client may call the auth server:\n\n`supatype.config.ts`:\n\n```ts\nauth: {\n rateLimits: { verify: 10, otp: 5 },\n},\n```\n\nEach limit except `smsSent` counts requests per client IP address. The address is the one the gateway forwards: Kong writes `X-Real-IP` from the connection and replaces any value the client sent, so a client cannot pick its own. The server believes a forwarded address only on a request that carries the project's forwarding secret, which Kong adds and no client holds. Any other request counts against the address of its connection, whatever `St-Forwarded-For`, `X-Real-IP` or `X-Forwarded-For` it carries, and the IP recorded in audit logs follows the same rule. A client over a limit gets 429 with error code `over_request_rate_limit` until the window lets it in again.\n\n| Key | What it counts, per client | Window | Default |\n| --- | --- | --- | --- |\n| `otp` | Sign-up and sign-in requests: `/signup` (not anonymous), `/otp`, magic links, password recovery, `/resend` and updating the signed-in user. Each of these counts on its own. It counts requests, not emails | 5 minutes | 30 |\n| `verify` | Requests to `/verify`, which checks the code or link from an email or SMS, whether the code is right or not | 5 minutes | 30 |\n| `tokenRefresh` | Requests to `/token`: password sign-in, refreshing a session and the other grants | 5 minutes | 150 |\n| `sso` | Requests that start a SAML sign-in | 5 minutes | 30 |\n| `mfa` | Multi-factor challenges, and verifies, each counted on its own | 1 minute | 15 |\n| `anonymousUsers` | Anonymous sign-ins | 1 hour | 30 |\n| `smsSent` | SMS messages the server sends, across every client together | 1 hour | 30 |\n\nA limit of N lets one client make N requests at once, and then one more each time the window divided by N passes. Every per-client limit works that way, over its own window: a limit of 3 lets one client make 3 requests at once, never more. A limit below 1 still lets one through. How many emails the server sends an hour is a separate limit: `SUPATYPE_RATE_LIMIT_EMAIL_SENT` on self-host, and the platform's on Cloud.\n\nOn self-host each key renders as a `SUPATYPE_RATE_LIMIT_*` variable for the server (`mfa` as `SUPATYPE_MFA_RATE_LIMIT_CHALLENGE_AND_VERIFY`), and a value in `.env` wins. Behind a proxy in front of Kong, Kong sees the proxy's address, so every client would share one count: set `SUPATYPE_RATE_LIMIT_HEADER` in `.env` to a header that proxy writes from the connection, and only if nothing else can reach Kong.\n\nThe forwarding secret is `SUPATYPE_FORWARDING_SECRET` in `.env`. `supatype init` generates it, and a project that predates it gets one on its next `dev` or `self-host` command. It is given to the server (as `SUPATYPE_SECURITY_FORWARDING_SECRET`), to Kong and to the functions worker, and to nothing else: the worker removes it from the environment before it loads your functions, so function code cannot read it. When a function calls the project's own address, the worker passes on the end user's address with it, so a function that signs a user in is counted against that user and not against the worker. Under Docker the worker reaches Kong on a second port, 8100, that is never published to the host: Kong leaves the two headers alone there, where it removes them on the public port, and adds no secret of its own, so code that reaches 8100 without the secret is still counted against its own connection. Keep it out of version control like the other secrets in `.env`, and never log it. A server with no secret set believes forwarded addresses from any sender, as before, and says so once when it starts.\n\n#### Environment variables\n\nThe server reads the project's `.env` when it starts, so `SUPATYPE_*` auth variables placed there take effect after a restart. In the Docker stacks, a few values are set by the generated Compose file and are read from the plain names shown.\n\n| Variable | What it does |\n| --- | --- |\n| `JWT_SECRET` | Signs every token. Required for self-host. Change it and every issued token, including the anon and service role keys, stops working |\n| `ANON_KEY`, `SERVICE_ROLE_KEY` | Keys signed with `JWT_SECRET`. `supatype keys --write` generates them |\n| `SITE_URL` | Self-host: your app's URL, the default place users land after confirming or signing in |\n| `SUPATYPE_URI_ALLOW_LIST` | Other URLs `redirectTo` may point at, comma-separated |\n| `DISABLE_SIGNUP` (self-host), `SUPATYPE_DISABLE_SIGNUP` (native dev) | `true` stops new sign-ups |\n| `SUPATYPE_EXTERNAL_EMAIL_ENABLED` | `false` turns email-and-password sign-in off. Set from `auth.email.enabled`; a value in `.env` wins |\n| `SUPATYPE_MAILER_AUTOCONFIRM` | `true` skips email confirmation. Set from `auth.email.enableConfirmations`: when that is unset, off in self-host and on in dev. A value in `.env` wins: set it there and restart the stack |\n| `SUPATYPE_EXTERNAL_<PROVIDER>_*` | OAuth providers, see [above](https://www.supatype.com/docs/auth.html#oauth) |\n| `SUPATYPE_EXTERNAL_ANONYMOUS_USERS_ENABLED` | Allow anonymous sign-in |\n| `SUPATYPE_EXTERNAL_EMAIL_MAGIC_LINK_ENABLED` | `false` turns magic links off |\n| `SUPATYPE_PASSWORD_MIN_LENGTH` | Minimum password length, at least 6 |\n| `SUPATYPE_EXTERNAL_PHONE_ENABLED`, `SUPATYPE_SMS_PROVIDER` | Phone sign-in. The provider is `twilio`, `twilio_verify`, `messagebird`, `textlocal` or `vonage` |\n\n> **SELF-HOST:** Self-host sends a confirmation link with every new email sign-up. Configure email delivery before you open sign-up to the public: with the `console` provider no link reaches anyone, so a new user has no way to confirm their address.\n\nTo create users from a seed file, see [Seeding users](https://www.supatype.com/docs/seeding.html#users).\n\n## Single sign-on\n\nSource: https://www.supatype.com/docs/sso.html\n\nSAML 2.0 single sign-on lets people sign in to your app through their organisation's identity provider, such as Okta, Microsoft Entra ID, Google Workspace or Keycloak. The provider is chosen by the domain of the user's email address.\n\nThe auth server is the SAML service provider. You turn SAML on once in `supatype.config.ts`. Identity providers are runtime data, usually one per customer, so you register them with `supatype sso`, in Studio, or through the admin API, never in the config. SAML works on `supatype dev` and on self-hosted stacks. It is not on Supatype Cloud yet.\n\n### Turn SAML on\n\n`supatype.config.ts`:\n\n```ts\nauth: {\n sso: {\n saml: { enabled: true },\n },\n},\n```\n\nRestart the stack to apply it: stop and start `supatype dev`, or run `supatype self-host compose up -d` on a server. The section takes these fields:\n\n| Field | What it does |\n| --- | --- |\n| `enabled` | Required. `true` turns SAML on, and the CLI generates the signing key the first time it sees it |\n| `allowEncryptedAssertions` | Accept encrypted assertions, and publish the key for encryption in the service provider metadata |\n| `relayStateValidity` | How long, in seconds, a sign-in your app starts may take at the identity provider. The server's default is 120 |\n| `rateLimitAssertion` | How many assertions the server accepts from one client every 5 minutes. The server's default is 15 |\n| `externalUrl` | The service provider's base URL, under which `/sso/saml/metadata` and `/sso/saml/acs` are served. The default is your API URL plus `/auth/v1` |\n\nA `SUPATYPE_SAML_*` value in `.env` wins over the config's. While SAML is off, the sign-in routes and the metadata answer 404 with `SAML 2.0 is disabled`. The admin routes keep working, so you can register providers before you turn it on, and every `supatype sso` command warns that SAML is off.\n\n### The signing key\n\nThe service provider signs its requests with an RSA key, and its certificate is made from that key alone. The first `supatype dev` or `supatype self-host compose up` with SAML on writes a new key to the project's `.env` as `SUPATYPE_SAML_PRIVATE_KEY`. On a self-hosted server that is the `.env` in the server's project directory. The CLI never prints the key, and never replaces one that is there.\n\nThe key never goes in `supatype.config.ts`, which is committed: a `privateKey` field under `auth.sso.saml` is refused with the variable to use instead. The generated Compose file names the variable and refuses to start without it, but never holds the value.\n\n> **KEEP THE KEY:** Every identity provider you set up trusts the certificate made from this key. Back `.env` up with your other secrets. A lost or changed key breaks every provider until each one is given the new metadata. To change it on purpose, [rotate it](https://www.supatype.com/docs/sso.html#rotate).\n\n### What to give the identity provider\n\nAn identity provider asks for the service provider's entity ID and its Assertion Consumer Service (ACS) URL, or for its metadata, which holds both and the certificate:\n\n| Value | Where |\n| --- | --- |\n| Entity ID and metadata URL (the same address) | `<API URL>/auth/v1/sso/saml/metadata` |\n| Metadata as a file | `<API URL>/auth/v1/sso/saml/metadata?download=true` |\n| ACS URL (HTTP-POST binding) | `<API URL>/auth/v1/sso/saml/acs` |\n| NameID format | Persistent is requested; email address is accepted too |\n\n`supatype sso info` prints the entity ID, ACS URL and metadata URL for the local stack, or for the linked deployment. With SAML on, it also reads the served metadata and prints the signing certificate as PEM under `Signing certificate (SHA-256 <fingerprint>):`, for an identity provider that asks for the certificate rather than the metadata. During a [key rotation](https://www.supatype.com/docs/sso.html#rotate) it prints the next one too, under `Next signing certificate, published for the key rotation`. While SAML is off it warns once that SAML is off, and that these values are not served until it is on: the metadata URL answers 404. Have the identity provider send an email attribute (`email` or `mail`), or use the email address as the NameID, and sign the assertion or the whole response. A stable user ID in the `urn:oasis:names:tc:SAML:attribute:subject-id` attribute is used in preference to the NameID when it is sent.\n\n### Register an identity provider\n\n```sh\n$ supatype sso add acme --metadata-url https://idp.acme.com/metadata --domains acme.com\n$ supatype sso list\n$ supatype sso show acme\n```\n\nThe name you give `add` is how every other `sso` command refers to the provider. It may use letters, digits, `.`, `_` and `-`, starting with a letter or digit. The commands reach the linked self-hosted deployment when the project is linked, and the local stack otherwise, which must be running. They call the admin API with the service role key from `.env`, or the link's token.\n\n| Flag (`add` and `update`) | What it sets |\n| --- | --- |\n| `--metadata-url <url>` | The identity provider's metadata URL. The server fetches it, and fetches it again when the copy it keeps goes stale |\n| `--metadata-file <path>` | The metadata XML from a file, instead of a URL. Update it by hand when the identity provider changes its certificate |\n| `--domains <list>` | Email domains that sign in through this provider, comma-separated. On `update` it replaces the list. A domain belongs to one provider only |\n| `--attribute-mapping-file <path>` | JSON that maps assertion attributes to user metadata: `{ \"keys\": { \"<field>\": { \"name\": \"<attribute>\" } } }`, each entry with `name` or `names`, and optional `default` and `array` |\n| `--name-id-format <format>` | The NameID format to request: `persistent`, `emailAddress`, `transient` or `unspecified` |\n\n`add` needs `--metadata-url` or `--metadata-file`, never both. `update <name>` changes only what its flags give, in place, and new metadata must keep the provider's entity ID. `remove <name>` asks first, or takes `-y`.\n\n> **CHANGE, DO NOT RE-ADD:** A user who signed in through a provider is tied to that provider's ID. After `remove`, those users can no longer sign in that way, and adding a provider with the same name later makes a new one that their accounts are not linked to. Use `update` to change a provider.\n\n#### The server fetches the metadata URL\n\n`--metadata-url` is fetched by the Supatype server, not by the CLI. Under Docker the server runs in a container, where `localhost` is the container itself, so the identity provider must be reachable from inside the server's container. When it is not, `add` or `update` fails with a 400 (`saml_metadata_fetch_failed`) that names the host and the reason:\n\n```sh\nThe server could not fetch SAML metadata from localhost:8080: connection refused. The server fetches metadata_url itself, so the URL must be reachable from the server, not only from your machine\n```\n\nThe reason is one of `connection refused`, `the host name could not be resolved`, `its TLS certificate is not trusted`, `timed out after 10s`, `it answered with HTTP status <N>` and `the response is not SAML metadata XML`. Metadata given with `--metadata-file` that is not SAML metadata is refused with `metadata_xml is not SAML metadata XML`.\n\nAn identity provider such as Keycloak builds its entity ID and sign-in URLs from the host it was reached on. Fetch the metadata through the same name and port the browser uses, or the server keeps endpoints the browser cannot open and an entity ID the provider's responses do not carry. For an identity provider running on your machine, either attach its container to the stack's Docker network under a name the browser also resolves to it (a `*.localhost` name resolves to your machine in browsers), or download the metadata in the browser and register it with `--metadata-file`.\n\nA metadata URL must be HTTPS. Plain `http://` is accepted only on a dev stack (`supatype dev`), for a local identity provider; a self-hosted stack refuses it with `metadata_url is not a HTTPS URL`.\n\n### Verify a domain\n\nA provider with domains may only sign in email addresses on those domains. Any other address is refused with `SAML Assertion email is not on a domain of this identity provider`. A domain routes sign-ins as soon as it is added, but it is not verified until you prove you own it, and only a verified domain links a sign-in to an account that already exists.\n\n```sh\n$ supatype sso verify-domain acme acme.com\nacme.com is not verified yet. Add this DNS record where the domain's DNS is managed:\n\n _supatype-challenge.acme.com TXT supatype-domain-verification=...\n\nNo TXT record was found at _supatype-challenge.acme.com.\nDNS changes can take a while to be seen. Check again with: supatype sso verify-domain acme acme.com\n```\n\nThe first run issues the domain's token and prints the TXT record to add at `_supatype-challenge.<domain>`. Each run checks DNS, and the command exits 1 until the record holds the token. Once seen, the domain stays verified, and the record may be removed. There is no periodic check after that. `sso list` and `sso show` mark each domain verified or not verified.\n\nOn a dev stack, a domain ending in `.supatype.test` counts as verified with no DNS lookup, so you can try linking locally. It still reads as not verified until `verify-domain` has run for it. A self-hosted stack always checks DNS.\n\n#### What verification changes\n\nThe first time someone signs in through a provider, the server looks for an existing account with the same email: a password, magic link, phone or OAuth account, not another SSO user.\n\n- No account: a new one is created, verified domain or not.\n- An account, and the email's domain is verified for this provider: the sign-in is linked to that account. It keeps its ID, its email and every way it already signed in, and gains an `sso:<provider ID>` identity.\n- An account, and the domain is not verified: the sign-in is refused with `This email already has an account. Ask your administrator to verify the domain so they can be linked.` No second account is ever made for the same address.\n- Several accounts whose email differs only in letter case: the one whose email is exactly the address the identity provider sent, letter for letter, is the one considered. When none matches exactly, the sign-in is refused with `More than one account has this email. Ask your administrator to merge them before signing in with SSO.`\n\n### Sign users in\n\nA sign-in your app starts asks the server for the identity provider's URL by the user's email domain, or by the provider's ID, and sends the browser there:\n\n`typescript`:\n\n```ts\nconst { error } = await supatype.auth.signInWithSSO({\n domain: \"acme.com\",\n options: { redirectTo: window.location.href },\n})\nif (error) console.error(error.message)\n```\n\nPass `{ domain }` or `{ providerId }`, never both. `providerId` is the provider's UUID, the `ID` line of `sso show`, not its name. A domain with no provider is refused with `No SSO provider assigned for this domain`, and a disabled provider with `SSO Provider is currently disabled`; the page stays where it is. `options` also takes `captchaToken`, `skipBrowserRedirect` to get the URL back without navigating, and `flowType`. `useAuth()` from `@supatype/react` has `signInWithSSO` too.\n\nThe sign-in uses PKCE by default, unlike `signInWithOAuth`. The browser comes back to `redirectTo` with `?code=` in the address and no tokens, and the client exchanges the code when it starts, with the verifier it saved in this browser when the sign-in began. So `redirectTo` must be a page of the same app that creates the client, opened in the same browser: usually the page that started the sign-in. It is honoured on `SITE_URL`'s host, a loopback address, or an entry in `SUPATYPE_URI_ALLOW_LIST`; without it, or for any other address, the browser lands on `SITE_URL`. `initialize()` resolves once the exchange is done, as it does for [OAuth](https://www.supatype.com/docs/auth.html#oauth).\n\n#### The pre-built form\n\n`src/SignInWithSSO.tsx`:\n\n```tsx\nimport { SupatypeProvider } from \"@supatype/react\"\nimport { SSOForm } from \"@supatype/react-auth\"\nimport { supatype } from \"./supatype\"\n\nexport function SignInWithSSO() {\n return (\n <SupatypeProvider client={supatype}>\n <SSOForm redirectTo={window.location.href} onError={(error) => console.error(error.message)} />\n </SupatypeProvider>\n )\n}\n```\n\n`SSOForm` asks for a work email and starts the sign-in for its domain. It takes `redirectTo`, `onSuccess` (called with the identity provider's URL), `onError`, `className`, `classNames` and `labels`, like the other [auth forms](https://www.supatype.com/docs/auth.html#ui). A refusal from the server, on the way out or the way back, shows above the field and goes to `onError`.\n\n#### Sign-ins the identity provider starts\n\nWhen a user opens your app from the identity provider's dashboard, there is no sign-in in your app to come back to. The server sends the browser to `SITE_URL`, or to a RelayState URL the provider sends when it is allowed, with the tokens in the fragment (`#access_token=...`), since no browser holds a PKCE verifier for it. The client accepts this whatever its `flowType`: it stores the session and clears the fragment. So the page at `SITE_URL` must create the client.\n\nA sign-in the server refuses on the way back, from either side, lands on `SITE_URL` with `error`, `error_code` and `error_description` in the query, and `initialize()` resolves with that error.\n\n### Rotate the signing key\n\nRotation runs two keys side by side, so identity providers can take the new certificate before the old one stops working.\n\n#### 1. Create the next key\n\n```sh\n$ supatype sso rotate-key\n```\n\nThis writes `SUPATYPE_SAML_NEXT_PRIVATE_KEY` to `.env`, or keeps the one already there.\n\n#### 2. Restart the stack\n\nRestart `supatype dev`, or run `supatype self-host compose up -d`, so the server loads the next key. Until then nothing has changed. From the restart, the metadata lists two certificates, the current one and the next. Requests are still signed with the current key, and encrypted assertions are decrypted with either.\n\n#### 3. Give every identity provider the new metadata\n\nHave each provider fetch the metadata again, upload the new file, or take the next certificate that `supatype sso info` prints during the rotation. Providers that check request signatures must take the new certificate before the next step.\n\n#### 4. Promote the next key\n\n```sh\n$ supatype sso rotate-key --promote\n```\n\nIt asks first, or takes `-y`; with no terminal it needs `-y`. The next key replaces `SUPATYPE_SAML_PRIVATE_KEY`, and `SUPATYPE_SAML_NEXT_PRIVATE_KEY` is removed.\n\n#### 5. Restart again\n\nAfter this restart the server signs with the new key and the metadata lists one certificate. A provider that never took the new certificate now fails its signature check.\n\nOn a project linked to a self-hosted deployment, the key is in the server's environment, not your `.env`, so `rotate-key` prints these steps for you to run in the server's project directory instead.\n\n### In Studio\n\nAuthentication > SSO lists the providers with their entity IDs, domains and status, and, while SAML is on, the entity ID and ACS URL to give an identity provider. There you can add a provider from a metadata URL or XML, edit it, disable and enable it, remove it, and verify a domain: the Verify dialog shows the TXT record and checks it. The page says when SAML is off.\n\nOnly owners and admins can change providers and verify domains; on a self-hosted project that means admins. The server enforces it, not just the page. Developers and viewers see the page read-only, with `Only owners and admins can change SSO providers.` Editors have no SSO page. See [Studio roles](https://www.supatype.com/docs/studio-roles.html). The Users list marks each user who signed in through SAML with `sso:` and their provider's name, for example `sso:acme`. A provider that has been removed, or was added without a name, shows the first block of its ID instead.\n\nWhile SAML is on, Studio's own sign-in page offers **Sign in with SSO**: an admin enters their work email and goes to the identity provider for its domain, then comes back to Studio, never to the app's site URL. Studio still lets in only people with a [Studio role](https://www.supatype.com/docs/studio-roles.html). With `auth.email.enabled: false`, the setting for a project that signs in only through SSO, Studio's email and password form is hidden, leaving single sign-on and any OAuth providers. The first SSO sign-in to an existing account removes its password, so admins of an SSO project sign in to Studio this way too.\n\n### The admin API\n\nAn app that lets its own customers set up SSO calls the auth server's admin API from its server, with the service role key. Never call it from the browser: the service role key passes every access rule.\n\n```sh\n$ curl -X POST https://api.example.com/auth/v1/admin/sso/providers \\\n -H \"Authorization: Bearer $SERVICE_ROLE_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"type\":\"saml\",\"resource_id\":\"acme\",\"metadata_url\":\"https://idp.acme.com/metadata\",\"domains\":[\"acme.com\"]}'\n```\n\n| Route under `/auth/v1` | What it does |\n| --- | --- |\n| `GET /admin/sso/providers` | Lists providers as `{ \"items\": [...] }`, without their metadata XML. Filter with `?resource_id=` or `?resource_id_prefix=` |\n| `POST /admin/sso/providers` | Creates one. `type: \"saml\"`, and `metadata_url` or `metadata_xml`; optional `domains`, `attribute_mapping`, `name_id_format`, `resource_id` and `disabled` |\n| `GET /admin/sso/providers/{id}` | One provider, with its domains and whether each is verified |\n| `PUT /admin/sso/providers/{id}` | Changes the fields given. `domains` replaces the list, new metadata must keep the entity ID, and `disabled: true` turns the provider off |\n| `DELETE /admin/sso/providers/{id}` | Removes the provider |\n| `POST /admin/sso/providers/{id}/domains/{domain}/verify` | Issues the domain's token the first time, checks DNS, and answers `domain`, `verified`, `verified_at`, the `challenge` record (`name` and `value`) and what DNS returned in `found` |\n\n`{id}` is the provider's UUID, or `resource_` followed by its `resource_id`: `resource_acme`. `resource_id` is the name `supatype sso` uses, so give each customer's provider a stable one and change the provider with `PUT` rather than deleting and creating it again. The admin routes work while SAML is off.\n\n## Storage\n\nSource: https://www.supatype.com/docs/storage.html\n\nDeclare buckets in your schema, point file and image fields at them, and upload through the client. Who may read, upload, overwrite and delete is decided by Postgres from the bucket's rules.\n\nPre-1.0: APIs and config may change between releases.\n\n### Declare a bucket\n\nA bucket is a type alias for `Bucket<\"id\", { ... }>` in your schema. The [schema page](https://www.supatype.com/docs/schema.html#buckets) has the short version. Every key in the second argument is optional.\n\n`schema/index.ts`:\n\n```ts\nimport type { Bucket, BucketLoggedIn, BucketOwner, BucketRole } from \"@supatype/types\"\n\nexport type Attachments = Bucket<\"attachments\", {\n accessMode: \"private\"\n accept: [\"application/pdf\", \"image/*\"]\n maxSize: \"20MB\"\n access: {\n read: BucketOwner\n create: BucketLoggedIn\n update: BucketOwner\n delete: BucketRole<\"admin\">\n }\n}>\n```\n\n| Key | What it does |\n| --- | --- |\n| `accessMode` | `\"public\"`, `\"private\"` or `\"custom\"`. Defaults to `\"private\"`. Only `\"public\"` serves files on a public URL. `\"custom\"` reads like `\"private\"` and is for buckets that set `s3BucketPolicy`. |\n| `maxSize` | Largest file accepted, written as `\"500KB\"`, `\"20MB\"` or `\"1GB\"`. Units are B, KB, MB and GB, counted in 1024s. Anything else fails the push. |\n| `accept` | Content types the bucket takes. Exact types such as `\"image/png\"`, or a wildcard such as `\"image/*\"`. Leave it out to accept any type. |\n| `access` | The `read`, `create`, `update` and `delete` rules, covered [below](https://www.supatype.com/docs/storage.html#access). Any other key fails the push. |\n| `s3BucketPolicy` | A raw S3 bucket policy as a JSON string, applied to the object store bucket in place of the default. It needs an S3 bucket per bucket, so [single-bucket mode](https://www.supatype.com/docs/storage.html#own-bucket) never applies it: there one policy would cover every bucket at once. It is applied exactly as written, so its `Resource` names the S3 bucket, which is `S3_BUCKET_PREFIX` then the bucket's id: with the prefix `acme-prod-`, the bucket `avatars` needs `arn:aws:s3:::acme-prod-avatars/*`. |\n\n`supatype push` and `supatype dev` register each bucket and write its settings. Changing `maxSize`, `accept` or `accessMode` and pushing again updates the bucket. Declaring the same bucket id twice with different settings fails the push.\n\n### File and image fields\n\n`ImageAsset<Bucket>` and `FileAsset<Bucket>` are fields that point at a file in a bucket. The column is JSONB holding the bucket and the path, and the generated type is `StorageReference`:\n\n`supatype/generated`:\n\n```ts\nexport type StorageReference = {\n bucket: string\n path: string\n}\n```\n\nThe field stores a reference, not the file. Upload the file first, then write its path to the row:\n\n`typescript`:\n\n```ts\nconst path = `${userId}/${file.name}`\nconst { error: uploadError } = await supatype.storage.from(\"attachments\").upload(path, file)\nif (uploadError) throw new Error(uploadError.message)\n\nawait supatype.from(\"post\").update({ attachment: { bucket: \"attachments\", path } }).eq(\"id\", postId)\n```\n\n- Always name the bucket. Without one, `ImageAsset` points at a bucket called `images` and `FileAsset` at one called `assets`, and neither exists unless you declare it.\n- `ImageAsset<Covers, { localized: true }>` stores one reference per locale instead of one.\n- Deleting a row does not delete its file, and deleting a file does not clear the field.\n\n### Access rules\n\nEach rule becomes a row level security policy on the table that records every stored file. The storage service runs each upload, overwrite, delete and list as the caller, so Postgres decides, the same way it does for your models.\n\n| Rule | Who passes |\n| --- | --- |\n| `BucketPublic` | Everyone, including the anon key |\n| `BucketLoggedIn` | Any signed-in user |\n| `BucketOwner` | The user who uploaded the file. An overwrite keeps the original owner. |\n| `BucketRole<\"admin\">` | Users whose `app_metadata.role` is `admin`, the same check as `Role` on a model |\n| `BucketPrivate` | Nobody but the service role |\n\n- A rule you leave out is refused, and the push prints a warning naming it.\n- `update` and `delete` need a `read` rule beside them. Postgres only lets a caller change rows it can read, so without one they match nothing. The push warns about this too, even on a public bucket.\n- `accessMode: \"public\"` serves files on the public URL without asking the `read` rule. Writes still go through `create`, `update` and `delete`.\n- `list` returns only the files the caller may read. `remove` deletes only the files the caller may delete, leaves the rest in place and returns just the ones it removed.\n- A refused write answers 401 to the anon key, because signing in might change the answer, and 403 to a signed-in user.\n\n> **NOTE:** A bucket with no `access` of its own takes the access rules of each model that has a file or image field pointing at it. Owner rules then compare the caller with the file's uploader. Declare `access` on the bucket to keep its rules in one place.\n\n### Upload\n\nThe [client page](https://www.supatype.com/docs/client.html#storage) shows the basic calls. `upload` sends the file in one request with the caller's token.\n\n`typescript`:\n\n```ts\nconst { data, error } = await supatype.storage.from(\"attachments\").upload(`${userId}/slides.pdf`, file, {\n contentType: \"application/pdf\",\n upsert: false,\n})\nif (error) console.error(error.status, error.message)\n```\n\n`file` may be a `File`, a `Blob` or an `ArrayBuffer`. On success `data` is `{ path }`.\n\nWithout `contentType` the client uses the `File`'s own type. If that is missing or generic, the service guesses from the extension (`.png`, `.pdf`, `.mp4` and other common types). The type is checked against `accept` before anything is stored.\n\nWith `upsert: true` an existing file at that path is replaced if the `update` rule allows it. The new bytes are stored alongside the old ones and swapped in when the row commits, so a reader never sees a half-written file.\n\n| Status | Why |\n| --- | --- |\n| 401, 403 | The bucket's `create` rule (or `update`, for an overwrite) refused the caller |\n| 404 | No bucket with that id |\n| 409 | A file already exists at that path and `upsert` was not set |\n| 413 | The file is larger than the bucket's `maxSize`, or the service limit when there is none |\n| 415 | The content type is not in `accept`. The body lists the allowed types. |\n| 507 | The upload would take the project past its total storage quota |\n\n### Download and URLs\n\nThere are three ways to read a file. All three go through the storage service, which looks up the file's current version, so a URL keeps working after the file is overwritten.\n\n| Method | Path | Who can use it |\n| --- | --- | --- |\n| `getPublicUrl(path)` | `/storage/v1/object/public/\u2026` | Anyone, only on a bucket with `accessMode: \"public\"`. Builds the URL locally with no request. |\n| `download(path)` | `/storage/v1/object/authenticated/\u2026` | The caller, if the `read` rule allows. Returns a `Blob`. |\n| `createSignedUrl(path, seconds)` | `/storage/v1/object/sign/\u2026?token=` | Anyone holding the link until it expires |\n\nA signed URL is only issued to a caller the `read` rule allows, and only for a file that exists. The expiry must be between 1 second and 7 days. The token is signed by the storage service and covers one bucket and one path. `createSignedUrls(paths, seconds)` signs several paths and reports an error per path.\n\n`typescript`:\n\n```ts\nconst bucket = supatype.storage.from(\"attachments\")\n\nconst { data: blob } = await bucket.download(`${userId}/slides.pdf`)\nconst { data: link } = await bucket.createSignedUrl(`${userId}/slides.pdf`, 3600)\nconst { data: files } = await bucket.list(`${userId}/`, { limit: 50, offset: 0 })\n```\n\n`list` returns up to 100 entries unless you pass `limit`. Each entry has `name`, `size`, `mimetype`, the owner and timestamps.\n\nThe first argument to `list` is a folder. Folders inside it come first, then files, each in name order, and there is no sort option. Pass `search` to match names without regard to case. The result also carries `count`, the number of matching entries in all.\n\nHow long a file may be cached depends on how it was read. There is no setting per upload.\n\n| Read through | `Cache-Control` |\n| --- | --- |\n| `getPublicUrl`, on a public bucket | `public, max-age=3600` |\n| `download`, with the user's session | `private, no-store`. No cache keeps it, so a CDN never serves one user's file to another. |\n| A signed URL | `public`, with a `max-age` of 3600 or the seconds left on the link, whichever is less. A cached copy stops when the link does. |\n\nEvery other answer, including an error such as a 404, carries `Cache-Control: no-store`. A CDN never keeps \"not found\" for a file you upload a moment later.\n\nPublic and private buckets differ in CORS too. A public bucket answers any origin. A private bucket sends no `Access-Control-Allow-Origin`, so read its files from a browser with a signed URL or `download`.\n\n`storage.listBuckets()` and `storage.createBucket(name, { public, fileSizeLimit, allowedMimeTypes })` need the service role key. Use them from a server or script, not a browser. In an app, declare buckets in the schema instead. The client has no call to change or delete a bucket. To change one, edit its declaration and push.\n\n### Image transforms\n\n`getPublicUrl` and `download` take a `transform` option. The service resizes and re-encodes the image on each request.\n\n`typescript`:\n\n```ts\nconst { data: { publicUrl } } = supatype.storage.from(\"covers\").getPublicUrl(post.cover.path, {\n transform: { width: 800, height: 450, resize: \"cover\", format: \"avif\", quality: 70 },\n})\n```\n\n| Option | Values | Default |\n| --- | --- | --- |\n| `width`, `height` | 1 to 4096 pixels | the original size |\n| `resize` | `cover`, `contain`, `fill`, `inside`, `outside` | `cover` |\n| `format` | `webp`, `avif`, `png`, `jpeg` | `webp` |\n| `quality` | 1 to 100 | 80 |\n\n- A transform runs only when `width`, `height`, `format` or `quality` is set. `resize` on its own does nothing.\n- Any transform re-encodes the image, as WebP unless you set `format`.\n- Images are never enlarged past their original size.\n- Files whose type is not `image/*` are served unchanged.\n- The same query parameters (`width`, `height`, `resize`, `format`, `quality`) work when appended to a signed URL.\n- On a public bucket, transformed responses carry `Cache-Control: public, max-age=3600` by default, set by `TRANSFORM_CACHE_TTL`. Put a CDN in front if the same sizes are requested often.\n- A transform read with the user's session is `private, no-store`, and one through a signed URL is cached no longer than the link lasts, as for plain files.\n\n### Limits and config\n\nThe storage service reads these environment variables. The self-host compose file sets the database, JWT and object store ones for you. The rest keep their defaults unless you set them on the `storage` service.\n\n| Variable | Default | What it controls |\n| --- | --- | --- |\n| `TIER_MAX_UPLOAD_SIZE` | 52428800 (50 MB) | Largest file, in bytes, for a bucket with no `maxSize`. A bucket's `maxSize` always wins. |\n| `STORAGE_QUOTA` | 1073741824 (1 GB) | Total bytes across every bucket. An upload past it gets 507. |\n| `MAX_SIGNED_URL_EXPIRY` | 604800 (7 days) | Longest signed URL, in seconds |\n| `DEFAULT_SIGNED_URL_EXPIRY` | 3600 | Expiry when a signing request names none |\n| `SIGNED_URL_SECRET` | the JWT secret | Key that signs URL tokens. Changing it invalidates every signed URL. |\n| `TRANSFORM_CACHE_TTL` | 3600 | `max-age`, in seconds, on transformed images |\n| `S3_BUCKET` | unset | One S3 bucket that holds every bucket as a key prefix, as described [below](https://www.supatype.com/docs/storage.html#own-bucket). Unset, each bucket gets an S3 bucket of its own, which the service creates and names `S3_BUCKET_PREFIX` then the bucket's id. |\n| `S3_BUCKET_PREFIX` | empty | With `S3_BUCKET` unset, put in front of each bucket's id to name its S3 bucket: `acme-prod-` makes `avatars` the S3 bucket `acme-prod-avatars`. S3 bucket names are global on AWS, so set one there. A prefix or a bucket id that makes no valid S3 bucket name is refused, the prefix at start and the bucket with 400. |\n| `S3_KEY_PREFIX` | empty | With `S3_BUCKET` set, a folder every key goes under, so several storage services can share one S3 bucket: `abc123/production` keeps `avatars/cat.png` at `abc123/production/avatars/cat.png`. One to four folder names joined by `/`, each lowercase letters, digits, `-` and `_`. Bucket ids are then limited to letters, digits, `.`, `_` and `-`. Anything else is refused, the prefix at start and the bucket with 400. |\n| `S3_ENDPOINT`, `S3_REGION`, `S3_ACCESS_KEY`, `S3_SECRET_KEY`, `S3_FORCE_PATH_STYLE` | none | Where the bytes are kept. The self-host stack sets them for its SeaweedFS. Running the service yourself, set `S3_REGION` for AWS or `S3_ENDPOINT` for another store; the service refuses to start with neither. Leave both keys blank to use the AWS SDK's own credentials. Path-style addressing is on when there is an endpoint. |\n\n> **SELF-HOSTED LIMITS:** The defaults above are for the storage service run on its own. A self-hosted stack has no plan, so its compose file sets `STORAGE_QUOTA`, `TIER_MAX_UPLOAD_SIZE` and `MAX_UPLOAD_SIZE` to `-1`, which means no limit. Set any of them in `.env`, in bytes, and run `supatype self-host compose up -d` to put a limit back. A bucket's `maxSize` still applies.\n\nThe service reads each upload fully into memory before storing it, so very large files cost memory on the storage container while they upload.\n\n### Where files live\n\nFile metadata is a row in the `storage` schema of your project's Postgres. The bytes go to an S3-compatible object store, each upload under its own versioned key. Read files through the storage API, not the object store, because the key is not the path you uploaded to.\n\n| Where you run | Where the bytes go |\n| --- | --- |\n| `supatype dev` (Docker, the default for new projects) | A SeaweedFS container, in the `storage-data` Docker volume. Its port is not published to your machine. `supatype dev --reset-db` keeps it. |\n| `supatype dev` with `provider: \"native\"` | Files under `~/.supatype/projects/<name>/storage-service`, served by the storage service running on your machine |\n| `supatype dev` with `provider: \"native\"` and `storage: { provider: \"s3\" }` | [Your own S3 bucket](https://www.supatype.com/docs/storage.html#own-bucket), named by `S3_BUCKET` in `.env`, served by the storage service running on your machine |\n| `supatype self-host compose up` with `storage: { production: \"s3\" }` | [Your own S3 bucket](https://www.supatype.com/docs/storage.html#own-bucket), named by `S3_BUCKET` in the server's `.env`. The stack runs no SeaweedFS. See [self-hosting configuration](https://www.supatype.com/docs/self-hosting/configuration.html#storage). |\n| `supatype self-host compose up` | A SeaweedFS service in the stack, in the `storage-data` volume. Its S3 port, 8333, is published (`SUPATYPE_SEAWEEDFS_PORT` changes it) and needs the stack's credentials. There is no anonymous access. |\n\n> **WARNING:** With the Native provider, the storage service is the same code a deployment runs, so bucket rules, `maxSize`, `accept` and transforms apply as they will once deployed. If it cannot start, storage is off: `supatype dev` prints why, `/storage/v1` answers 503 \"storage service is not running\", and storage comes back once you fix the cause and restart dev. There is no fallback store, because one that skipped your rules would let any caller read a private bucket.\n\n#### Switching storage or GraphQL off\n\n`services: { storage: false }` in `supatype.config.ts` answers every `/storage/v1` request with 503, and `services: { graphql: false }` answers `/graphql/v1` with 501. Self-host renders `SUPATYPE_STORAGE_DISABLED` and `SUPATYPE_GRAPHQL_DISABLED` into the server; a push to Supatype Cloud sets the same switch for the project. A key left out leaves the service on, and `true` turns it back on.\n\n#### Your own S3 bucket\n\nOn Supatype Cloud, name the bucket in `supatype.config.ts` and `supatype push` (or `supatype deploy`) sends it to the project's production environment. Only the organisation's owners and admins can set it, and the keys are read from your environment or `.env` with `env(\"NAME\")`, sent once, stored encrypted and never shown again:\n\n`supatype.config.ts`:\n\n```ts\nimport { defineConfig, env } from \"@supatype/cli\"\nexport default defineConfig({\n // docs:no-check (a fragment: the rest of your config stays as it is)\n storage: {\n provider: \"s3\",\n production: \"s3\",\n s3: { bucket: \"acme-files\", region: \"eu-west-1\", accessKey: env(\"ACME_S3_KEY\"), secretKey: env(\"ACME_S3_SECRET\") },\n },\n})\n```\n\nUse `endpoint` (an https URL) in place of `region` for another S3-compatible store, and `forcePathStyle` to override path-style addressing. Both keys are required on Cloud, since a Cloud project has no instance role to fall back to. Leaving `storage.s3` out of the config sends nothing and keeps whatever the project has; to go back to Supatype's bucket, call `DELETE /projects/<ref>/storage-bucket`.\n\n> **WARNING:** Switching buckets does not move your files. New files go to the new bucket; the ones stored before stay in the old one and stop being served. Copy them across first if you need them. Self-host reads its bucket from `S3_*` in `.env` and ignores `storage.s3`.\n\nSet `S3_BUCKET` and the storage service keeps every bucket inside that one S3 bucket, the way Supabase Storage uses `GLOBAL_S3_BUCKET`. A bucket is a row in your database and a key prefix in S3: a file `avatars/me.png` is stored under `avatars/me.png/<version>`. The service never creates an S3 bucket or puts a bucket policy, so:\n\n- The S3 bucket stays private. Public files are served by the storage service at `/storage/v1/object/public/<bucket>/<path>`, never straight from S3.\n- The keys only need to read, write, list and delete objects in that one bucket (`s3:GetObject`, `s3:PutObject`, `s3:DeleteObject` and `s3:ListBucket` on AWS). They do not need to create buckets.\n- Deleting a bucket deletes every key under its prefix.\n\n| Store | Set |\n| --- | --- |\n| AWS S3 | `S3_BUCKET` and `S3_REGION`. Leave `S3_ENDPOINT` blank. Leave `S3_ACCESS_KEY` and `S3_SECRET_KEY` blank to use the AWS SDK's own credentials, such as an instance or task role or `AWS_PROFILE`. |\n| Another S3-compatible store, such as Cloudflare R2 | `S3_BUCKET`, `S3_ENDPOINT`, `S3_ACCESS_KEY` and `S3_SECRET_KEY`. `S3_REGION` defaults to `us-east-1` and path-style addressing is on; set `S3_FORCE_PATH_STYLE=false` if your store wants the bucket in the host name. |\n\nThe service refuses to start without either `S3_REGION` or `S3_ENDPOINT`, or with only one of the two keys. Use a separate bucket for development and production.\n\nIn a self-hosted stack the storage service runs in a container, where `localhost` is that container. For a store on the same machine, such as a MinIO you run beside the stack, set `S3_ENDPOINT` to an address the container can reach: `http://host.docker.internal:9000` with Docker Desktop on macOS and Windows, or on Linux the host's address on the Docker bridge (usually `http://172.17.0.1:9000`) or its LAN address. Native `supatype dev` runs the service on your machine, so `localhost` works there.\n\nA bucket's `s3BucketPolicy` needs an S3 bucket of its own, so single-bucket mode never applies it. The storage service refuses one with 400 on a bucket made or changed through its API. A bucket `supatype push` creates keeps the policy in its record without applying it, and nothing warns you yet. If you need a policy per bucket, leave `S3_BUCKET` unset so each bucket gets its own S3 bucket, and set `S3_BUCKET_PREFIX` to keep their names unique.\n\nSetting `S3_BUCKET` on a storage service that already holds files does not move them: they stay in the per-bucket S3 buckets the service made before, where it no longer looks.\n\nWith `storage: { provider: \"s3\" }`, native `supatype dev` starts the storage service against the bucket in `.env`, and stops with a message if `S3_BUCKET` is blank. A `SUPATYPE_STORAGE_URL` in `.env` still wins: dev then starts no storage service and sends storage requests to that URL.\n\nBack up the `storage-data` volume along with the database. A database dump holds the file records but not the bytes.\n\nRemoving a bucket from the schema drops its policies on the next push. The bucket and its files stay where they are.\n\n## Realtime\n\nSource: https://www.supatype.com/docs/realtime.html\n\nSubscribe to inserts, updates and deletes on your tables over a WebSocket. Each change is checked against the subscriber's read access before it is sent. Broadcast and presence channels can be made private, with rules in your schema.\n\nPre-1.0: APIs and config may change between releases.\n\n### What is sent\n\nThe realtime service reads changes from Postgres logical replication, so every committed `INSERT`, `UPDATE` and `DELETE` is seen, whether it came from the API, Studio, a function or plain SQL. There is nothing to switch on per table. A change is only sent to clients subscribed to that table.\n\n| Event | `new` | `old` |\n| --- | --- | --- |\n| `INSERT` | the whole row | `null` |\n| `UPDATE` | the whole row | the whole row as it was |\n| `DELETE` | `null` | the whole row as it was |\n\nEvery table Supatype manages has `REPLICA IDENTITY FULL`, so the write-ahead log carries the whole previous row. A table set up outside Supatype keeps Postgres's default identity, and its `old` can hold only the key.\n\nValues arrive with the same types and formats as a REST read. A `BigInt` column becomes a native `bigint`, and `Decimal` and `Money` stay exact strings. `Json` columns arrive as the parsed value, not as JSON text. `timestamptz` arrives as ISO 8601 with a `T` and a full offset, such as `2024-01-01T12:00:00+00:00`, which every browser parses; `timestamp` is `2024-01-01T12:00:00` and `timetz` has its full offset. Fractional seconds keep their microseconds. Arrays of any type arrive as arrays, as REST sends them: `integer[]` and `double precision[]` hold numbers, `boolean[]` holds booleans, `bigint[]` and `numeric[]` hold exact strings, and `text[]`, `uuid[]` and `date[]` hold strings. Before 0.9.3 every array arrived as Postgres's text form, such as `\"{1,2}\"`. Before 0.9.3 `Json` was a string and `timestamptz` was `2024-01-01 12:00:00+00`, which Safari and Firefox read as `Invalid Date`; code that called `JSON.parse` on a `Json` column now gets the value itself.\n\n### Read access\n\nRealtime follows the same [access rules](https://www.supatype.com/docs/schema.html#access) as the REST API. For each change and each subscriber, the service checks with the subscriber's token, inside Postgres:\n\n- Insert and update: the row is selected again, by its primary key, as the subscriber. If the `read` rule hides it, the change is not sent. The check sees the row as it is at that moment, so a row deleted straight after it was inserted is not sent either. With the Native provider or your own Postgres, the `read` rule is applied to the row in the change instead.\n- Delete: the `read` rule is applied to the deleted row, as the subscriber, so a subscriber only hears of deletes of rows they could read. A delete on a table without `REPLICA IDENTITY FULL`, or without a Supatype `read` rule, is not sent.\n- Field rules: a column the subscriber may not read under a [field rule](https://www.supatype.com/docs/schema.html#field-rules) arrives as `null`, in both `new` and `old`. A filter on such a column is matched against the masked value, so it cannot be used to test a hidden value.\n- Service role: sees every change unmasked.\n- No token: receives no changes.\n\nThe row check uses the table's primary key. Inserts and updates on a table without one are not sent.\n\n### Subscribe\n\n`from(table).subscribe()` is the shortest path, shown on the [client page](https://www.supatype.com/docs/client.html#realtime). The callback's rows are typed from your schema.\n\n`typescript`:\n\n```ts\nconst sub = supatype.from(\"comment\").subscribe(\n (change) => {\n if (change.eventType === \"INSERT\") addComment(change.new)\n if (change.eventType === \"UPDATE\") replaceComment(change.new)\n if (change.eventType === \"DELETE\") removeComment(change.old?.id)\n },\n { event: \"*\", filter: `post_id=eq.${postId}` },\n)\n\n// later\nsub.unsubscribe()\n```\n\nEach call opens its own channel, so two components watching the same table do not interfere. All channels share one WebSocket per client. The payload has `eventType`, `new`, `old`, `schema`, `table` and `commitTimestamp`.\n\n#### Options\n\n| Option | Values | Default |\n| --- | --- | --- |\n| `event` | `\"INSERT\"`, `\"UPDATE\"`, `\"DELETE\"`, `\"*\"` | `\"*\"` |\n| `filter` | `\"column=op.value\"`, several joined with commas | none |\n| `schema` | the Postgres schema of the table | `\"public\"` |\n\n#### Filters\n\nA filter is checked on the server, so changes that do not match never reach the client. Several conditions joined with commas must all match. The operators are `eq`, `neq`, `gt`, `gte`, `lt` and `lte`.\n\n- Values are compared by the column's type, as Postgres would compare them, so `salary=gt.100000` compares numbers. A column of a type the service does not recognise is compared as text.\n- A null value, or one that cannot be read as the column's type, matches nothing.\n- An operator not in that list is ignored, and the filter then matches every change.\n- A delete is matched on `old`, the row as it was.\n\n#### Channels\n\n`supatype.realtime.channel(name)` is the lower-level form, for when you want the channel's status or want to mix changes with [broadcast and presence](https://www.supatype.com/docs/realtime.html#broadcast):\n\n`typescript`:\n\n```ts\nconst channel = supatype.realtime\n .channel(`post:${postId}`)\n .on(\"postgres_changes\", { event: \"INSERT\", table: \"comment\", filter: `post_id=eq.${postId}` }, (change) => {\n showComment(change.new)\n })\n .subscribe((status, err) => console.log(status, err?.message))\n```\n\nStatus is `SUBSCRIBING`, `SUBSCRIBED`, `CHANNEL_ERROR`, `TIMED_OUT` or `CLOSED`. `CHANNEL_ERROR` means the server refused a request on the socket, such as a `postgres_changes` listener for a table that does not exist, for a view, which has no changes of its own, or for a table the subscriber's role cannot read, such as `auth.users` with an anon or signed-in key: every change would be withheld from it. A channel used only for broadcast and presence is never checked against a table, whatever its name. With `CHANNEL_ERROR` the callback's second argument, `err`, is an `Error` whose message is the server's reason and names the table; it is undefined with every other status. A join hears only changes committed after it was taken. `TIMED_OUT` means the client gave up reconnecting. Render the status rather than assuming a channel is live: a subscription that stopped receiving looks the same as a quiet table. Pass `table` explicitly. Without it the channel name is read as `schema:table`.\n\nA channel carries one table subscription. If you call `.on(\"postgres_changes\", ...)` more than once on a channel, the first call's table, event and filter are what the server registers. Use one channel per table.\n\n### Broadcast and presence\n\nBroadcast sends a message to everyone else on a channel. Presence tells a channel who has joined and left. Neither touches the database.\n\n`typescript`:\n\n```ts\nconst room = supatype.realtime\n .channel(`cursor:${docId}`)\n .onBroadcast(\"move\", (payload) => drawCursor(payload))\n .onPresence(({ joins, leaves }) => updateUsers(joins, leaves))\n .subscribe((status) => {\n if (status === \"SUBSCRIBED\") room.track({ name: displayName })\n })\n\nroom.broadcast(\"move\", { x: 120, y: 48 })\n```\n\n- Only clients that have subscribed to the channel receive its messages. The two differ on the sender: a broadcast is not sent back to the client that sent it, but presence is. Your own `track` arrives in your `onPresence` as a join, and your own leave as a leave, so skip your own entry if you only want the others.\n- A presence entry is the payload you pass to `track`, plus `user_id` from the token. The server writes `user_id` last, so a payload cannot claim to be someone else. Every client without a signed-in user shares the `user_id` `anonymous`, so `user_id` cannot tell two anonymous clients apart, or tell you which entry is your own. Put a value you generate yourself in the `track` payload, such as `track({ clientId: crypto.randomUUID(), name })`, and key your member map on that.\n- Calling `track` again announces the new payload as a fresh join, so keep your own map of members keyed by `user_id`.\n- A client that joins late is sent the members already tracked on the channel as joins, then hears about joins and leaves from then on.\n- A client leaves on `untrack()`, on unsubscribe and when its socket closes.\n- Messages sent while the socket is not open are dropped, so send after `SUBSCRIBED`.\n\n> **WARNING:** A channel your schema does not declare has no access rules. Anyone with your anon key who knows its name can join it, read its messages and send to it. Do not put private data in it. Declare the channel to guard it: see [private channels](https://www.supatype.com/docs/realtime.html#private).\n\n### Framework hooks\n\n`@supatype/react` exports `useSubscription`. It subscribes when the component mounts, unsubscribes when it unmounts, and re-subscribes when the channel name, event, table, schema or filter changes. The callback can change between renders without re-subscribing. It returns `status`, and `error`, the server's reason while the status is `CHANNEL_ERROR` and null otherwise.\n\n`tsx`:\n\n```tsx\nimport { useState } from \"react\"\nimport { useSubscription } from \"@supatype/react\"\nimport type { TableRow } from \"@supatype/client\"\n\nfunction Comments({ postId }: { postId: string }) {\n const [comments, setComments] = useState<TableRow<\"comment\">[]>([])\n const { status } = useSubscription<TableRow<\"comment\">>(`comments:${postId}`, {\n table: \"comment\",\n event: \"INSERT\",\n filter: `post_id=eq.${postId}`,\n callback: ({ new: row }) => { if (row) setComments((list) => [...list, row]) },\n })\n return <p>{status}: {comments.length} new</p>\n}\n```\n\nIt needs `SupatypeProvider` above it, which takes your client as `client`. Give each use its own channel name: two hooks with the same name share a channel.\n\n`useChannel(name, setup, deps)` is for a channel that needs more than one listener, such as rows, presence and a broadcast together. `setup` receives the channel and adds its listeners; the hook subscribes, unsubscribes when the component unmounts or `name` or `deps` change, and runs `setup` again only when `deps` change, as `useEffect` does. It returns `status` and `error` as `useSubscription` does, and `isConnected` and `connectionState` for the socket itself.\n\n`tsx`:\n\n```tsx\nimport { useChannel } from \"@supatype/react\"\nimport { addBid, notify } from \"./app\"\n\nfunction Auction({ id }: { id: string }) {\n const { status, isConnected } = useChannel(`auction:${id}`, (channel) => {\n channel.on(\"postgres_changes\", { event: \"INSERT\", table: \"bid\", filter: `auction_id=eq.${id}` }, ({ new: bid }) => addBid(bid))\n channel.onBroadcast(\"outbid\", (payload) => notify(payload))\n }, [id])\n return <p>{isConnected ? status : \"reconnecting\"}</p>\n}\n```\n\n`useRealtimeConnection()` returns only `isConnected` and `connectionState`. `@supatype/vue` has `useChannel(name, setup)` and `useRealtimeConnection()`, and `@supatype/svelte` and `@supatype/solid` have `createChannel(name, setup)` and `createRealtimeConnection()`. They return `status` and `error` as that binding's `createSubscription` does (`\"connecting\"`, `\"connected\"`, `\"disconnected\"` or `\"error\"`), plus `isConnected` and `connectionState`, each as a ref, signal accessor or store to match the binding. `name` can be a string, or one that changes: a ref or getter in Vue, an accessor in Solid, a store in Svelte (with runes, `toStore(() => name)` from `svelte/store` makes one). When it changes the old channel is left, its listeners go with it, and `setup` runs on the new channel, so `status` reads `\"connecting\"` until it joins. Otherwise `setup` runs once, when the component mounts (straight away in Svelte), and the channel is left when it unmounts. There is no `deps` argument.\n\n`@supatype/vue` has `useSubscription(table, { event, filter })`, and `@supatype/svelte` and `@supatype/solid` have `createSubscription(table, { event, filter })`. These watch the `public` schema and return `data`, `error` and `status`, which is `\"connecting\"`, `\"connected\"`, `\"disconnected\"` or `\"error\"`. `data` is the table's rows. It is read once the subscription has joined, and read again after each re-join (a dropped socket that came back, or a sign-in), so changes made while the socket was down are not lost. From then on each change is an upsert by key: an insert or update replaces the row with the same key or adds it, and a delete removes it, with no effect for a key that is not held. The key is `id`; pass `key: \"slug\"`, or an array for a composite key, when the primary key is another column. A `filter` narrows the read as well as the changes. If the read fails, `error` holds the reason until a later read succeeds, and `status` is unchanged. Before 0.9.3 `data` started empty and an update or delete of a row that existed before subscribing did nothing.\n\n### Private channels\n\nA private channel is a broadcast and presence channel with access rules, written in your schema. You declare it with a `Channel` type, push, and the realtime service checks every join, broadcast and presence update against that rule, as the user who made it. Nobody can read or fake traffic on it just by knowing its name.\n\nThis is the same idea as Supabase Realtime Authorization. The difference is who decides. In Supabase the client flags a channel private and policies on `realtime.messages` do the rest. Here the schema declaration decides, whether or not the client says `private`, so a client cannot skip the rules by leaving a flag out.\n\n#### How it works\n\n- A channel has three operations. `join` covers subscribing, receiving broadcasts and receiving presence. `send` covers broadcasting. `track` covers appearing in presence.\n- An operation you leave out is denied to everyone except the service role. A declaration with no rules at all is refused when the schema is read.\n- Each rule is written in the same [access rule language](https://www.supatype.com/docs/schema.html#access) as a model, and runs inside Postgres as the caller. A `Rows` rule sees only the rows that caller may read.\n- Each operation is judged on its own. A rule that reads a table the caller has no privilege on denies that operation and no other, so a channel with `join: Public` and a `track` rule over a private table still admits anon to join, and refuses it presence.\n- The server asks once at join, keeps the answer, and then judges each broadcast and presence update from that answer with no database call.\n- The service role may do anything on any channel.\n\n#### Example: an auction lot\n\nEach lot has a channel. Only a signed-in user who is watching the lot may join it and appear in its presence. Any signed-in user who has joined may send a `bid` event, and only with an amount between 1 and 1,000,000. Only the seller, or an auctioneer, may announce that the reserve is met, which is a second channel on the same lot.\n\n`schema/index.ts`:\n\n```ts\nimport type {\n Model, Channel, UUID, Int, LoggedIn, Role, In, Exists, Rows,\n Eq, All, Any, AuthUid, Param, Event, Payload,\n} from \"@supatype/types\"\n\nexport type Lot = Model<\n { id: UUID; seller_id: UUID; title: string },\n { access: { read: LoggedIn } }\n>\n\nexport type LotWatcher = Model<\n { id: UUID; lot_id: UUID; user_id: UUID },\n { access: { read: LoggedIn } }\n>\n\nexport type Bid = Model<\n { id: UUID; lot_id: UUID; bidder_id: UUID; amount: Int },\n { access: { read: LoggedIn; create: LoggedIn } }\n>\n\n// Lots the signed-in user is watching.\ntype MyLots = Rows<\"lot_watcher\", \"lot_id\", Eq<\"user_id\", AuthUid>>\n\n// True when the signed-in user is the seller of the lot named in the topic.\ntype SellerOfThisLot = Exists<\n Rows<\"lot\", \"id\", All<[Eq<\"id\", Param<\"id\">>, Eq<\"seller_id\", AuthUid>]>>\n>\n\n// Bids and watchers. A signed-in watcher may send a \"bid\" event with a sensible amount.\nexport type LotChannel = Channel<\"lot:{id}\", {\n params: { id: UUID }\n access: {\n join: Any<[In<\"id\", MyLots>, Role<\"auctioneer\">]>\n send: All<[\n LoggedIn,\n Event<\"bid\">,\n Payload<\"amount\", { kind: \"number\"; min: 1; max: 1000000 }>,\n ]>\n track: All<[LoggedIn, In<\"id\", MyLots>]>\n }\n}>\n\n// Announcements only the seller (or an auctioneer) may make about the same lot.\nexport type LotStatusChannel = Channel<\"lot:{id}:status\", {\n params: { id: UUID }\n access: {\n join: Any<[In<\"id\", MyLots>, Role<\"auctioneer\">]>\n send: All<[Any<[SellerOfThisLot, Role<\"auctioneer\">]>, Event<\"reserve_met\">]>\n }\n}>\n```\n\nThings to notice:\n\n- `In<\"id\", MyLots>` at the top of a rule: a bare string names a channel parameter, here the `{id}` in the pattern. Inside `Rows` a bare string is a column of that table, so a parameter there is written `Param<\"id\">`.\n- `Event` and `Payload` are checked by the realtime server on every broadcast, with no database call. They are valid only in `send` and only directly inside `All<[...]>`. One `All` names one event, which is why the seller's event has its own channel.\n- `Payload` checks the shape of a field: `string` (with `maxLength`), `number` (with `min` and `max`), `boolean` or `required`. A missing field fails its check. It cannot say whether a bid is a good one. Put that in a database function (see [sending from the database](https://www.supatype.com/docs/realtime.html#send-from-db)).\n- The channel types need no `export`, but exporting them does no harm.\n\n#### Declaring a channel\n\n- A pattern is segments separated by `:`. A segment is a literal, a `{name}` that matches exactly one segment, or a final `*` that matches one or more remaining segments.\n- A literal may hold only letters, digits, `_`, `.` and `-`. A pattern may not be a bare `*`, and may not start with `realtime:` or `_supatype`.\n- Every `{name}` needs an entry in `params`, and every `params` key must be in the pattern. A parameter is a `UUID`, a `string` or an `Int`. A topic whose parameter has the wrong shape, such as `lot:abc` for `{id: UUID}`, is refused as not fitting. It never reaches Postgres as a bad cast.\n- Two declarations that could match the same topic are refused, and both are named. `lot:{id}` and `lot:featured` cannot both exist.\n- `Owner` is refused on a channel, because a channel has no row to own.\n- A `send` rule made only of `Event` and `Payload` checks who is sending nothing, so anon may send. `supatype diff` and `supatype push` warn about it every time, as long as the rule stands. Add a caller test such as `LoggedIn`. Writing `Public` in the rule says anyone may send, and silences the warning.\n- `supatype diff` and `supatype push` list channels added, removed and changed, and which operation's rule changed.\n- The engine must be new enough to emit the access functions. The CLI refuses a push that declares a channel, or sets `realtime.channels`, to an engine that does not list `private_channels` in its capabilities. See [moving from 0.9.2](https://www.supatype.com/docs/realtime.html#upgrading).\n- After `supatype generate`, the declared patterns type the channel names in the client, so editors suggest `lot:${string}`. Any other string is still accepted.\n\nA declaration is enforced as soon as it is pushed, for every client, including ones built before channels existed.\n\n#### The realtime.channels switch\n\nThe switch decides what happens to a topic that no declaration matches. It lives in `supatype.config.ts` and push carries it into the database, so self-host and Cloud need nothing else.\n\n`supatype.config.ts`:\n\n```ts\nimport { defineConfig } from \"@supatype/cli\"\nexport default defineConfig({\n project: { name: \"gavel\" },\n database: { provider: \"docker\" },\n server: { mode: \"dev\" },\n app: { mode: \"none\" },\n realtime: { channels: \"declared\" },\n})\n```\n\n| Value | An undeclared topic |\n| --- | --- |\n| `\"open\"` | Broadcast and presence work as they always did. This is the default when the key is absent. |\n| `\"declared\"` | The join is allowed, so `from(table).subscribe()` still works, but broadcast and presence on it are refused. A broadcast from the database to it is dropped. `supatype init` writes this for new projects. |\n\nThe `REALTIME_CHANNELS` environment variable on the realtime service can only tighten this. Set to `declared`, it makes the service behave as declared even when the database says `open`. It can never loosen a database that says `declared`. Any other value stops the service from starting.\n\n#### Using a private channel from the client\n\nPass `private: true` when you open the channel. The server enforces declarations without it. What the flag adds is an assertion: a name that no declaration matches is refused at once, so a typo fails loudly, and a server too old to enforce channels is never asked.\n\n`typescript`:\n\n```ts\nimport { isRealtimeChannelError } from \"@supatype/client\"\nimport { supatype } from \"./supatype\"\nimport { displayName, lotId, retryLater, showBid, showRefusal, tellUser, updateWatchers } from \"./app\"\n\nconst lot = supatype.realtime\n .channel(`lot:${lotId}`, { private: true })\n .onBroadcast(\"bid\", (bid) => showBid(bid))\n .onPresence(({ joins, leaves }) => updateWatchers(joins, leaves))\n .onRefused((refusal) => {\n // The channel is still joined. This one send went nowhere.\n if (refusal.code === \"payload_refused\") tellUser(\"That bid was not accepted.\")\n })\n .subscribe((status, err) => {\n if (status === \"SUBSCRIBED\") lot.track({ name: displayName })\n if (status === \"CHANNEL_ERROR\" && isRealtimeChannelError(err)) {\n if (err.retryable) retryLater()\n else showRefusal(err.reason)\n }\n })\n\nlot.broadcast(\"bid\", { amount: 120 })\n```\n\nIn React, `useChannel` takes the options as its fourth argument, and returns `error` for a refused or withdrawn join and `refusal` for a refused send. The Vue, Solid and Svelte channel bindings take the same options and return `refusal` too.\n\n`tsx`:\n\n```tsx\nimport { useChannel } from \"@supatype/react\"\nimport { isRealtimeChannelError } from \"@supatype/client\"\nimport { showBid } from \"./app\"\n\nfunction Lot({ id }: { id: string }) {\n const { status, error, refusal } = useChannel(\n `lot:${id}`,\n (channel) => {\n channel.onBroadcast(\"bid\", (bid) => showBid(bid))\n },\n [id],\n { private: true },\n )\n\n if (status === \"CHANNEL_ERROR\") {\n return <p>{isRealtimeChannelError(error) ? error.reason : \"error\"}: {error?.message}</p>\n }\n return <p>{status}{refusal ? ` (${refusal.code})` : \"\"}</p>\n}\n```\n\n#### Refusals and withdrawal\n\nEvery refusal carries a fixed code. Your app acts on the code, and may show the message. Codes are listed in [refusal codes](https://www.supatype.com/docs/realtime.html#refusal-codes).\n\n- A refused join arrives as `CHANNEL_ERROR`, with a `RealtimeChannelError` as the second argument. Its `reason` is the code, `channel` names the topic, and `retryable` is true only when the server could not reach the database. `isRealtimeChannelError(value)` tells one from any other error.\n- A refused broadcast, presence track or payload does not change the channel's status. The channel is still joined. It goes to `onRefused` as `{ channel, code, message }`, with `code` one of `send_denied`, `track_denied` or `payload_refused`.\n- Withdrawal is access taken back from a channel you held. It reaches every handle on that channel as `CHANNEL_ERROR` with reason `withdrawn`, and you also leave the channel's presence. The client does not rejoin by itself. Subscribe again once the user's access is restored.\n- A message never contains the rule or the data it read. It names the declaration.\n\n#### Sending from the database\n\nA broadcast is not a transaction, so data that matters, such as a bid, should be written by a database function. That function can then tell the watchers itself with `_supatype.realtime_send(topic, event, payload)`. It works from any SQL: an RPC function, a trigger, a hook or a migration.\n\n`place_bid.sql`:\n\n```sql\ncreate or replace function place_bid(p_lot uuid, p_amount integer)\nreturns void\nlanguage plpgsql\nsecurity invoker\nas $$\nbegin\n insert into bid (id, lot_id, bidder_id, amount)\n values (gen_random_uuid(), p_lot, auth.uid(), p_amount);\n\n -- Tell everyone watching the lot. The send rule of lot:{id} is checked as the caller.\n perform _supatype.realtime_send(\n 'lot:' || p_lot,\n 'bid',\n jsonb_build_object('amount', p_amount)\n );\nend;\n$$;\n```\n\nThe client calls it like any function, and listeners get the broadcast through `onBroadcast` as usual.\n\n`typescript`:\n\n```ts\nconst { error } = await supatype.rpc(\"place_bid\", { p_lot: id, p_amount: 120 })\nif (error) console.error(error.code, error.message)\n```\n\n- Receivers are every member the channel's `join` rule admitted. There is no new access path.\n- `realtime_send` checks the caller's `send` rule, including the event and payload checks, and raises error `42501` with the same sentence a refused broadcast gets. Only signed-in users sending as themselves pass. Anon is refused. The service role may send anything.\n- It writes one row to `_supatype.realtime_outbox`, which the realtime service reads from the replication slot. A trigger deletes each row as it is written, so the table never fills. Inserting into the outbox directly is judged by the same rule, and the row's `sender` must be the caller's own id (leave it out and the insert is refused).\n- Under `declared`, a database send to a topic no declaration matches is dropped, and the service logs it once per topic.\n\n> **SECURITY DEFINER:** Keep the function `SECURITY INVOKER`, as above, so the send rule judges the user. A `SECURITY DEFINER` function owned by a superuser counts as the service role, and its sends skip every check. Do the checks inside such a function yourself.\n\n#### Token changes, re-checks and outages\n\n- **New token.** When a socket gets a new token, for example after sign-in, sign-out or a role change, every channel it holds is judged again as the new identity. A channel whose `join` rule no longer admits the user is withdrawn, with a presence leave. Changed `send` and `track` answers replace the old ones.\n- **Revocation.** If a user is removed from a table a rule reads, such as `lot_watcher`, the held channels of that declaration are judged again, in one batch a second. They are also judged again after a schema push, and every 300 seconds as a backstop. Set `REALTIME_CHANNEL_RECHECK_S` to change that interval.\n- **Expiry.** A token that expires closes the socket with 4401, as before.\n- **Database down at join.** The service fails closed. It refuses every join, open channels included, with code `unavailable` and `retryable` set, because without the database it cannot tell whether a topic is declared. Retry with a delay.\n- **Database down at a re-check.** Nobody loses a channel because a check could not run. Held channels keep their access and the check is tried again at the next interval. A new token that cannot be checked still withdraws the channels, since the old answer no longer applies.\n- **Shared instance.** A shared realtime service, which serves many projects from one database, does not enforce channel rules. It refuses a join that says `private`, with code `shared_instance`. Supatype Cloud (closed beta) runs one realtime service per project.\n\n### Refusal codes\n\nThe set is closed. A client that meets a code it does not know should treat it as `refused`.\n\n| Code | Arrives as | Meaning | What the app should do |\n| --- | --- | --- | --- |\n| `join_denied` | `CHANNEL_ERROR` | The channel's `join` rule said no, or the channel declares none. | Tell the user they may not open this. Do not retry. Ask them to sign in if they are not. |\n| `not_declared` | `CHANNEL_ERROR` | You opened it with `private: true` and no declaration matches the name. | A bug: fix the name, or push the declaration. |\n| `does_not_fit` | `CHANNEL_ERROR` | A declaration matches the start of the name, but a parameter has the wrong shape, such as a non-UUID. | A bug: build the topic from a valid value. |\n| `unavailable` | `CHANNEL_ERROR`, `retryable` | The server could not reach the database to check. | Retry after a delay. This is the only retryable code. |\n| `shared_instance` | `CHANNEL_ERROR` | The realtime service is shared, and private channels are not available there. | Use a project with its own realtime service. |\n| `withdrawn` | `CHANNEL_ERROR` | A re-check took back access to a channel you held. | Stop showing the channel's data. Join again only when the user's access changes. |\n| `send_denied` | `onRefused` | A broadcast was refused: the `send` rule said no, there is none, or the topic is undeclared under `declared`. | Show that the send failed. The channel is still joined. |\n| `track_denied` | `onRefused` | A presence track was refused. | Show that the user is not shown as present. The channel is still joined. |\n| `payload_refused` | `onRefused` | The event name or payload failed the send rule's checks. | Fix the message, or tell the user their input was not accepted. |\n| `refused` | `CHANNEL_ERROR` | Any other refusal, such as a bad filter, a missing table or no token. | Read the message. Do not retry blindly. |\n| `unsupported_server` | `CHANNEL_ERROR` | The client's own: the server did not announce private channel support, so a `private: true` join was never sent. The message says to upgrade the server. | Upgrade the realtime service. Do not fall back to an open channel. |\n\n### Moving from 0.9.2\n\nNothing changes until you declare a channel or set `realtime.channels`. A project with no `realtime` key stays `\"open\"`, so broadcast and presence behave as they did. `supatype init` writes `\"declared\"` for new projects only.\n\nBefore 0.9.3, anyone with your anon key could join any channel, read its broadcasts, send on it and appear in its presence. To close that:\n\n- Step 1: Upgrade the realtime service and the engine. The engine must list `private_channels` in its capabilities. The CLI checks this and refuses the push if it does not, because an older engine would drop the channels and report success while enforcing nothing. On self-host, raise the engine pin in `versions.engine`. On Cloud, a push that declares channels is refused until the platform's engine lists the capability.\n- Step 2: Declare a `Channel` for each topic your app uses, with the rules you want. Declaring one enforces its pattern at once, for every client, in either mode.\n- Step 3: Set `realtime: { channels: \"declared\" }` and run `supatype dev`. Fix the refusals you see. `supatype diff` warns when the mode goes from `open` to `declared`, and when you remove a declaration under `declared`.\n- Step 4: Push.\n- Step 5: Add `private: true` to the channels the client opens, so a mistyped name is refused instead of left open.\n\nA channel named after a table, which `from(table).subscribe()` opens, keeps working under `declared` with no declaration, because it only carries row changes. Row changes are still guarded by the table's access rules.\n\nA client that sends `private: true` to a 0.9.2 realtime service fails with `unsupported_server` and the message \"this realtime server does not enforce private channels; upgrade it\".\n\n### Connection and auth\n\nThe client opens the socket at `/realtime/v1` on your project URL when the first channel subscribes, and closes it when the last one unsubscribes. It sends the current session's token, or the anon key when nobody is signed in.\n\n`supatype.realtime.removeChannel(name)` leaves a channel by name. `supatype.realtime.disconnect()` closes the socket whatever is still subscribed, and reports `CLOSED` to every channel still registered.\n\nWhen someone signs in, signs out or a different user signs in, the client reconnects with the new token and joins every channel again. Access is checked as the new identity from then on. A token refresh for the same user does not reconnect, so no changes are missed.\n\nA channel's status cannot tell a drop from a first connect, since both read `SUBSCRIBING`. For the socket itself, `supatype.realtime.isConnected` is true while it is open, and `supatype.realtime.onConnectionChange((state) => ...)` calls you each time `supatype.realtime.connectionState` changes between `\"connected\"`, `\"connecting\"` (first connect, reconnecting after a drop or a sign-in, or waiting to retry) and `\"disconnected\"` (nothing subscribed, `disconnect()` was called, or every retry failed). It returns a function that stops the listener, and does not call you with the state it already has. Refetch when the state returns to `\"connected\"` after a drop. In React, `useChannel` and `useRealtimeConnection` expose the same two values.\n\nIf the socket drops, the client retries after 1, 2, 4, 8 and 16 seconds, then every 30 seconds, for up to 10 attempts. Channels report `SUBSCRIBING` while it retries and `TIMED_OUT` once it gives up. Changes made while the socket was down are not replayed, so refetch after a reconnect if you need the gaps filled.\n\n### Config and requirements\n\nRealtime needs Postgres with `wal_level = logical`, the `wal2json` plugin, and a database role allowed to create replication slots. The Postgres that `supatype dev` and the self-host stack run has all three. For a database you bring yourself, `supatype db check` tests for them.\n\nIf the database cannot do logical decoding, realtime does not stop the stack. The service stays up and serves broadcast and presence, change subscriptions deliver nothing, and `/health/ready` on the service answers 503 with the reason. When you run against your own database, set `database.external.realtime` to `false` in `supatype.config.ts` to leave the service out of the stack.\n\nThe service reads these environment variables. The self-host compose file sets the first three.\n\n| Variable | Default | What it controls |\n| --- | --- | --- |\n| `DATABASE_URL` | required | The database to read changes from |\n| `JWT_SECRET` | required | Verifies subscribers' tokens |\n| `SLOT_NAME` | `supatype_realtime` | The replication slot the service creates and reads |\n| `PORT` | 4000 | The port the service listens on |\n| `REPLICATION_POLL_INTERVAL` | 100 | How often, in milliseconds, the slot is read |\n| `SECURE_CHANNELS` | `true` | When `true`, a client must present a valid token before it can join a channel |\n| `REALTIME_CHANNELS` | unset | Set to `declared` to refuse broadcast and presence on undeclared channels whatever the database says. It can only tighten `realtime.channels` |\n| `REALTIME_CHANNEL_RECHECK_S` | 300 | Seconds between re-checks of every channel a socket holds, as a backstop to the checks made on a new token, a push and a change to a table a rule reads |\n\nTo set these from `supatype.config.ts` rather than the environment, use `realtime: { channels: \"declared\", recheckSeconds: 120 }`. Self-host renders them as the realtime service's defaults, which a value in `.env` overrides. A push to Supatype Cloud sets them on the project's realtime service (production only), and a setting you take out of the config stops applying on the next push that still sets another one.\n\n### Limits\n\n- Changes are picked up by reading the replication slot every 100 ms, so expect that much delay on top of the network.\n- While `supatype push` is changing the schema, the slot is not read. Changes made during the push are held in the slot and sent once it finishes.\n- Each change costs one database query per subscriber, to check that subscriber's access. Many subscribers to a busy table means many queries.\n- The replication slot keeps WAL until the service reads it. If the service is stopped for a long time while the database keeps writing, WAL builds up on disk.\n- Each private channel a socket holds costs one query at join, one more every re-check interval, and a batch a second while a table its rules read is changing.\n- Subscriptions live in the service's memory. A restart drops every socket, and clients reconnect and join again.\n\n## Functions\n\nSource: https://www.supatype.com/docs/functions.html\n\nA function is a TypeScript file in `functions/` that runs on Deno and answers HTTP at `/functions/v1/<name>`. It receives a standard `Request` and returns a standard `Response`.\n\n### Where functions live\n\nFunctions sit in `functions/` at the project root. Each one is either a folder with an `index.ts` or a single `.ts` file. The name becomes the route.\n\n| File | Route |\n| --- | --- |\n| `functions/send-invite/index.ts` | `/functions/v1/send-invite` |\n| `functions/ping.ts` | `/functions/v1/ping` |\n| `functions/_shared/email.ts` | none: shared code |\n\n- Names starting with `_` or `.` are skipped, so `functions/_shared/` holds code every function can import with a relative path.\n- `.d.ts` files are skipped.\n- `_logs` is reserved by the worker, and the gateway refuses `/functions/v1/hooks` from outside, so do not use either name.\n\nTo use another directory, set `functions.path` in `supatype.config.ts`. It resolves against the project root.\n\n`supatype.config.ts`:\n\n```ts\nimport { defineConfig } from \"@supatype/cli\"\n\nexport default defineConfig({\n project: { name: \"my-app\" },\n database: { provider: \"docker\" },\n server: { mode: \"dev\" },\n app: { mode: \"none\" },\n functions: {\n path: \"functions\",\n },\n})\n```\n\n### Runtime\n\nFunctions run on Deno. Locally the CLI downloads Deno on first use. On a self-hosted stack they run in the `functions-worker` container, and `supatype-server` proxies `/functions/v1` to it.\n\nThe worker loads every function once at startup and serves them from one process. Invocations run concurrently: nothing per call is written to the process environment, so one slow function does not block another.\n\nThe CLI writes three files to help your editor: `functions/deno.d.ts`, `functions/tsconfig.json` and `functions/_shared/context.ts`. It also adds `functions` to the root `tsconfig.json` `exclude` list, so your app's type check skips Deno code. `context.ts` is rewritten by `init`, `functions new`, `push` and `dev`, so do not edit it.\n\n### Write a function\n\nScaffold one with the CLI:\n\n```sh\n$ npx supatype functions new greet\n```\n\nA function default-exports a handler. It gets the request and a context object, and returns a `Response`. There is no Supatype package to import at runtime and no client injected for you.\n\n`functions/greet/index.ts`:\n\n```ts\nimport type { FunctionContext } from \"../_shared/context.ts\"\n\nexport default async function handler(req: Request, ctx: FunctionContext): Promise<Response> {\n if (req.method !== \"POST\") {\n return Response.json({ message: \"Use POST\" }, { status: 405 })\n }\n const { name } = (await req.json()) as { name?: string }\n return Response.json({ greeting: `Hello, ${name ?? \"there\"}`, region: ctx.region })\n}\n```\n\nA thrown error becomes a `500` with `{ \"error\": \"function_error\", \"message\": \"...\" }`. An unknown name returns `404` with the list of available functions.\n\n### The context object\n\nThe second argument carries what the function needs about its call and its project.\n\n| Field | What it holds |\n| --- | --- |\n| `executionId` | A UUID unique to this call. Every log line the call writes carries it. |\n| `functionName` | The route being served. |\n| `url` | The project's API base URL, reachable from inside the function. |\n| `anonKey` | The project's anon key. |\n| `serviceRoleKey` | Only present when the project grants this function the service role. See [Service role](https://www.supatype.com/docs/functions.html#service-role). |\n| `dbUrl` | A direct database URL, only when the deployment provides one. |\n| `region` | `local` unless the deployment sets a region. |\n| `env` | Your variables from the function env files. See [Environment and secrets](https://www.supatype.com/docs/functions.html#env). |\n\n### Who is calling\n\nThe client sends the signed-in user's access token in the `Authorization` header. The function receives that header as it was sent. Nothing checks it for you, so a function that cares who is calling must ask auth.\n\n`functions/whoami/index.ts`:\n\n```ts\nimport type { FunctionContext } from \"../_shared/context.ts\"\n\nexport default async function handler(req: Request, ctx: FunctionContext): Promise<Response> {\n const authorization = req.headers.get(\"Authorization\")\n if (!authorization) return Response.json({ message: \"Sign in first\" }, { status: 401 })\n\n const headers = { Authorization: authorization, apikey: ctx.anonKey }\n const res = await fetch(`${ctx.url}/auth/v1/user`, { headers })\n if (!res.ok) return Response.json({ message: \"Not signed in\" }, { status: 401 })\n\n const user = (await res.json()) as { id: string; email?: string }\n // Forward the same headers to REST and the user's access rules apply.\n const posts = await fetch(`${ctx.url}/rest/v1/post?select=title`, { headers })\n return Response.json({ id: user.id, posts: await posts.json() })\n}\n```\n\nForwarding the caller's token is the safe default: the database sees the user, not the function, and every [access rule](https://www.supatype.com/docs/schema.html) still applies.\n\nDo not decode the token yourself to read a role. Until its signature is checked, anyone can send a payload that says `\"role\": \"admin\"`. Ask `/auth/v1/user`, as above, which checks it. `supatype.auth.getUser()` on a client you create inside a function does not help here: it reads that client's own stored session, not the request's token, so it returns no user.\n\n### Service role\n\nA function is a public endpoint. By default it does not receive the service-role key, which reads and writes past every access rule. The worker removes the key from the environment before any function is imported, so `Deno.env` cannot reach it either.\n\nTo give a function the key, name it in `functions.serviceRole`. It then appears as `ctx.serviceRoleKey`.\n\n`supatype.config.ts`:\n\n```ts\nexport default defineConfig({\n // ...\n functions: {\n serviceRole: [\"send-invite\"],\n },\n})\n```\n\n`supatype push` refuses a name that matches no function, so a typo cannot silently grant nothing. `supatype doctor` lists the current grants.\n\nLocal dev applies the same list, so a function that relies on the key without being named fails there first. Under `supatype functions serve` no function receives the key unless `SUPATYPE_SERVICE_ROLE_KEY` is set in your shell, and then only the functions the list names.\n\n### Environment and secrets\n\nVariables for functions live in env files inside the functions directory:\n\n- `functions/.env.local` is shared by every function.\n- `functions/.env.<name>.local` applies to one function and overrides the shared file.\n\nRead them from `ctx.env`. The files are read on each call, so a changed value takes effect without a restart. Keep them out of git.\n\nEvery value set with `supatype functions env set`, in `.env.local` or in `.env.<name>.local` arrives in `ctx.env` on each call, never in `Deno.env`: `Deno.env` is the worker's one process environment, shared by every call running at the same time, so a value put there for one function would reach every other. `Deno.env.get(\"RESEND_API_KEY\")` finds nothing.\n\n`Deno.env` holds only the worker's own settings (such as `SUPATYPE_URL`, `SUPATYPE_PUBLIC_URL` and `SUPATYPE_ANON_KEY`, which also arrive as `ctx` fields), Deno's `DENO_*` variables and what the operating system needs, such as `PATH` and the temporary directory. Before any function is imported the worker deletes everything else, so the stack's secrets and the variables in your shell never reach function code, under `supatype dev` and `supatype functions serve` as on a deployed stack. A self-hosted worker also keeps `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` and `SITE_URL` when Compose passes them.\n\n```sh\n$ npx supatype functions env set RESEND_API_KEY=re_123\n$ npx supatype functions env list\n$ npx supatype functions env unset RESEND_API_KEY\n```\n\nOn a project that is not linked, these commands edit `functions/.env.local`. `list` masks the values.\n\nAdd `--function <name>` to `list`, `set` or `unset` to work on one function's own values: on a linked project they go to that function, and on a project that is not linked they edit `functions/.env.<name>.local`. A function's own value overrides a shared one with the same name.\n\n```sh\n$ npx supatype functions env set RESEND_API_KEY=re_456 --function send-invite\n$ npx supatype functions env list --function send-invite\n$ npx supatype functions env unset RESEND_API_KEY --function send-invite\n```\n\nOn Supatype Cloud the per-function routes need a control plane that serves `/projects/<ref>/functions/<name>/env`.\n\n`functions/send-invite/index.ts`:\n\n```ts\nconst apiKey = ctx.env[\"RESEND_API_KEY\"]\nif (!apiKey) return Response.json({ message: \"RESEND_API_KEY is not set\" }, { status: 500 })\n```\n\n### Call a function\n\nFrom your app, use `functions.invoke` on the client. It posts JSON to `/functions/v1/<name>` with the user's token and returns `{ data, error }`. A non-2xx response becomes `error`, using the `message` field from the body when there is one.\n\n`typescript`:\n\n```ts\nconst { data, error } = await supatype.functions.invoke(\"greet\", { body: { name: \"Alex\" } })\n```\n\n`invoke` also takes `method` (default `POST`) and `headers`. A JSON response is parsed and anything else comes back as text. On a `401` the client refreshes the session once and retries. More in [Client: Functions](https://www.supatype.com/docs/client.html#functions).\n\n### Local development\n\n`supatype dev` serves functions through the same gateway as the rest of the API when a functions directory exists. You do not run anything else.\n\nWith the Native provider, Deno runs in the project folder, so a project with a `package.json` resolves `npm:` imports from its `node_modules`. Install what a function imports, such as `npm install postgres` for `npm:postgres`. Without it the call fails with `Could not find a matching package for 'npm:postgres' in the node_modules directory`. Do not turn on `nodeModulesDir: \"auto\"` in a `deno.json` there: Deno then rewrites `node_modules`, and `supatype.config.ts` stops loading.\n\nTo run functions on their own, with Deno watching for changes:\n\n```sh\n$ npx supatype functions serve\n$ npx supatype functions invoke greet --local --data '{\"name\":\"Alex\"}'\n```\n\n`serve` listens on port `18472` by default; change it with `--port`. It loads `functions/.env.local` unless you pass `--env-file`. `invoke` sends a POST, prints the status and the response, and gives up after 30 seconds. It exits 1 when the function answers with a status of 400 or above, so a script can tell a failed call (a 404 for a function that does not exist, say) from one that worked. `--auth` adds a test token to the request, on this machine only: on a Cloud link it is refused, because it would send your Supatype Cloud session, which can manage your projects, to the function, and on a self-hosted link it is refused because there is no user token to send. Call a deployed function with a signed-in user's access token instead. With `--local`, or when no Cloud project is linked, `invoke` calls a running `serve` on `--port` (18472 by default) when one answers, and the project's dev API otherwise.\n\n### Self-host\n\nThe self-host Compose file always includes a `functions-worker` service, built from the `supatype/functions-worker` image. It mounts the project read-only and serves `functions/` from it. There is no bundle or upload step: the files on disk are what runs.\n\nThe worker reads code once at startup, so restart it after changing a function:\n\n```sh\n$ docker compose -p supatype-<project> -f .supatype/self-host/docker-compose.yml restart functions-worker\n```\n\n`<project>` is your project name from `supatype.config.ts` in lower case, with spaces and other symbols replaced by `-`. `supatype self-host compose restart functions-worker` does the same and finds the project name for you. Env file changes do not need a restart.\n\nOn an unlinked project with a self-host Compose file, `supatype functions deploy` uploads nothing. It lists the functions it found on disk and prints that restart command.\n\nThe worker gets the anon and service-role keys from the stack. To give functions a database connection, set `SUPATYPE_FUNCTIONS_DB_URL`; it appears as `ctx.dbUrl`. It is off by default because a direct connection is not a request through the API: model hooks do not run, and row rules and field masking apply only for the role the URL names. A superuser or `BYPASSRLS` role (the admin role, `service_role`) skips both, so point it at a login role that is neither, granted only what your functions need. The database name at the end of the URL is the value of `POSTGRES_DB` in your `.env`.\n\nThe worker runs Deno 2.9.8. Postgres drivers verified against a live database on it: `npm:postgres` (latest), `npm:postgres@3.4.5` and `npm:pg`. `npm:postgres` 4.0 and later does not run on Deno before 2.8, where it fails with `Not implemented: LibuvStreamWrap.prototype.useUserBuffer` or `socket._handle.useUserBuffer is not a function`. Every 3.4 release runs there; a stack on an older worker image should pin `npm:postgres@3.4.5`.\n\nFunction logs are JSON lines on the container's output, each with the call's `request_id`, status and duration:\n\n```sh\n$ npx supatype self-host compose logs --service functions-worker\n```\n\nUnder `supatype dev` without Docker (native dev), functions run inside the server process, so there is no worker container to read. `supatype dev` sets `SUPATYPE_FUNCTIONS_LOG_TO_STDOUT`, and the server then prints each line a function writes to the terminal that runs `dev`, prefixed with the function name, for example `[hello] got a request`. Lines that name no function, such as Deno's own errors, are prefixed `[deno]`. The same lines stay in Studio's function logs. A server that does not have the variable set, such as Cloud or a Compose stack, prints nothing extra.\n\n> **NOTE:** The Compose file mounts `functions/` at the project root. Keep the default path on a self-hosted stack.\n\n### Model hooks\n\nA model hook is a handler the API server calls around a write to one model: to check it, change it, refuse it, or react once it has happened. Hooks run on the same Deno worker as functions, but they are not public endpoints. They live in their own `hooks/` directory at the project root, the worker serves them under a `hooks/` route, and the gateway refuses that route from outside.\n\n#### Triggers\n\n| Key | Runs | Can |\n| --- | --- | --- |\n| `beforeChange` | Before an insert or update reaches Postgres | Let it through, replace the rows or the patch, or refuse it |\n| `afterChange` | After an insert or update commits, from any writer | React only. It cannot change or undo the write |\n| `beforeDelete` | Before a delete reaches Postgres | Let it through or refuse it |\n| `afterDelete` | After a delete commits, from any writer | React only |\n\n`before*` hooks fire on writes to `/rest/v1/<table>`: `POST` and `PUT` are inserts, `PATCH` is an update, `DELETE` is a delete. That covers the client's `insert`, `upsert`, `update` and `delete`, including calls made with the service-role key. RPC calls, direct SQL, seeds and migrations do not fire them.\n\n`after*` hooks read committed changes from the database's change log instead, so they fire for every writer: the API, Studio, SQL and functions. Seeds are the exception. On a database without logical replication they fall back to writes through the API only; `supatype db check` and `supatype doctor` say which you have.\n\n#### Declare a hook\n\nName the handler in the model's second argument. A string is the handler's directory name; an object adds options.\n\n`schema/index.ts`:\n\n```ts\nexport type Post = Model<{\n id: UUID\n title: string\n // ...\n}, {\n // access, versions, ...\n hooks: {\n beforeChange: \"check-post\"\n afterChange: { function: \"notify-post\"; timeout: 5000 }\n }\n}>\n```\n\n| Option | Meaning |\n| --- | --- |\n| `function` | The directory under `hooks/`. |\n| `timeout` | Milliseconds to wait for an answer. Default `2000`. |\n| `onUnavailable` | What to do when the hook does not answer: a timeout, a connection failure, a `5xx`, a thrown error or an unreadable body. `\"reject\"` refuses the write, `\"log\"` lets it through and logs. Defaults to `\"reject\"` for `before*` hooks and `\"log\"` for `after*` hooks. |\n| `columns` | `after*` hooks only. `\"safe\"`, the default, leaves every column with a field `read` rule out of the hook's rows; `\"all\"` keeps them. |\n\n`supatype push` refuses a schema whose hook names a directory with no `index.ts`, so a typo cannot leave a hook that never fires.\n\n#### Write the handler\n\n```sh\n$ npx supatype hooks new check-post\n$ npx supatype hooks list\n```\n\n`hooks new` creates `hooks/<name>/index.ts`. When a model already names it, the file is set up for that event; otherwise the command prints the line to add to the model. `hooks list` prints each `Model.event` with its handler and marks any whose handler is missing. `supatype doctor` reports the same.\n\nHandlers import their types from `hooks/_supatype/hooks.ts`, which `push`, `dev` and `generate` write from your schema. Until the first push it does not exist, so a new handler will not compile yet. Do not edit it.\n\n`hooks/check-post/index.ts`:\n\n```ts\nimport { hook, type BeforeChange } from \"../_supatype/hooks.ts\"\n\nconst checkPost: BeforeChange<\"post\"> = async (ctx) => {\n if (ctx.operation === \"insert\") {\n if (ctx.rows.some((row) => row.title.trim() === \"\")) return { reject: \"A post needs a title\" }\n return { rows: ctx.rows.map((row) => ({ ...row, title: row.title.trim() })) }\n }\n if (ctx.patch.title !== undefined && ctx.patch.title.trim() === \"\") {\n return { reject: { message: \"A post needs a title\", status: 422, code: \"empty_title\" } }\n }\n return {}\n}\n\nexport default hook(checkPost)\n```\n\nThe type argument is the table name. `BeforeChange`, `AfterChange`, `BeforeDelete` and `AfterDelete` type the context from the model, and only tables that declare a hook are accepted.\n\n| Context field | What it holds |\n| --- | --- |\n| `table`, `operation` | The table and `insert`, `update` or `delete`. |\n| `user` | `sub`, `role` and `email` from the caller's verified token, or `null` for an anonymous caller and for an `after*` hook on a write made outside the API. |\n| `requestId` | Matches the request in the server logs. |\n| `rows` | An insert's rows, always an array. On `afterChange`, every row one transaction wrote to the table with that operation, always present and in the JSON shape PostgREST returns, so a bulk insert is one call. |\n| `old` | On an `afterChange` update and on `afterDelete`: the rows as they were before. On an update, `old[i]` is `rows[i]` as it was. |\n| `deliveryId` | On `after*` hooks: `commitLSN:schema.table:operation`, the same on every delivery of one call. Delivery is at least once, so keep the ids you have handled if a repeat would do harm. |\n| `patch` | An update's changes. |\n| `filter` | The request's filter on an update or delete, such as `id=eq.42`. A hook cannot change it. |\n| `previous()` | Before an update or delete: fetches the rows about to change, up to 100, with `truncated: true` when there were more. They come back as stored, without field masking, so do not copy them into a refusal message. |\n\nA `before*` handler returns `{}` to let the write through. `beforeChange` can return `{ rows }` for an insert or `{ patch }` for an update to replace what is written. `{ reject }` refuses the write: the caller gets your message with status `422`, or the `4xx` status you set. A thrown error is not a refusal: it counts as the hook not answering, and `onUnavailable` decides.\n\nTo keep a model's whole lifecycle in one directory, point several events at the same name and export `hooks({ beforeChange: checkPost, afterChange: notify })` instead of `hook(...)`. An event with no handler in that map lets the write through.\n\n#### How hooks run\n\n- The server reads the whole request body before any hook runs. A body over 1 MiB on a write to a hooked table is refused, rather than written without the hook.\n- An `after*` hook runs once the write has committed. A delivery it does not answer is retried with backoff, then logged, and never reaches the caller. Its rows leave out restricted columns unless it declares `columns: \"all\"`.\n- A hook may write through the API, and those writes fire hooks too. A chain more than four hooks deep is refused with status `508`, so a hook that writes to its own table cannot loop forever.\n- On a Docker stack the `functions-worker` container mounts `hooks/` next to `functions/`. When `supatype dev` runs on Docker, the worker restarts when a hook file changes. On a self-hosted stack, restart it after changing a hook, as for functions.\n\n> **NOT A SECURITY BOUNDARY:** Direct SQL, seeds and migrations skip hooks. A rule every writer must follow belongs in the model's [access rules](https://www.supatype.com/docs/schema.html#access) or a constraint. Use hooks for application logic: enrichment, notifications, indexing, and checks the database cannot express.\n\n### Limits\n\n- The gateway waits up to two minutes for a function to start responding.\n- The self-host worker sets no memory or CPU cap per function. Set container limits in Compose if you need them.\n- Function names and bodies are not typed on the client.\n\n## Seeding\n\nSource: https://www.supatype.com/docs/seeding.html\n\nA seed file describes the rows you want. Supatype checks it against your schema, orders the writes by foreign key and applies them in one transaction.\n\nPre-1.0: APIs and config may change between releases.\n\n### Seed files\n\nPut seed files in `seeds/`. They run in alphabetical order, so name them `01-authors.ts`, `02-posts.ts`. Files ending `.ts`, `.mts` or `.tsx` are found. When `seeds/` holds none, `seed.ts` at the project root runs instead.\n\nEach file exports a default function. The function does not connect or await anything. It records the writes, and the engine applies them.\n\n`seeds/01-blog.ts`:\n\n```ts\nimport type { SeedContext } from \"@supatype/cli/seed\"\n\n// Sign-in users are not seeded. Create one first, then paste the id list-users prints:\n// supatype admin create-user --email alex@example.com --role editor\n// supatype admin list-users\nconst ALEX = \"<id from supatype admin list-users>\"\n\nexport default async function seed({ db, expr, log }: SeedContext) {\n log(\"seeding authors, tags and posts\")\n\n db.author.upsert({\n where: { id: ALEX },\n data: { id: ALEX, name: \"Alex Rivera\" },\n })\n\n db.tag.upsert({ where: { name: \"news\" }, data: { name: \"news\" } })\n\n db.post.upsert({\n where: { slug: \"hello-world\" },\n data: {\n title: \"Hello world\",\n slug: \"hello-world\",\n body: \"Our first post.\",\n kind: \"news\",\n views: expr.default(),\n published_at: expr.ago({ days: 1 }),\n author: { connect: { id: ALEX } },\n comments: { create: [{ user_id: ALEX, body: \"First!\" }] },\n },\n })\n}\n```\n\nThis uses the schema from the [Schema](https://www.supatype.com/docs/schema.html#relations) page.\n\n### The builder\n\n`db` has one property per table, typed from your schema. A wrong column or a missing required field fails to compile.\n\nThe types come from `supatype/generated/seed.ts`, which is gitignored. `supatype generate`, `dev` and `push` write it, and a project made by `supatype init` also rebuilds it on install.\n\nThe context also has `expr` (values the database computes), `log` (print a line) and `environment` (the `--environment` name, if given).\n\n`db.$if(condition, body)` runs `body` only when the database says so. The builder never connects, so the engine checks the condition when the seed runs. Use a plain `if` for anything your own code can decide.\n\n`seeds/02-tags.ts`:\n\n```ts\nimport type { SeedContext } from \"@supatype/cli/seed\"\n\nexport default async function seed({ db }: SeedContext) {\n db.$if({ notExists: { model: \"Tag\" } }, () => {\n db.tag.create({ name: \"general\" })\n })\n}\n```\n\nThe condition is `{ exists }` or `{ notExists }`, naming a model and an optional `where`, or `{ environment: \"staging\" }`.\n\nWithout `where`, the condition asks whether the table has any row. A `where` names the rows to look for, in one of two forms:\n\n`seeds/03-once.ts`:\n\n```ts\nimport { like, type SeedContext } from \"@supatype/cli/seed\"\n\nexport default async function seed({ db }: SeedContext) {\n // Columns and values, like an upsert's `where`: every column equals its value.\n db.$if({ notExists: { model: \"Tag\", where: { name: \"general\" } } }, () => {\n db.tag.create({ name: \"general\" })\n })\n\n // A rule, for anything else: eq, neq, gt, gte, lt, lte, like, oneOf, isNull, notNull, and, or, not.\n db.$if({ notExists: { model: \"Tag\", where: like(\"name\", \"team-%\") } }, () => {\n db.tag.create({ name: \"team-default\" })\n })\n}\n```\n\nIn the plain form a value is a string, number, bigint, boolean, `Date` or `null` (which matches an empty column). Each is written the way an upsert's `where` writes it, so a decimal column matches exactly. A value an earlier call returned, such as `alex.id`, cannot be compared there: the condition is checked against values known before the seed runs.\n\nA file can also export a `config`. `runOnce: true` applies the file at most once, for a one-time backfill. It covers the whole run: if one file sets it, every file in that run gets it, with a warning.\n\n`seeds/01-blog.ts`:\n\n```ts\nexport const config = { runOnce: true }\n```\n\n### Create and upsert\n\n| Call | Does |\n| --- | --- |\n| `db.tag.create(data)` | Inserts one row. Running the seed again inserts it again |\n| `db.tag.createMany(rows)` | Inserts many rows in one statement |\n| `db.tag.upsert({ where, data })` | Inserts the row, or updates the row `where` names |\n\nUse `upsert` for fixtures. Seeds get run again, and `upsert` makes that safe. `where` takes only columns that name one row: the primary key or a `Unique<>` column. A model with neither cannot be upserted, so give it a unique key.\n\nFields you leave out of `data` keep their current value when an upsert updates.\n\n### Relations\n\nSet a foreign key by naming the related row by any unique key:\n\n`seeds/02-posts.ts`:\n\n```ts\ndb.post.upsert({\n where: { slug: \"second-post\" },\n data: {\n title: \"Second post\",\n slug: \"second-post\",\n body: \"More news.\",\n kind: \"news\",\n author: { connect: { id: ALEX } },\n },\n})\n```\n\n`create` and `upsert` return a reference you can use in later writes, such as `post.id`. It is a placeholder, filled in with the real value when the seed is applied. `createMany` returns nothing, so use `create` for a row you need to reference.\n\n`seeds/02-posts.ts`:\n\n```ts\nconst tag = db.tag.create({ name: \"release\" })\nlog(`created a tag, referenced as ${JSON.stringify(tag.id)}`)\n```\n\n### Nested children\n\nWrite a row's children inside it with `create` or `createMany`. Their foreign keys are filled in for you.\n\nUnder an `upsert`, a child is written only if the parent has no child with the same values. So:\n\n- Running the seed again adds nothing.\n- A child whose values you changed is added beside the old one. The old one stays.\n- A child that matches is not updated. To change one, upsert it on its own model by a unique key.\n- Values the database computes, fields left out and `expr.default()` are not compared.\n\n### Rich text and defaults\n\nA `RichText` field takes a plain string. It becomes a one-paragraph document. Rich text inside a block is not converted, so write the full document there.\n\nA `Blocks` entry is `{ type, data }`, with the block's fields under `data`, as Studio stores it. See `sections` below.\n\nA column stored as `jsonb` takes an object or an array as it is. A string is read as JSON text, so a value that is itself a JSON string needs its quotes: `alert: JSON.stringify(\"outbid\")`, not `alert: \"outbid\"`, which fails with `invalid input syntax for type json`. This includes a field whose type push stores as `jsonb` by fallback, such as a single string literal type.\n\n`expr` gives values the database works out when the seed runs:\n\n`seeds/02-posts.ts`:\n\n```ts\ndb.post.upsert({\n where: { slug: \"launch-day\" },\n data: {\n title: \"Launch day\",\n slug: \"launch-day\",\n body: \"We are live.\",\n sections: [{ type: \"hero\", data: { heading: \"We are live\" } }],\n kind: \"news\",\n views: expr.default(),\n published_at: expr.now({ days: 7 }),\n author: { connect: { id: ALEX } },\n },\n})\n```\n\n`expr.now()`, `expr.ago({ days: 1 })`, `expr.startOf(\"day\", { days: 30, hours: 9 })` and `expr.startOfBefore(\"month\", { months: 1 })` are times. `startOf` moves forward from the start of the period and `startOfBefore` moves back. They only fit date fields.\n\n`expr.default()` sets the column's own default. It is sent as `{ \"$default\": true }`. Leaving a field out of an upsert keeps the old value. `expr.default()` resets it. It only fits columns that have a default.\n\nLeave `id` out and the database makes one.\n\n### Sign-in users\n\nA seed cannot create sign-in users. Users live in the auth schema, which the seed builder does not reach. Create them first, then put their ids in the seed:\n\n```sh\n$ supatype admin create-user --email alex@example.com --role editor\n$ supatype admin list-users\n```\n\n`create-user` also gives the user a Studio role (`admin` if you do not pass `--role`). `list-users` prints each id.\n\nFor app users with no Studio access, sign them up through the client's `auth.signUp`, or create them in Studio under Authentication > Users with Studio access set to \"No access\".\n\nA `SupatypeAuthUserId` field with `onDelete` has a foreign key to the user, so the user must exist before the seed runs.\n\n### Many-to-many rows\n\nMany-to-many relations have no nested write yet. The rows live in the junction table, which the builder does not list, so a seed writes them with `db.$sql`, which runs in the same transaction. (App code can write the same rows through the client: see [Linking many-to-many rows](https://www.supatype.com/docs/client.html#many-to-many).)\n\n`seeds/03-tags.ts`:\n\n```ts\ndb.$sql(\n `insert into post_tag (post_id, tag_id)\n select p.id, t.id from post p, tag t\n where p.slug = $1 and t.name = $2\n on conflict do nothing`,\n [\"hello-world\", \"news\"],\n)\n```\n\nThe statement runs at its position in the file, after every write above it, so it can read the rows those writes made.\n\nEach param binds by its JSON type: a string as `text`, a whole number as `bigint`, any other number as `double precision`, a boolean as `boolean`, and an object or array as `jsonb`. A column of another type needs a cast on its placeholder, such as `$1::uuid`. That includes an id taken from an earlier write, such as `post.id`, which binds as text:\n\n`seeds/03-tags.ts`:\n\n```ts\nconst post = db.post.upsert({\n where: { slug: \"release-notes\" },\n data: {\n title: \"Release notes\",\n slug: \"release-notes\",\n body: \"What changed.\",\n kind: \"news\",\n author: { connect: { id: ALEX } },\n },\n})\ndb.$sql(\n `insert into post_tag (post_id, tag_id)\n select $1::uuid, t.id from tag t where t.name = $2\n on conflict do nothing`,\n [post.id, \"news\"],\n)\n```\n\n> **ONE PARAM PER PLACEHOLDER:** Pass exactly one param for each of `$1` to `$n` in the statement. A count that does not match is refused before anything runs. A param is a value, so write expressions such as `now()` in the statement itself.\n\nA JavaScript `bigint` is sent as its digits, and a `Date` as an ISO timestamp. Both bind as text, so cast them: `$1::bigint`, `$2::timestamptz`. `expr` values, `expr.default()` included, are refused as params.\n\n### Running seeds\n\n```sh\n$ supatype seed # every file in seeds/\n$ supatype seed seeds/02-posts.ts # one file\n$ supatype seed --atomic # all files in one transaction\n$ supatype seed --status # what ran, when, and what changed since\n$ supatype seed --connection <dsn> # another database, from this machine\n$ supatype seed --env staging # a linked project's environment\n$ supatype seed --local # the local stack, even when linked\n$ supatype seed --environment staging\n```\n\n`--status` lists each applied file with its status, when it ran, how long it took, and whether the file has changed since. `--environment` names the environment for an `{ environment }` condition.\n\nA Docker project's local stack has to be running: with it stopped, `supatype seed` starts nothing and exits 2, saying to start it with `supatype dev`, or `supatype self-host compose up -d` on a server. `--connection` seeds the database it names either way.\n\nEach file is one transaction. Without `--atomic`, a failure in the third file leaves the first two applied, and the report says so.\n\nErrors name your schema, such as `Tag.name is already taken`, with the file and position. Exit code `1` means a seed failed. Exit code `2` means the run could not start.\n\nA seed writes the model's own table, so rows on a drafts model are seeded as published.\n\n#### A linked project\n\nA project linked with `supatype link`, to Supatype Cloud or to a self-hosted server, seeds through that server. The CLI collects your files as it does locally and sends the result to the server, which applies it as the environment's own database role. The CLI never holds the database credential. `--env <name>` picks the environment, and the link's default is used without it.\n\n- Seeding production asks you to type the project ref. In a script, or with no terminal, pass `--confirm-production`. A self-hosted server's one environment is production.\n- `--force` is refused on a linked project. Use `--confirm-production` to skip the prompt, or `--local` to seed the stack on this machine instead.\n- `--environment` must match the environment being seeded, because that is what an `{ environment }` condition reads. Drop it, or pass `--env` with the same name.\n- Every file must `export default` a function. A file without one would run its writes when it is read, so it is refused before anything is sent.\n- The server refuses with `schema_not_pushed` when the database lacks the schema the seed was built against. Run `supatype push` first.\n- `--status` needs only permission to view the project. Applying a seed needs permission to push the schema.\n- `--connection` and `--local` skip the link and seed the database or stack on this machine.\n\n## Studio\n\nSource: https://www.supatype.com/docs/studio.html\n\nStudio is the admin app that ships with every Supatype stack. It builds content editors from your models and gives developers the API docs, a SQL runner and the database history in one place.\n\nPre-1.0: APIs and config may change between releases.\n\n### Open Studio\n\nStudio is served at `/studio/` on the project's gateway.\n\n- **Local, Docker (the default):** `supatype dev` prints it in the **Services running** panel as `http://localhost:<gateway-port>/studio/`. The port is `SUPATYPE_KONG_PORT` in `.env`.\n- **Self-hosted:** `http://<your-host>:<gateway-port>/studio/`, or `/studio/` on your domain once HTTPS is on. See [Self-host](https://www.supatype.com/docs/#self-host).\n- **Local, Native:** `supatype dev` does not start Studio with the Native provider.\n\nSign in with an email and password. The first admin comes from `SUPATYPE_ADMIN_EMAIL` and `SUPATYPE_ADMIN_PASSWORD` in `.env`, as described in [Local development](https://www.supatype.com/docs/#local-dev). Add more people with `supatype admin create-user`.\n\nStudio also offers every OAuth provider the project has enabled. To offer only some, name them in `supatype.config.ts`:\n\n`supatype.config.ts`:\n\n```ts\nstudio: { auth: { providers: [\"github\"] } }\n```\n\nSigning in is not enough on its own. Every person also needs a [Studio role](https://www.supatype.com/docs/studio-roles.html).\n\n### Finding your way\n\nThe sidebar lists, top to bottom: Dashboard and Models; Database and Media & Storage; Authentication; Edge Functions, Static site and Realtime; and Plugins. Settings is pinned at the bottom.\n\nSome entries depend on who you are or where Studio runs. Authentication is hidden from editors and viewers. Realtime is hidden when the server does not offer the Realtime inspector. Static site appears only when the host (Supatype Cloud or a self-host deployment that provides it) describes a site, and its Deployments page needs a host that can list deployments.\n\nFeatures that are not built yet have no sidebar entry. Some pages inside a group still say a feature is coming soon: Database Wrappers, Read Replicas and Analytical Warehouse under Database, Backups there too except on Supatype Cloud, and Auth Hooks and Attack Protection under Authentication.\n\nThe Static site group shows the site address, whether it is served from files or proxied to an app, and what is served, with a Settings page for the serving mode, SPA fallback and response headers. A setting that `supatype.config.ts` sets is marked as such. Where a deployment can list site deployments, the group has a Deployments page. A deployment that cannot describe its site has no Static site group.\n\n**Jump to** in the top bar searches pages, users and records.\n\nIf the newest schema push was refused or failed, a notice shows above every screen. It says that nothing was applied and links to that push in the migration history. It goes away once a push applies.\n\n### Editing content\n\nStudio reads your schema after each push and builds an editor for every model. There is nothing to configure: add a model, save, and it appears under **Models**.\n\n#### The list\n\nEach model opens on a list of its records. Columns you can sort have sortable headers. Fields wrapped in `Searchable<T>`, or named in the model's `searchable: [...]` option, get a search box. Tick rows to delete several at once, after a confirmation. **Create Post** (named after the model) opens an empty form.\n\n#### The record editor\n\nEach field gets an input that matches its type: text, numbers, dates, slugs, selects, relations, JSON, code, images, files, rich text and blocks among them. The model's name in Studio comes from `label` and `labelPlural` in its options. A form also has **Duplicate** and **Delete**, and Delete asks first.\n\nA `Slug<\"title\">` field follows the title on a new record. A model with hooks shows \"This post has custom logic that runs on save.\"\n\nA singleton model (`singleton: true`) is listed under **Globals** and opens straight into its one record.\n\nIf the project has more than one locale, a language switcher appears in the top bar on content screens.\n\n#### Model tabs\n\nEach model has tabs beside the editor:\n\n| Tab | Shows |\n| --- | --- |\n| Schema | The model's fields as the database has them |\n| Rules | Field bounds, constraints and indexes, as the database enforces them |\n| Data | A table browser for the model's table, with filters, inline edits and a record inspector |\n| API | REST examples for this model |\n| GraphQL | GraphQL examples for this model |\n| Cache | The model's cached REST responses |\n\nEditors do not see Schema or Rules. Cache is for admins and developers.\n\nWhen the cache service refuses a request, the Cache tab shows the reason the server gave, with the HTTP status after it. If the project has no keyspace behind the cache yet, it says that nothing is cached and reads go straight to the database.\n\n### Rich text and blocks\n\nA `RichText` field opens a rich text editor with a toolbar for bold, italic, underline, strikethrough, headings 1 to 3, paragraphs, bullet lists and numbered lists. The field stores a Lexical document.\n\nA `Blocks<T>` field is a list of sections. An editor adds a block by type, fills in its fields, and can move or duplicate it. See [Slugs, rich text and blocks](https://www.supatype.com/docs/schema.html#content) for how they are declared and stored.\n\nTo render a rich text field in React, pass the stored value to `RichText` from `@supatype/react`:\n\n`src/PostBody.tsx`:\n\n```tsx\nimport { RichText } from \"@supatype/react\"\nimport type { TableRow } from \"@supatype/client\"\n\nexport function PostBody({ post }: { post: TableRow<\"post\"> }) {\n return <RichText content={post.body} as=\"article\" />\n}\n```\n\n### Media and files\n\n**Media & Storage** lists your buckets. Each bucket has two tabs:\n\n- **Files:** browse folders, upload files (or drop them on the page), create folders, and download or delete files. **Details** shows a file's size, type, owner, dates and its public URL.\n- **Policies:** the bucket's access rules. Who can read or change them is on [Studio roles](https://www.supatype.com/docs/studio-roles.html#matrix).\n\nDeclare buckets in your schema with `Bucket<>` so they are versioned with everything else. Studio can create one by hand, but warns first and recommends the schema instead. See [Storage](https://www.supatype.com/docs/storage.html).\n\nAn image field in the record editor takes a dropped file, an **Upload**, or **Select from bucket**, which browses the bucket the field names. A localized image field uploads one image per locale.\n\n### Drafts and publishing\n\nOn a model with `versions: { drafts: true }` (see [Drafts and versions](https://www.supatype.com/docs/schema.html#drafts)), the editor's side panel holds the publishing controls:\n\n- **Save draft** saves without changing what readers see. On a new record the first save creates it.\n- **Publish** makes the saved draft live, saving any unsaved edits first.\n- The menu beside Publish has **Schedule publish...** (and **Change schedule...** or **Cancel schedule** once one is set), **Discard changes**, which returns the draft to the published version, and **Unpublish**, which keeps the content as a draft.\n\nA status badge shows Draft, Published, Scheduled or Partly published, and \"Changed\" when there are edits since publishing. With several locales a record can be published, and unpublished, per language.\n\nA draft may leave a required field empty. Studio asks before saving it, and it cannot be published until the field is filled.\n\nWho sees drafts and the publish controls is set by `publishing.draft_visibility`. See [Drafts and publishing](https://www.supatype.com/docs/studio-roles.html#drafts) in Studio roles, which also covers saving drafts from the Data tab.\n\n### Version history\n\nA model with `versions` keeps a history of each record. On a model with drafts, open it with **History** in the publishing panel. Each version shows when it was saved, by whom, and its state: Live, Scheduled, Pending draft or Superseded. Select a version to compare its fields with the newest one.\n\n- **Restore as draft** brings the version back as the current draft. Nothing goes live until it is published.\n- **Publish this version** restores it and publishes it in one step.\n\nA model without `versions` says so, and keeps no history.\n\n### Live preview and preview links\n\nTell Studio where each model renders in your app with `admin.livePreview`, keyed by model name. Field names in braces are filled from the record:\n\n`supatype.config.ts`:\n\n```ts\nadmin: {\n livePreview: {\n Post: { urlPattern: \"/preview/{slug}\" },\n },\n},\n```\n\nA path is enough when the same stack serves your app (`app.mode` is `static` or `proxy`). With `app.mode: \"none\"` give a full URL. `supatype push` refuses a path in that mode.\n\n#### Live preview\n\nWith this set, the editor gets a **Live preview** button. It opens your page in a side panel and sends the unsaved form values to it on every change. Read them with `useLivePreview`:\n\n`src/PostPreview.tsx`:\n\n```tsx\nimport { useLivePreview } from \"@supatype/react\"\n\nexport function PostPreview({ post }: { post: { title: string } }) {\n const { data, isPreview } = useLivePreview({ initialData: post, model: \"Post\" })\n return <h1>{data.title}{isPreview && \" (preview)\"}</h1>\n}\n```\n\n`model` is the schema's model name, as in `admin.livePreview`. The hook only accepts messages from the window that frames the page, at Studio's origin. By default that is the origin of the client in `SupatypeProvider`. If Studio is served somewhere else, pass `studioOrigin`.\n\n#### Share a preview\n\nOn a saved record, **Share a preview** makes a link for someone without an account. Choose how long it lives: 15 minutes, 1 hour, 1 day or 7 days. The link is your preview URL with a `preview` query parameter. Studio lists the links it has made, and each can be revoked.\n\nOn the preview page, create a client with that code as `previewCode` and read the draft with `.draft()`. The code is the client's whole credential: it cannot be combined with `serviceRoleKey`. See [Drafts and publishing](https://www.supatype.com/docs/client.html#drafts) in Client.\n\n### API docs\n\n**Settings > API > REST** opens the REST docs. They are built from your models plus the auth and storage endpoints. Each endpoint lists its parameters, an example body and response, and a curl example. Filter by category or table, or search.\n\n**Try it** sends a real request and shows the response headers and body. It asks who to send as: yourself, anonymous, the service role or a pasted token. See [Send as](https://www.supatype.com/docs/studio-roles.html#send-as).\n\nThe REST section also has Settings and Cache tabs for admins and developers.\n\n### GraphQL explorer\n\nThe GraphQL page sends queries to `POST /graphql/v1`. Pick a model to start from a list query, edit it, and press **Run**. It uses the same Send as choice as Try it. Each model's GraphQL tab has examples for that model.\n\n### SQL runner\n\n**Database > SQL Runner** runs SQL against the project. Press **Run Query**, or Ctrl+Enter (Cmd+Enter on a Mac).\n\n- Each run opens a result tab with its time. Export a result as CSV or JSON.\n- Statements that drop, empty or overwrite data (`DROP`, `TRUNCATE`, `DELETE`, `UPDATE`, and an `ALTER` that drops something or turns off row level security) ask first and name what they change.\n- `EXPLAIN (FORMAT JSON)` draws the plan as a tree.\n- Query History lists earlier runs in this session.\n- A `DELETE` or `UPDATE` with no `WHERE` fails with `DELETE requires a WHERE clause`. That is `pg_safeupdate`, which the image loads for every session, this runner included. Write `WHERE true` to mean every row. On a connection of your own, `SET safeupdate.enabled = 0` turns the check off for that session.\n\n> **FULL ACCESS:** Queries run as `supatype_sql_editor`, which has the rights of the role that owns your tables. Row level security does not apply and masked columns show in full. It is not a superuser. Every query is recorded. Only admins and developers can open it.\n\n### Database, migrations and schema objects\n\nEditors do not see the Database pages. The SQL runner is for admins and developers only.\n\n| Page | Shows |\n| --- | --- |\n| Overview | A diagram of your tables and their relations |\n| Tables, Views, Triggers, Indexes, Constraints, Types, Roles, Extensions | The database's objects of that kind |\n| Migrations | Every push: its status, number of changes, when it was applied, who pushed it and the engine version. Open one to see its schema changes and its SQL. Filter by status and date, or search by name or id |\n| Schema objects | Every object Supatype manages, from the managed-object ledger, with its status (managed, adopted or released) and a link to the migration that last changed it |\n| Seeds | Each recorded `supatype seed` run: file, status, rows written, time and duration |\n\nAdopted and released objects come from [supatype adopt](https://www.supatype.com/docs/cli.html#schema). Seed runs are covered in [Seeding](https://www.supatype.com/docs/seeding.html#run).\n\n### Logs\n\nFunction logs are on the **Edge Functions** page. Pick a function and open its **Logs** tab. Live tail is on by default. Turn it off to read recent logs by time range, with optional auto-refresh. A deployment that runs functions inside the server process has no worker to tail, so Studio shows recent logs instead.\n\nThe same page has an **Invoke** tab to call a function, and **Environment Variables**. See [Functions](https://www.supatype.com/docs/functions.html).\n\n> **NOTE:** Under Observability, API request logs are not recorded yet. Auth, storage, realtime and Postgres logs are coming soon.\n\n### Other screens\n\n| Screen | For |\n| --- | --- |\n| Dashboard | Totals and recent activity for users, records, storage and the database |\n| Authentication | Users (including their Studio access), access policies, providers, SAML single sign-on (see [Single sign-on](https://www.supatype.com/docs/sso.html#studio)), configuration and email templates. Configuration is read-only: change those settings in `.env` and restart the stack. A template saved under Email Templates is kept in the database until **Reset to default** removes it. See [Auth](https://www.supatype.com/docs/auth.html) |\n| Settings | API keys, CORS origins and database settings |\n| Realtime | Channels, clients, a live stream and a broadcast tester, where the deployment's control plane supports the inspector |\n\n### Roles\n\nWhat each person can see and change in Studio depends on their Studio role: admin, developer, editor or viewer. Admins and developers work with full access. Editors and viewers work within the role's limits, and field masks still apply to them.\n\nThe full table, field masking, Send as and how to give someone a role are on [Studio roles](https://www.supatype.com/docs/studio-roles.html).\n\n## Studio roles\n\nSource: https://www.supatype.com/docs/studio-roles.html\n\nEveryone who signs in to Studio has a Studio role. The role decides which screens they see and what they may change.\n\nPre-1.0: APIs and config may change between releases.\n\n### The four roles\n\nA self-hosted project has four Studio roles:\n\n**Admin**: Everything, including giving and removing Studio roles.\n\n**Developer**: Everything an admin can do, except Studio roles.\n\n**Editor**: Content and files. No schema, SQL or settings.\n\n**Viewer**: Reads content, files, schema and logs. Changes nothing.\n\nSupatype Cloud adds owner and billing roles for the organisation. On a self-hosted project those two grant nothing, and the CLI refuses any role but the four above.\n\n> **NOTE:** A Studio role is separate from your app. It grants nothing in your own application, and `Role<>` rules in the schema do not read it.\n\n### What each role can do\n\nThe server checks every Studio request against this table.\n\n| Can | Admin | Developer | Editor | Viewer |\n| --- | --- | --- | --- | --- |\n| Browse content and download files | Yes | Yes | Yes | Yes |\n| Edit content, upload and delete files | Yes | Yes | Yes | No |\n| See the schema, migrations and access rules | Yes | Yes | No | Yes |\n| See logs | Yes | Yes | No | Yes |\n| Push the schema | Yes | Yes | No | No |\n| Deploy functions, hooks and secrets | Yes | Yes | No | No |\n| Use the SQL editor | Yes | Yes | No | No |\n| Work with full access | Yes | Yes | No | No |\n| Use the realtime inspector | Yes | Yes | No | No |\n| Manage API keys, CORS and domains | Yes | Yes | No | No |\n| Manage the app's users | Yes | Yes | No | No |\n| See [SSO providers](https://www.supatype.com/docs/sso.html#studio) | Yes | Yes | No | Yes |\n| Change [SSO providers](https://www.supatype.com/docs/sso.html#studio) and verify their domains | Yes | No | No | No |\n| Create, change and delete buckets | Yes | Yes | No | No |\n| Give and remove Studio roles | Yes | No | No | No |\n\n> **SQL EDITOR:** The SQL editor signs in as `supatype_sql_editor`. It is not a superuser, but it is a member of the database owner. Row level security does not apply there, and masked columns show in full. Every query is recorded. After each statement, everything the editor created is handed to the project owner. A table, view or function you make there ends up owned by the owner, not by `supatype_sql_editor`. A `SECURITY DEFINER` function written in the editor therefore runs with the owner's rights, and the owner is not a superuser.\n\n> **BUCKET RULES:** A bucket's access rules page is part of \"see the access rules\". Viewers and editors see it read-only. Only admins and developers can change the rules.\n\n### Full access and Studio mode\n\nAdmins and developers work with full access. Studio acts for them as the service role, so your app's access rules and field masks do not apply. An amber \"Full access\" banner shows while project rows are on screen. Every change is recorded.\n\nEditors and viewers work in Studio mode. Your app's row rules are skipped, so the Studio role decides which rows they reach. Field rules still apply, so masked columns stay masked. Every change is recorded.\n\nThere is no switch for this on content screens. To see data as an app user would, use [Send as](https://www.supatype.com/docs/studio-roles.html#send-as).\n\nThe project MCP, which lets an agent work with a running project's records, acts with the signed-in person's Studio role: a viewer's agent can only read, and only an admin's or developer's agent may ask for full access. See [MCP servers](https://www.supatype.com/docs/mcp.html#project-roles).\n\n### Field masking\n\nA column with a [field rule](https://www.supatype.com/docs/schema.html#field-rules) shows a padlock in Studio:\n\n- A padlock alone: the value is hidden from you.\n- A padlock with a question mark: the column is restricted per record, and this value is hidden or empty.\n- A value with a small padlock: you can see it, but other callers may not.\n\nIn forms, a column you cannot read shows the padlock. A column you can read but not write is disabled. Admins and developers see every value with the small padlock, because masks do not apply to full access.\n\n### Send as\n\nThe API page's Try it, the GraphQL explorer and a function's Invoke tab ask who to send the request as:\n\n| Choice | Sends | Offered to |\n| --- | --- | --- |\n| Me (default) | Your own token. Your app's access rules apply to you | Every role |\n| Anonymous | The anon key, as a visitor who is not signed in | Every role |\n| Service role | The service role. No rules apply. The key never reaches the browser | Admins and developers |\n| A token I paste | A token you paste, such as a test user's | Every role |\n\nThe choice applies to one request and is not remembered. The Invoke tab is on the Edge Functions page, which only admins and developers can open.\n\n### Drafts and publishing\n\nOn a model with drafts, the record editor shows Save draft and Publish. Its menu also schedules, discards and unpublishes.\n\nAdmins, developers and editors see drafts by default. Change this with `publishing.draft_visibility` in `supatype.config.ts`. A role that cannot see drafts does not get the publish controls.\n\nIn the Data browser, saving a cell or adding a row on a drafts model asks first:\n\n- Save as draft: the change is stored as a draft, and a new row is created unpublished. The cell keeps the live value with a Draft badge until the record is published.\n- Save and publish: the change goes live now, with any earlier draft changes to that record. A new row is created and published.\n\n> **DELETES ARE PERMANENT:** Deleting a row in the Data browser deletes it for good. It does not make a draft.\n\n### Giving someone a role\n\nIn Studio, open Authentication > Users. The Studio access column shows each user's role. An admin can change it there, or choose No access. Developers see it read-only. Editors and viewers have no Authentication page. Your own row cannot be changed.\n\nCreate User has a Studio access choice too. Only admins see it.\n\nFrom the command line:\n\n```sh\n$ supatype admin create-user --email sam@example.com --role editor\n$ supatype admin set-role --email sam@example.com --role viewer\n$ supatype admin list-users\n```\n\n`create-user` makes a new sign-in user with a Studio role. `--role` is `admin`, `developer`, `editor` or `viewer`, and defaults to `admin`. It asks for the password if you leave out `--password`. `supatype dev` and `supatype push` make sure a first admin exists.\n\n> **CLI:** The CLI writes the database directly. It does not run the checks Studio runs, such as keeping the last admin.\n\n### Only admins change admins\n\n- Only admins give, change or remove Studio roles.\n- A developer cannot change an admin's account: no disabling, deleting, password or email changes, MFA changes, signing out or sending links. The server refuses with \"Only a Studio admin can change another admin's account.\"\n- Nobody can change their own Studio role or remove their own access.\n- The last admin cannot be removed. Make someone else an admin first.\n\n## MCP servers\n\nSource: https://www.supatype.com/docs/mcp.html\n\nMCP is the Model Context Protocol. It is how a coding agent such as Claude Code or Cursor calls tools. Supatype has two MCP servers: one for working on your project's code and schema, and one for the content in a running project.\n\nPre-1.0: APIs and config may change between releases.\n\n### Which one to use\n\n| | Developer MCP | Project MCP |\n| --- | --- | --- |\n| For | Changing the project: schema, types, pushes, logs, docs | Working with the records in a running project |\n| Runs | On your machine, started by the agent with `supatype mcp` | As a service next to your project, at `/mcp` on its API URL |\n| Talks over | Standard input and output | Streamable HTTP |\n| Sign-in | None. It uses your machine and your linked project | Your Studio login, approved in the browser |\n| Acts as | You, through the CLI | You, with your Studio role |\n\nUse the developer MCP while you build. Use the project MCP when an agent should read or edit content, such as posts or products, in a project that is already running. You can add both.\n\n### Developer MCP\n\n`supatype mcp` starts an MCP server over standard input and output, for the project in the current directory. It prints nothing else, because the output carries the protocol. It finds the project's config and target the way every other command does, so it works against the local stack, a linked self-hosted server or a linked Supatype Cloud project. See [`supatype mcp`](https://www.supatype.com/docs/cli.html#mcp) in the CLI reference.\n\n#### Add it to your agent\n\nClaude Code. Run this in the project directory:\n\n```sh\n$ claude mcp add supatype -- supatype mcp\n```\n\nCursor. Add this to `.cursor/mcp.json` in the project:\n\n`.cursor/mcp.json`:\n\n```json\n{\n \"mcpServers\": {\n \"supatype\": {\n \"command\": \"supatype\",\n \"args\": [\"mcp\"]\n }\n }\n}\n```\n\nClaude Desktop reads the same `mcpServers` shape from `claude_desktop_config.json`. The server needs to start in your project directory, and this page does not cover how Claude Desktop sets that. Use Claude Code or Cursor for the developer MCP.\n\nThe `supatype` command must be on your `PATH`.\n\n#### Tools\n\nEvery tool returns structured data. A failure comes back as a tool error with the real message, and the server keeps running.\n\n| Tool | What it does | Arguments |\n| --- | --- | --- |\n| `get_schema` | The project's models, fields and access rules, as compiled from the schema files, with its buckets, channels and warnings | |\n| `diff` | What `supatype diff` shows: the operations a push would apply and the engine's warnings, and whether any operation is destructive. Changes nothing | `env` |\n| `push` | Applies the schema, as `supatype push` does, but never asks a question. See [Push rules](https://www.supatype.com/docs/mcp.html#dev-push) | `env`, `confirmDestructive` |\n| `generate_types` | Writes the generated types, client and hook types, as `supatype generate` does, and lists the files it wrote. It writes local files only | |\n| `status` | What `supatype status` reports: the linked target, or the local stack's services | `env` |\n| `logs` | Recent logs from the local Docker stack. It never follows | `service`, `since` (such as `5m` or `1h`), `tail` (1 to 1000, default 100) |\n| `search_docs` | Searches the documentation bundled with the CLI and returns the five best sections, each with an excerpt | `query` |\n\n`env` names the environment when the project is linked, as `--env` does on the commands.\n\n#### Push rules\n\nA person is not at the other end to answer a prompt, so `push` decides from its arguments what `supatype push` would have asked.\n\n- A diff with no destructive operation is applied.\n- A diff with a destructive operation, an operation that drops data, is refused. The refusal returns the diff and names `confirmDestructive`.\n- A push to a linked environment named `production` is refused, destructive or not. This covers a linked Supatype Cloud or self-hosted environment with that name. The local stack and a direct database connection are not treated as production.\n- Both refusals lift when the call carries `confirmDestructive: true`.\n\nThe refusal text tells the agent to show you the operations first and to pass the flag only if you agree. Nothing is applied when a push is refused.\n\nSome refusals need a person at a terminal. The agent gets a message that says so, and the plan with it:\n\n- The schema declares models for tables Supatype does not manage. The message names them and says to run `supatype push` in a terminal, which offers to adopt them.\n- Objects that decide who may read or write were changed outside Supatype. The message says to run `supatype push` in a terminal to review them, or `supatype push --overwrite-drift` to put Supatype's definitions back.\n- The engine is busy with another push. Try again shortly.\n- A direct database connection is missing something Supatype needs. The refusal lists the gaps.\n\n> **PRODUCTION:** `confirmDestructive: true` allows a destructive push and a push to production. Set up your agent so it asks you before it passes the flag.\n\n### Project MCP\n\nA running project serves an MCP endpoint at `/mcp` on its API URL. An agent signs in as you and works with the project's records using your Studio role. A self-hosted stack generated by the CLI runs it automatically, so the address is the project's public API URL plus `/mcp`. For a project at `https://api.example.com`, that is `https://api.example.com/mcp`.\n\n#### Add it to your agent\n\nClaude Code:\n\n```sh\n$ claude mcp add --transport http myproject https://api.example.com/mcp\n```\n\nCursor, in `.cursor/mcp.json`:\n\n`.cursor/mcp.json`:\n\n```json\n{\n \"mcpServers\": {\n \"myproject\": {\n \"url\": \"https://api.example.com/mcp\"\n }\n }\n}\n```\n\n`myproject` is a name you choose. Use one name per project if an agent works with several.\n\n#### Sign-in and approval\n\nThe first time the agent connects, it opens your browser at the project's approval page, `/studio/oauth/consent` on the API URL. Sign in with your Studio login and choose Approve. The agent then holds a token for that project's MCP endpoint and nothing else.\n\nThat token works only through the MCP. Sent straight to the project's API, its auth routes or Studio, it is refused, so a leaked token cannot skip the MCP's tools, limits and audit. The MCP proves each call it makes to the API server with a key only the two of them hold: `SUPATYPE_MCP_GATEWAY_KEY`, which a self-hosted stack generates into `.env` (see [Configuration](https://www.supatype.com/docs/self-hosting/configuration.html)). Agent sign-in checks are reused for up to 10 seconds; removing someone's Studio role still stops their data calls at once.\n\nOnly Studio members can use it. If you have no Studio role in the project, the agent's calls are refused. Give someone a role as described in [Studio roles](https://www.supatype.com/docs/studio-roles.html#grant).\n\n#### What each role can do\n\nThe agent acts with your Studio role, so it can do what you can do in Studio's content screens, and no more. The tools it is shown depend on the role.\n\n| Can | Admin | Developer | Editor | Viewer |\n| --- | --- | --- | --- | --- |\n| List models, read records, list versions | Yes | Yes | Yes | Yes |\n| Create, update and delete records | Yes | Yes | Yes | No |\n| Save drafts, publish, unpublish and make preview links | Yes | Yes | Yes | No |\n| Ask to act elevated | Yes | Yes | No | No |\n\nA viewer sees only the read tools. The other roles see every tool.\n\n#### Tools\n\nEach tool takes the model as an argument, by the name `list_models` returns.\n\n| Tool | What it does |\n| --- | --- |\n| `list_models` | Lists the models in the project |\n| `describe_model` | One model's table, key column and fields, and whether it keeps drafts |\n| `list_records` | Records of a model, with filters, order, columns and paging. See [Filters](https://www.supatype.com/docs/mcp.html#project-filters) |\n| `get_record` | One record by its key |\n| `create_record` | Creates a record. On a model with drafts it is created as an unpublished draft |\n| `update_record` | Changes fields of a record by its key. On a model with drafts it saves a draft |\n| `delete_record` | Deletes a record by its key and returns it. This cannot be undone |\n| `save_draft` | Saves a new draft of a record on a model with drafts. The live record does not change |\n| `publish` | Publishes a record's draft: the latest, or the `version` you name, in all locales or the `locales` you name |\n| `unpublish` | Takes a record off, in all locales or the `locales` you name |\n| `preview_link` | Makes a link that lets someone without an account read one record's draft. Its code is shown once. `ttl` sets how many seconds it lasts |\n| `list_versions` | A record's version history, newest first, with each version's status and locales |\n\n`create_record` and `update_record` take `values`, a JSON object of field names and values, with at least one field. A write goes through the project's API, so its field rules, hooks and validation apply, as they do in Studio.\n\n#### Drafts and publishing\n\nOn a model with drafts, `create_record` and `update_record` never change the live record. They store a draft, and the answer says so. The record goes live only when the agent calls `publish`. `list_versions` shows the versions to choose from.\n\n`save_draft`, `publish`, `unpublish`, `preview_link` and `list_versions` apply to models that keep drafts. On any other model they return an error that says to use `create_record`, `update_record` and `delete_record`. Reads take `draft: true` to show unpublished edits on a model with drafts. See [Drafts and publishing](https://www.supatype.com/docs/studio-roles.html#drafts) and [Schema](https://www.supatype.com/docs/schema.html) for how a model gets drafts.\n\n#### Filters\n\n`list_records` takes `filter`, an object of field names to `operator.value`, such as `{\"status\": \"eq.published\", \"views\": \"gte.100\"}`. Filters combine with AND. The operators are:\n\n| Operator | Matches |\n| --- | --- |\n| `eq`, `neq` | Equal, not equal |\n| `gt`, `gte`, `lt`, `lte` | Greater than, at least, less than, at most |\n| `like`, `ilike` | A pattern, case sensitive or not |\n| `is` | Null, true or false, such as `is.null` |\n| `in` | One of a list, such as `in.(a,b)` |\n| `cs`, `cd` | Contains, is contained by |\n\nA field the model does not have, or any other operator, is refused with a message that says why. Other arguments are `order` (a field name with an optional `.asc` or `.desc`), `columns`, `limit` and `offset`.\n\n#### Elevated mode and auditing\n\nEach call runs in an acting mode, chosen the way Studio chooses it:\n\n| Call | Mode |\n| --- | --- |\n| A read, with no `elevated` argument | Full access for an admin or developer. Studio mode for an editor or viewer |\n| A write, with no `elevated` argument | Studio mode, for every role |\n| `elevated: true` | Full access. Only admins and developers may ask. Other roles get an error |\n| `elevated: false` | Studio mode |\n\nFull access acts as the service role: your app's row rules and field masks do not apply. In Studio mode your app's row rules are skipped, and field rules and masks still apply. The same words are explained in [Full access and Studio mode](https://www.supatype.com/docs/studio-roles.html#modes).\n\nA role that is not allowed to read or write, or to act elevated, is refused with an error. It is never quietly given less, so an empty result is a real empty result.\n\nEvery call is recorded with the person who signed in, the agent (its OAuth client), the tool, the mode it ran in and the result. A refused call is recorded too.\n\n#### Limits\n\n- `list_records` returns 1 to 100 records per call, 20 if you do not say. Page with `offset`.\n- Each project has a cap on tool calls in flight at once. It is 8 unless the service is set otherwise with `SUPATYPE_MCP_MAX_CONCURRENT_CALLS`. A call over the cap is refused at once with \"too many tool calls in flight for this project, retry shortly\".\n\n## Deploy your frontend\n\nSource: https://www.supatype.com/docs/deploying-your-frontend.html\n\nA production build of your app needs two values: your deployment's API URL and its anon key. This page shows how each host gets them, and what you see when one is missing.\n\nPre-1.0: APIs and config may change between releases.\n\n### What a build needs\n\n`supatype init`, `supatype dev` and `supatype keys` write a local stack's URL and anon key to `.env.development.local`. Vite, Next.js and Expo read that file in development only, so a production build never ships `localhost`, and gets neither value from it. A production build gets them in one of three ways:\n\n| Way | Use it when |\n| --- | --- |\n| `supatype build` | You run the build command, on any host. It gives the build both values under every framework's name, and refuses to start without them. |\n| `supatype keys --print frontend` | You paste the values into a host's settings. It prints each name and value as a `NAME=value` line. |\n| `<script src=\"/supatype-env.js\" vite-ignore>` | Supatype serves the app, or it is a Next.js app with the route [below](https://www.supatype.com/docs/deploying-your-frontend.html#nextjs). The page reads both values from the server when it loads, so one build runs on every deployment that serves it. |\n\nEach framework reads its own names. `supatype build` and `keys --print frontend` give all of them:\n\n| Framework | API URL | Anon key |\n| --- | --- | --- |\n| Vite | `VITE_SUPATYPE_URL` | `VITE_SUPATYPE_ANON_KEY` |\n| SvelteKit, Astro | `PUBLIC_SUPATYPE_URL` | `PUBLIC_SUPATYPE_ANON_KEY` |\n| Next.js | `NEXT_PUBLIC_SUPATYPE_URL` | `NEXT_PUBLIC_SUPATYPE_ANON_KEY` |\n| Expo | `EXPO_PUBLIC_SUPATYPE_URL` | `EXPO_PUBLIC_SUPATYPE_ANON_KEY` |\n\nPass the values straight to `createClient`, as [Client: Create the client](https://www.supatype.com/docs/client.html#setup) does, with no check of your own in front of it. A bundler that knows a name is unset can turn such a check into a throw that hides the reason. The client checks for itself, and names what is missing.\n\n### supatype build\n\n```sh\n$ supatype build # runs the package.json build script\n$ supatype build -- vite build # or the command after --\n$ supatype build --env staging -- npm run build # for one linked environment\n```\n\nKeep the real build command, such as `vite build`, in package.json's `build` script. A build script that is itself `supatype build` is refused, since a bare `supatype build` runs that script: it stops and says the build script calls `supatype build` itself, so running it again would never end. A command after `--` runs even inside another build.\n\nIt runs your build with the deployment's API URL and anon key under all four prefixes. It writes no file: the values live only in the build's environment. The exit code is the build's own, so CI behaves as it did before. Each value is looked for on its own, in this order:\n\n| Source | Where it looks |\n| --- | --- |\n| The environment | `SUPATYPE_URL` and `SUPATYPE_ANON_KEY`, or any of the names above. A host's own settings always win. |\n| The server the URL names | For the anon key only, when the environment holds a URL: `<URL>/supatype-env.json`, the key that server publishes. HTTPS for an address that is not local, a local one only with `--allow-local`. A 503 there reads `the server at <url> is not set up to publish its anon key:` and the setting the server names. |\n| The linked environment | The one `--env` names, else the link's default. Supatype Cloud: the environment's address, and its anon key from the control plane, which needs `supatype login` (or `SUPATYPE_ACCESS_TOKEN`) as an owner or admin. Self-host: the link's address, and the anon key the server publishes at `/supatype-env.json`, fetched only over HTTPS for an address that is not local. |\n| `.env` | `PUBLIC_SUPATYPE_URL` or `API_EXTERNAL_URL`, and `ANON_KEY`, as the server's own `.env` holds them. |\n\nThe first source holding a value decides it. A local address there, such as `localhost` or `127.0.0.1`, stops the build rather than being passed over, because a production build would ship it. Pass `--allow-local` to build against a local stack anyway. A service role key offered as the anon key stops the build too: the service role key never reaches a build. An anon key counts only for the URL being built for: with `SUPATYPE_URL` naming one deployment and a link to another, the link's key is listed as `skipped ... not the URL being built for`, never paired with the wrong address.\n\n`.supatype/link.json` holds secrets and is never committed, so a CI host has no link. There, set `SUPATYPE_URL` in the host's settings: `supatype build` fetches the anon key from `<SUPATYPE_URL>/supatype-env.json`, copies both to every framework's names, and stops the build when one is missing. Set `SUPATYPE_ANON_KEY` as well only when that server does not publish it (`server.public_env: false`, or a plain `http://` address). `supatype deploy` builds your app with the same values, and takes `--allow-local` too.\n\n### Supatype hosts it\n\nA missing page on a plain static site serves `index.html`, on a self-hosted stack and on Supatype Cloud alike, so a single-page app's routes load on a refresh. Set `spa: false` in the `build` section of `supatype.config.ts` to answer 404 instead, and `spa: true` to turn the fallback on for a framework whose Cloud default is off. `supatype deploy` sends the setting to Cloud and `supatype self-host compose` gives it to the self-hosted server. With nothing set, both hosts take the same default from the framework: on for a plain static site, Vite and Remix SPA, off for Next.js, Astro, SvelteKit and Nuxt, whose pages are pre-rendered. A deploy with the fallback on refuses when the build has no `index.html` at its root: add one, or set `spa: false`.\n\nWhen a self-hosted stack serves your app (`app.mode: \"static\"`), its server answers `/supatype-env.js` with its own address and anon key:\n\n```sh\n$ curl https://example.com/supatype-env.js\nwindow.__SUPATYPE_ENV__ = {\"url\":\"https://example.com\",\"anonKey\":\"eyJhbGciOi...\"};\n```\n\n`supatype init` puts the tag in the head of the `index.html` it writes for a static app, so it runs before the app's own script. It never changes an `index.html` that is already there, such as the one in a Vite app made before `init` ran: it prints `skipped index.html (already exists)` and adds no tag. Until you add the tag, a build made without the values throws `MissingClientValuesError` on its first request. For such an app, or one made another way, add it yourself, before the app's own script:\n\n`index.html`:\n\n```html\n<script src=\"/supatype-env.js\" vite-ignore></script>\n<script type=\"module\" src=\"/src/main.ts\"></script>\n```\n\nLoad it as a plain script, without `async` or `defer`, before the app's own script. A plain script in the head has always run before any module script, wherever the app puts its own; with `async` it can run after it. When it has not run by the client's first request, that request throws, saying the page loads the script but it set no `window.__SUPATYPE_ENV__` in time.\n\n`vite-ignore` tells Vite to leave the tag as it is. The project has no such file, since the server answers it, so without the attribute every `vite build` warns `<script src=\"/supatype-env.js\"> in \"/index.html\" can't be bundled without type=\"module\" attribute`. Vite drops the attribute from the page it builds, and a browser ignores it, so the same tag does for a page with no build step. Do not make it `type=\"module\"`: Vite then tries to bundle it, and the build fails with `Failed to resolve /supatype-env.js`.\n\nThe client reads `window.__SUPATYPE_ENV__` for any value the build did not carry, at its first request. It never guesses the address from the page. A value the build did carry always wins. So a build made with neither value, by a plain `npm run build`, runs on every deployment that serves it. Served from the API's own origin, it needs no [allowed origin](https://www.supatype.com/docs/deploying-your-frontend.html#cors) either. To build on the server instead:\n\n`vm`:\n\n```sh\n$ supatype app add --static ./dist # once, then commit supatype.config.ts\n$ supatype build # reads API_EXTERNAL_URL and ANON_KEY from .env\n$ supatype self-host compose up -d\n```\n\n> **IF THE KEY IS MISSING:** `supatype build` stops before the build starts and lists every source it tried, as shown in [When a value is missing](https://www.supatype.com/docs/deploying-your-frontend.html#missing). A page built without the key and served without the script tag, or by a server with `server.public_env: false`, makes its first request throw in the browser console: `Supatype client has no anon key.`\n\n> **CLOUD:** For Supatype Cloud, `supatype build --env <name>` and `supatype deploy` read the environment's anon key from the control plane, so a build on a linked machine needs nothing set by hand. Each Cloud environment's API also answers `/supatype-env.json` and `/supatype-env.js` on its own address. On a CI host, use the sections below.\n\n### Next.js\n\nA Next.js app does not need its values at build time. `next build` prerenders pages without them, and the route `app/supatype-env.js/route.ts` serves them to each page load from `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` in the server's environment. `createServerClient` reads the same two, for Server Components, Route Handlers and middleware. `supatype init` writes the route and the root layout's script for an App Router app; [Frameworks: Next.js](https://www.supatype.com/docs/frameworks.html#nextjs) shows both, and the server client. So one build runs on every environment: set the two variables where the app runs. In development the route answers too: `supatype dev`, `init` and `keys --write` put the local stack's `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` in `.env.development.local`, which `next dev` reads.\n\n| Host | What to set |\n| --- | --- |\n| Vercel | `SUPATYPE_URL` and `SUPATYPE_ANON_KEY` under the project's Environment Variables, for each environment. The build command stays `next build`. |\n| Netlify | The same two, under the site's Environment variables. |\n| Your own Node server | The same two, in the environment of the process that runs `next start`. |\n\n`vm`:\n\n```sh\n$ npm run build\n$ SUPATYPE_URL=https://api.example.com SUPATYPE_ANON_KEY=eyJhbGciOi... npm start\n```\n\n`supatype keys --print frontend` prints the values to copy. The route is read on every page load and the server client on every call, so the same build started with another deployment's two values runs against that one. A value fixed into the build under `NEXT_PUBLIC_SUPATYPE_URL` or `NEXT_PUBLIC_SUPATYPE_ANON_KEY` still wins over the route's, so leave those unset in production. A Next.js app on its own host or server is on another origin from the API: add its address to the API's allowed origins, as in [Allow your app's origin](https://www.supatype.com/docs/deploying-your-frontend.html#cors). The server client uses them only where `SUPATYPE_URL` or `SUPATYPE_ANON_KEY` is unset.\n\nA static export (`output: \"export\"` in `next.config`) has no server to run the route, so `init` writes no route, no layout script and no `@supatype/ssr` for it, and prints the two ways instead: build with the values, `supatype build -- next build`, or have Supatype host the export (`supatype app add --static ./out`), whose server answers `/supatype-env.js` itself; add the `<Script>` tag to the root layout for that.\n\nA Pages Router app gets nothing written by `init`, which prints these steps instead: create the same route file under `app/supatype-env.js/`, beside `pages/`; in `pages/_document.tsx`, import `Script` from `next/script` and put `<Script src=\"/supatype-env.js\" strategy=\"beforeInteractive\" />` inside `<Head>`; add `@supatype/ssr` to the app's dependencies, and set the two variables where it runs.\n\n> **IF THE KEY IS MISSING:** The build still succeeds, and the page renders. With `SUPATYPE_ANON_KEY` or `SUPATYPE_URL` unset, `/supatype-env.js` still answers 200, not cached, but sets only the reason in place of the values: `window.__SUPATYPE_ENV__ = {\"error\":\"public env unavailable: SUPATYPE_ANON_KEY is not set on this server\"};`. With both unset it names both, a line each, the key first. It does the same when `SUPATYPE_ANON_KEY` holds a service role key, and answers 404 only when `SUPATYPE_PUBLIC_ENV` is off. A browser runs no script answered with an error status and tells the page nothing of why, so the reason travels in the script. The browser client's first request then throws `Supatype client has no API address and anon key. createClient was given none, and https://your-app.example.com/supatype-env.js set no API address and anon key, giving the server's reason instead:`, followed by that reason and `Fix that in the environment of the server that answers it`, then the route and the build-time variables. A server client given neither throws on its first request: `Supatype client has no API address and anon key. It was given none, and it is running on a server, where there is no page to read them from.`, followed by `Set SUPATYPE_URL and SUPATYPE_ANON_KEY in the server's environment`.\n\n### Expo\n\nAn Expo Router app has no `index.html`. Its web page is rendered from `app/+html.tsx`, or `src/app/+html.tsx` when the routes are in `src/app`. `supatype init` puts the script first in that file's `<head>`, and when the app has no such file, makes it from the template the installed Expo ships, as `npx expo customize +html.tsx` does. A web build then reads both values from the server that hosts it when the page loads, so `npx expo export --platform web` needs neither. The tag is left out of development pages: `expo start --web` serves no such file, and a development build reads its values from `.env.development.local`. In an app `init` did not set up, add the tag yourself:\n\n`app/+html.tsx`:\n\n```tsx\n<head>\n {__DEV__ ? null : <script src=\"/supatype-env.js\" />}\n <meta charSet=\"utf-8\" />\n```\n\nExpo renders `+html.tsx` only when `web.output` in `app.json` is `\"static\"` or `\"server\"`, as a new app's is. With `\"single\"`, put `<script src=\"/supatype-env.js\" vite-ignore></script>` in the head of `public/index.html` instead. A `\"static\"` export is plain files: have Supatype host them with `supatype app add --static ./dist`. A `\"server\"` export, the default from SDK 58, renders each page in a Node server (`npx expo serve`); the Supatype server in front of it answers `/supatype-env.js` itself, whatever the app mode. On any other host, build with the values instead.\n\nA native build, for iOS or Android and on EAS, has no page, so it takes its values at build time under `EXPO_PUBLIC_SUPATYPE_URL` and `EXPO_PUBLIC_SUPATYPE_ANON_KEY`. `expo export` and EAS builds run in production mode, which never reads `.env.development.local`, where `supatype dev` and `keys` put the local stack's values. Give them your deployment's: on a linked machine, build through `supatype build`; for an EAS build, set the two names in the project's EAS environment variables, with the values `supatype keys --print frontend --env production` prints.\n\n```sh\n$ supatype build -- npx expo export --platform android\n```\n\nAn Expo page with neither value makes the client's first request throw, naming `app/+html.tsx` and the build-time names rather than `index.html`.\n\n### Vercel\n\nPrint the values for the deployment on your own machine, where the project is linked:\n\n```sh\n$ supatype keys --print frontend --env production\nVITE_SUPATYPE_URL=https://api.example.com\nPUBLIC_SUPATYPE_URL=https://api.example.com\nNEXT_PUBLIC_SUPATYPE_URL=https://api.example.com\nEXPO_PUBLIC_SUPATYPE_URL=https://api.example.com\nVITE_SUPATYPE_ANON_KEY=eyJhbGciOi...\nPUBLIC_SUPATYPE_ANON_KEY=eyJhbGciOi...\nNEXT_PUBLIC_SUPATYPE_ANON_KEY=eyJhbGciOi...\nEXPO_PUBLIC_SUPATYPE_ANON_KEY=eyJhbGciOi...\n```\n\nIn the Vercel project's settings, under Environment Variables, add `SUPATYPE_URL` with that value, for each environment you deploy. `supatype build` fetches the anon key from the server it names; add `SUPATYPE_ANON_KEY` too if that server does not publish it. Then have Vercel build through the wrapper:\n\n`vercel.json`:\n\n```json\n{\n \"buildCommand\": \"npx supatype build\"\n}\n```\n\n`supatype build` copies the two values to `NEXT_PUBLIC_`, `VITE_` and the other names, then runs your build script. A Next.js app needs no wrapper on Vercel: see [Next.js](https://www.supatype.com/docs/deploying-your-frontend.html#nextjs).\n\nThen allow the site on the API: add its `*.vercel.app` address and any custom domain to the allowed origins, as in [Allow your app's origin](https://www.supatype.com/docs/deploying-your-frontend.html#cors).\n\n> **IF THE KEY IS MISSING:** The deployment fails at its build step, before your build starts. The build log shows `No anon key for a production build of the front end.`, each source tried, and ends `or set SUPATYPE_ANON_KEY.`\n\n### Netlify\n\nUnder the site's configuration, in Environment variables, add `SUPATYPE_URL`, and `SUPATYPE_ANON_KEY` only if the server does not publish its key, with the values `supatype keys --print frontend` prints. Then set the build command:\n\n`netlify.toml`:\n\n```toml\n[build]\n command = \"npx supatype build\"\n publish = \"dist\"\n```\n\n`publish` is your build's output directory: `dist` for Vite, `build` for SvelteKit's static adapter. Then add the site's `*.netlify.app` address and any custom domain to the API's allowed origins, as in [Allow your app's origin](https://www.supatype.com/docs/deploying-your-frontend.html#cors).\n\n> **IF THE KEY IS MISSING:** The deploy fails in its build step with the same refusal, and nothing is published: the site keeps serving the last deploy that built.\n\n### Cloudflare Pages\n\nIn the Pages project's settings:\n\n| Setting | Value |\n| --- | --- |\n| Build command | `npx supatype build` |\n| Build output directory | Your build's output, such as `dist` |\n| Variables and Secrets | `SUPATYPE_URL`, from `supatype keys --print frontend`, and `SUPATYPE_ANON_KEY` only if the server does not publish its key |\n\nThen add the project's `*.pages.dev` address and any custom domain to the API's allowed origins, as in [Allow your app's origin](https://www.supatype.com/docs/deploying-your-frontend.html#cors).\n\n> **IF THE KEY IS MISSING:** The build fails, and its log shows the refusal with each source tried. A variable added after the last build reaches only the next one, so retry the deployment once it is set.\n\n### GitHub Actions\n\nStore `SUPATYPE_URL` as a repository variable, under Settings, Secrets and variables, Actions. `supatype build` fetches the anon key from the server it names, so a self-hosted deployment needs nothing more: no link and no service role key in CI. Where the server does not publish the key, store `SUPATYPE_ANON_KEY` too; it is public, so a variable, not a secret, will do.\n\n`.github/workflows/build.yml`:\n\n```yml\nname: Build\n\non:\n push:\n branches: [main]\n\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-node@v4\n with:\n node-version: 22\n - run: npm ci\n - run: npx supatype build\n env:\n SUPATYPE_URL: ${{ vars.SUPATYPE_URL }}\n # Only where the server does not publish its key:\n # SUPATYPE_ANON_KEY: ${{ vars.SUPATYPE_ANON_KEY }}\n```\n\nPublish the output however you deploy it, and add the address it is served from to the API's allowed origins ([Allow your app's origin](https://www.supatype.com/docs/deploying-your-frontend.html#cors)). To give every later step the values under every framework's name instead, run `npx supatype keys --print frontend >> \"$GITHUB_ENV\"` with the same `env:`. To deploy to your own server over SSH and build there, follow [Deploy to a VM with GitHub Actions](https://www.supatype.com/deploy-vm-github-actions.html).\n\n> **IF THE KEY IS MISSING:** The `npx supatype build` step fails and the job stops there. A variable that does not exist reaches the step as an empty string, which counts as not set.\n\n### Your own server\n\nOn the server that runs the stack, `supatype build` needs nothing more: its `.env` records the deployment's `API_EXTERNAL_URL` and `ANON_KEY`.\n\n`vm`:\n\n```sh\n$ cd /opt/my-app\n$ git pull\n$ npm install\n$ supatype push\n$ supatype build\n$ supatype self-host compose up -d\n```\n\nTo build somewhere else, such as your laptop, set `SUPATYPE_URL` to the deployment's address, or link the deployment and name it:\n\n```sh\n$ supatype link --env production --url https://api.example.com --token \"$SERVICE_ROLE_KEY\"\n$ supatype build --env production\n```\n\nThen copy the output to whatever serves it, and add that server's address to the API's allowed origins ([Allow your app's origin](https://www.supatype.com/docs/deploying-your-frontend.html#cors)); built on the stack's own server and served by it, the app needs nothing. For a self-hosted link the anon key comes from `https://api.example.com/supatype-env.json`. It is fetched over HTTPS only, so a link to a plain `http://` address that is not local gives no key; set `SUPATYPE_ANON_KEY` instead. A Supatype Cloud link reads the key from the control plane.\n\n> **IF THE KEY IS MISSING:** On the server, `anon key from .env: no ANON_KEY` means the keys were never made: run `supatype keys`. `is a local address, which a production build would ship` means `API_EXTERNAL_URL` in `.env` is still a `localhost` address: set it to the server's public one.\n\n### Allow your app's origin\n\nA self-hosted API answers browsers only from the origin of its `SITE_URL` and the origins you list. An app served from anywhere else, such as Vercel, Netlify, Cloudflare Pages, a Next.js server of its own or a dev server on another port, is refused: the preflight gets 403, and the browser reports `Failed to fetch`. When Supatype serves the app, it is on the API's own origin and needs nothing here.\n\nList the app's origin in `supatype.config.ts`, or in `.env` as `SUPATYPE_CORS_ALLOW_ORIGINS`, comma-separated. Each entry is `scheme://host[:port]`, with no path:\n\n`supatype.config.ts`:\n\n```ts\n// supatype.config.ts (excerpt)\napi: { corsOrigins: [\"https://my-app.vercel.app\", \"https://www.example.com\"] },\n```\n\n`.env`:\n\n```ini\nSUPATYPE_CORS_ALLOW_ORIGINS=https://my-app.vercel.app,https://www.example.com\n```\n\n`vm`:\n\n```sh\n$ supatype self-host compose restart server\n```\n\nThe restart renders the compose file again and recreates the server with the new list. Owners, admins and developers can instead add the origin in Studio, on the Settings page's CORS tab, which needs no restart; a list saved there replaces the default until it is reset, and the site URL stays allowed whatever is saved. On Supatype Cloud, add it there. Each preview deployment with its own address is another origin. `supatype dev` allows every origin, so a local stack never shows this. The rest of the rules are under [Self-hosting](https://www.supatype.com/docs/#self-host), in Allowed origins.\n\n### When a value is missing\n\nAt build time, `supatype build` stops before the build starts, exits 1, and lists every source it tried for each value. With nothing set, in a project that is not linked:\n\n```sh\n$ supatype build\n\u2717 No API URL and no anon key for a production build of the front end.\n not set API URL from the environment: none of SUPATYPE_URL, VITE_SUPATYPE_URL, PUBLIC_SUPATYPE_URL, NEXT_PUBLIC_SUPATYPE_URL, EXPO_PUBLIC_SUPATYPE_URL is set\n not set anon key from the environment: none of SUPATYPE_ANON_KEY, VITE_SUPATYPE_ANON_KEY, PUBLIC_SUPATYPE_ANON_KEY, NEXT_PUBLIC_SUPATYPE_ANON_KEY, EXPO_PUBLIC_SUPATYPE_ANON_KEY is set\n not set anon key from the server SUPATYPE_URL names: no API URL in the environment to ask\n not set API URL from the linked environment: no .supatype/link.json (run `supatype link`)\n not set anon key from the linked environment: no .supatype/link.json (run `supatype link`)\n not set API URL from .env: no PUBLIC_SUPATYPE_URL or API_EXTERNAL_URL\n not set anon key from .env: no ANON_KEY\n\nRun `supatype build --env <name>` for a linked deployment, or set SUPATYPE_URL and SUPATYPE_ANON_KEY.\n```\n\nThe first line starts with `\u2717` in a terminal, and with `[supatype]` in a CI log or anywhere else the output is not a terminal. With `SUPATYPE_URL` set it starts `No anon key for a production build of the front end.`, and the line for the server the URL names says what that server answered.\n\n`supatype keys --print frontend` reads the same sources, refuses the same way, and names itself as the command to run. It takes `--allow-local` too, for printing a local stack's values: `supatype keys --print frontend --allow-local`. At run time, creating the client never throws, so `next build` can prerender a page that creates one at module scope. The first request a client makes without the anon key throws a `MissingClientValuesError` instead, so the browser console says what is wrong rather than the page going blank. The error starts `Supatype client has no anon key. createClient was given none, and the page had set no window.__SUPATYPE_ENV__ by its first request.` and goes on to name the build-time variables, `supatype build`, the script tag, and for Next.js the route and the server's `SUPATYPE_URL` and `SUPATYPE_ANON_KEY`. With no address either, it starts `Supatype client has no API address and anon key.` A page that already loads `/supatype-env.js` is not told to add it. When the server could not give the values, the script sets `error` in their place, and the first request quotes it and sends nothing, on every path: tables, rpc, functions, GraphQL, auth, realtime and storage. When the page has the script element but no `window.__SUPATYPE_ENV__` at all, the script did not run: it was blocked, failed to load, ran after the app's own script, or came from a server too old to serve it. The error says so, and to open the script in the browser to see what it answers.\n\n### The anon key is public\n\nThe anon key is not a secret. Every browser that loads your app holds it, which is why the server can publish it and a CI host can keep it as a plain variable. What protects your data is the [access rules](https://www.supatype.com/docs/schema.html#access) in your schema, which every request made with the anon key goes through.\n\nThe service role key passes every rule, so it never goes near a build. `supatype build` and `keys --print frontend` never output it, and refuse a service role key offered as the anon key. The server never serves it.\n\n`/supatype-env.json` and `/supatype-env.js` are on by default. For an API-only project, with no frontend for the server to serve, turn them off:\n\n`supatype.config.ts`:\n\n```ts\n// supatype.config.ts (excerpt)\nserver: {\n public_env: false,\n},\n```\n\nThe next `supatype self-host compose up -d` gives the server `SUPATYPE_PUBLIC_ENV=false`, and both addresses answer 404. A deployment that means to publish and cannot (no anon key, no URL, or a service role key in `SUPATYPE_ANON_KEY`) answers `/supatype-env.json` with 503 instead, with no caching and a body naming every setting to fix, and `/supatype-env.js` with 200, not cached, setting only `error` to the same text, which the browser client throws on its first request. `supatype dev` does the same. Turning them off does not make the anon key secret: every client of the API still holds it. It only stops the server publishing it, and `supatype build` for that deployment then needs `SUPATYPE_ANON_KEY` set.\n\n## Deploy to a VM with GitHub Actions\n\nSource: https://www.supatype.com/deploy-vm-github-actions.html\n\nCreate a project on your laptop, push it to GitHub, run the stack on a VM with Docker Compose, and ship schema and frontend changes on every push to `main`.\n\nPre-1.0: APIs and config may change between releases.\n\n### What you will have\n\n- One repository with `supatype.config.ts`, shared by local development and the VM.\n- A VM running `supatype self-host compose`, with the gateway serving HTTPS for your domain on ports 80 and 443.\n- A GitHub Action that connects over SSH, pulls, migrates, rebuilds static files and restarts Compose.\n\n> **SCOPE:** This guide covers self-hosting only. Supatype Cloud is a separate product.\n\n### Create the project locally\n\nOn your machine, with Node.js 20.19 or later, or 22.12 or later on Node 22: the CLI needs 18, and the Vite 8 app it sets up needs one of those.\n\n#### 1. Scaffold\n\n```sh\n$ npm install -g @supatype/cli\n$ mkdir my-blog && cd my-blog\n$ supatype init\n```\n\n`init` installs dependencies and writes generated secrets and API keys to `.env` for local development.\n\n#### 2. Add a static frontend\n\n```sh\n$ supatype app add --static ./public\n$ npm install -D vite\n# in package.json: \"build\": \"vite build\", with output in public/\n```\n\nCommit `supatype.config.ts`. You do not run `app add` again on the server.\n\nGive the deployment its domain while you are here. The gateway gets a Let's Encrypt certificate for it itself, so there is no reverse proxy to set up:\n\n```sh\n$ supatype add domain example.com --email you@example.com\n```\n\nThis writes `server.mode`, `server.domain` and `server.tls` to `supatype.config.ts`. `supatype dev` ignores them, so local development stays on `http://localhost`. See [Self-hosting](https://www.supatype.com/docs/#self-host) for the details.\n\n#### 3. Develop, then push to GitHub\n\n```sh\n$ supatype dev\n```\n\nOptionally proxy to Vite from a gitignored `supatype.local.config.ts` while production stays `static`. See [Deploy changes](https://www.supatype.com/docs/#deploy-changes).\n\n```sh\n$ git init\n$ git add .\n$ git commit -m \"Initial Supatype project\"\n$ git branch -M main\n$ git remote add origin git@github.com:YOUR_USER/my-blog.git\n$ git push -u origin main\n```\n\n### Prepare the VM\n\nA one-time setup on Ubuntu 22.04 or similar, with SSH access.\n\n#### 4. Install the tools and clone\n\n`vm`:\n\n```sh\n# Docker: https://docs.docker.com/engine/install/ubuntu/\n# Node.js 20.19 or later, or 22.12 or later on Node 22, which Vite 8 needs to build the app (Ubuntu's own nodejs package is older): https://nodejs.org/en/download\n$ sudo apt update && sudo apt install -y git\n$ sudo npm install -g @supatype/cli\n\n$ sudo mkdir -p /opt/my-blog\n$ sudo chown \"$USER\":\"$USER\" /opt/my-blog\n$ cd /opt/my-blog\n$ git clone git@github.com:YOUR_USER/my-blog.git .\n```\n\n#### 5. Write the production secrets\n\nCreate `/opt/my-blog/.env` on the server and never commit it. Generate each `CHANGE_ME` with `openssl rand -base64 48 | tr -d '/+='`, use a different value for each, and set your public URL. Compose refuses to start while any of the passwords or secrets is missing.\n\n`/opt/my-blog/.env`:\n\n```ini\nDATABASE_URL=postgresql://supatype_admin:CHANGE_ME@localhost:5432/my-blog\nPOSTGRES_USER=supatype_admin\nPOSTGRES_PASSWORD=CHANGE_ME # the same value as in DATABASE_URL\nPOSTGRES_DB=my-blog\nAUTHENTICATOR_PASSWORD=CHANGE_ME\nSUPATYPE_SQL_EDITOR_PASSWORD=CHANGE_ME\nSUPATYPE_CONTROL_PLANE_SECRET=CHANGE_ME\nSUPATYPE_KEYSPACE_PASSWORD=CHANGE_ME # the cache's password, from supatype/postgres 17.2.13\nJWT_SECRET=CHANGE_ME # at least 32 characters\n# Leave both keys blank. compose up mints them from JWT_SECRET.\nANON_KEY=\nSERVICE_ROLE_KEY=\nAPI_EXTERNAL_URL=https://example.com\nSITE_URL=https://example.com\n```\n\nThen run `supatype keys --write` in `/opt/my-blog`. It signs `ANON_KEY` and `SERVICE_ROLE_KEY` from this `JWT_SECRET` and adds the `VITE_SUPATYPE_URL` (`https://example.com`, from `API_EXTERNAL_URL`) and `VITE_SUPATYPE_ANON_KEY` copies your frontend build reads to `.env`. With a `localhost` or `127.0.0.1` `API_EXTERNAL_URL`, as on a test machine, it treats the stack as a local one and writes those copies to `.env.development.local` instead, which a production build never reads. Keys from your laptop will not work here, because they were signed with a different secret.\n\n#### 6. First boot\n\n`vm`:\n\n```sh\n$ cd /opt/my-blog\n$ npm install\n$ supatype self-host compose up -d\n$ supatype push\n$ supatype build\n$ supatype self-host compose up -d\n```\n\n`compose up` writes the compose file itself, so there is no separate render step.\n\nBefore this, point an A record for `example.com` at the VM and open ports 80 and 443 in its firewall. Then open `https://example.com`, with Studio at `/studio/`. Without a domain in `supatype.config.ts`, the gateway is on `http://YOUR_VM_IP:18473` instead. Backups, logs and rollbacks are covered in [Running in production](https://www.supatype.com/docs/#production).\n\n### Repository secrets\n\nIn your repository, open **Settings \u2192 Secrets and variables \u2192 Actions** and add:\n\n| Secret | Value |\n| --- | --- |\n| `VM_HOST` | Public IP or hostname of the VM |\n| `VM_USER` | SSH user, for example `ubuntu` |\n| `VM_SSH_KEY` | Private key (PEM) that can log in as `VM_USER` |\n| `DEPLOY_PATH` | Project directory on the VM, for example `/opt/my-blog` |\n\n> **NOTE:** The workflow never uploads `.env`. Production secrets stay on the VM.\n\n### The workflow\n\nAdd `.github/workflows/deploy-self-host.yml` to your repository:\n\n`.github/workflows/deploy-self-host.yml`:\n\n```yml\nname: Deploy self-host\n\non:\n push:\n branches: [main]\n workflow_dispatch:\n\njobs:\n deploy:\n runs-on: ubuntu-latest\n steps:\n - name: Deploy over SSH\n uses: appleboy/ssh-action@v1.2.0\n with:\n host: ${{ secrets.VM_HOST }}\n username: ${{ secrets.VM_USER }}\n key: ${{ secrets.VM_SSH_KEY }}\n script_stop: true\n script: |\n set -euo pipefail\n cd \"${{ secrets.DEPLOY_PATH }}\"\n git fetch origin main\n git reset --hard origin/main\n npm ci\n supatype push\n supatype build\n supatype self-host compose up -d\n```\n\nOn every push to `main` the VM pulls the latest code, applies schema migrations, rebuilds `public/` and refreshes Compose.\n\n> **NOTE:** `supatype push` reads `DATABASE_URL` from the VM's `.env`, which points at the Compose Postgres on `localhost:5432`. If you would rather not install the CLI globally on the VM, use `npx @supatype/cli` in the script.\n\n> **CHANGES THAT NEED A YES:** The push in CI has no terminal to ask in. A change that needs your consent, such as a drop, an undeclared rename or a large table rewrite, fails the job, and the log prints the command to run. Record renames with `supatype rename` and commit `supatype/renames.json`. After a Supatype upgrade, run the first push by hand over SSH.\n\n### Verify the pipeline\n\n#### 7. Push a change\n\n```sh\n$ git add .\n$ git commit -m \"Add posts and update the landing page\"\n$ git push origin main\n```\n\nWatch the run under **Actions** on GitHub. When it succeeds, load your gateway URL and check that the schema and static files changed.\n\n#### If something fails\n\n| Symptom | Check |\n| --- | --- |\n| SSH fails | The firewall allows port 22, and `VM_SSH_KEY` matches the VM's `authorized_keys`. |\n| `supatype push` fails | Compose is up, and `DATABASE_URL` points at `localhost:5432`. If it refused a change that needs your consent, see [The workflow](https://www.supatype.com/deploy-vm-github-actions.html#workflow). |\n| Site unchanged | `supatype build` writes to the directory in `app.static_dir`, then re-run `supatype self-host compose up -d`. |\n| `supatype build` fails | It lists each source it tried for the API URL and anon key. On the VM both come from `.env`: `API_EXTERNAL_URL` must be the public address, not `localhost`, and `ANON_KEY` must be set. See [Deploy your frontend](https://www.supatype.com/docs/deploying-your-frontend.html#missing). |\n\n> **RATHER NOT RUN IT YOURSELF?:** Supatype Cloud runs the same stack for you, and it is in closed beta. [Request access](https://www.supatype.com/#cloud), or [book a call](https://www.supatype.com/#contact) about self-hosting with support.\n\n## Coming from Supabase\n\nSource: https://www.supatype.com/from-supabase.html\n\nSupatype runs on Postgres with row level security, a REST and GraphQL API, auth, storage, realtime and functions, so most of what you know carries over. The difference is where it starts: you write TypeScript types and access rules, and Supatype writes the SQL, the policies and the client types from them.\n\n### What maps to what\n\n| In Supabase | In Supatype |\n| --- | --- |\n| `create table` in SQL migration files | A `Model<>` type in `schema/index.ts`. See [Models](https://www.supatype.com/docs/schema.html#models) |\n| RLS policies written with `create policy` | An `access` rule for `read`, `create`, `update` and `delete` on the model. Supatype turns it into row level security. See [Access rules](https://www.supatype.com/docs/schema.html#access) |\n| Column privileges and views to hide a column | A field rule under `access.fields`. A caller who may not read the column gets `null`. See [Field rules](https://www.supatype.com/docs/schema.html#field-rules) |\n| Applying migrations, then running `supabase gen types` | `supatype dev` locally, `supatype push` elsewhere. Both apply the schema and write the client types |\n| `supabase-js` | `@supatype/client`, imported from the generated `supatype/generated/client`. See [Create the client](https://www.supatype.com/docs/client.html#setup) |\n| Studio table editor | Supatype Studio: a form for each model built from its fields, version history and drafts, a media library, plus database views and a SQL runner. See [Studio roles](https://www.supatype.com/docs/studio-roles.html) |\n| Storage buckets and policies on `storage.objects` | A `Bucket<>` type with the same four rules as a model. See [Storage buckets](https://www.supatype.com/docs/schema.html#buckets) |\n| Supabase Auth | Supatype's auth service, reached through `supatype.auth`: sign up, password, magic links, OAuth, one-time codes and MFA. See [Auth](https://www.supatype.com/docs/client.html#auth) |\n| Realtime `postgres_changes` on a channel | `supatype.from(\"table\").subscribe()`. Broadcast and presence use `supatype.realtime.channel(name)`. See [Realtime](https://www.supatype.com/docs/client.html#realtime) |\n| Edge Functions on Deno | Functions on Deno, called at `/functions/v1/<name>` and from `supatype.functions.invoke`. See [Functions](https://www.supatype.com/docs/client.html#functions) |\n\n### What you stop writing\n\n- SQL for tables, columns, indexes, foreign keys and enums. The model type declares them.\n- One RLS policy per operation, with `using` and `with check` kept in step by hand. One rule per operation does both.\n- Migration files. A push compares your schema with the database, shows the plan and asks before anything that can lose data. `supatype diff` shows the plan without applying it.\n- A separate type generation step after each migration. Types are written on every `supatype dev` save and every `supatype push`.\n- Bucket policies in SQL. A bucket's rules sit next to the models in the schema.\n\n### Before and after\n\nA posts table where anyone reads published posts, and authors read and change their own.\n\n#### Supabase\n\n`supabase/migrations/20260101000000_posts.sql`:\n\n```sql\ncreate table public.posts (\n id uuid primary key default gen_random_uuid(),\n author_id uuid not null references auth.users (id) on delete cascade,\n title text not null,\n status text not null default 'draft' check (status in ('draft', 'published'))\n);\n\nalter table public.posts enable row level security;\n\ncreate policy \"Read published or own\" on public.posts for select\n using (status = 'published' or (select auth.uid()) = author_id);\ncreate policy \"Insert own\" on public.posts for insert to authenticated\n with check ((select auth.uid()) = author_id);\ncreate policy \"Update own\" on public.posts for update to authenticated\n using ((select auth.uid()) = author_id) with check ((select auth.uid()) = author_id);\ncreate policy \"Delete own\" on public.posts for delete to authenticated\n using ((select auth.uid()) = author_id);\n```\n\n```sh\n$ supabase migration up\n$ supabase gen types typescript --local > database.types.ts\n```\n\n#### Supatype\n\n`schema/index.ts`:\n\n```ts\nimport type { Model, UUID, SupatypeAuthUserId, Default, Owner, Any, Eq, Literal } from \"@supatype/types\"\n\nexport type Post = Model<{\n id: UUID\n author_id: SupatypeAuthUserId<{ onDelete: \"cascade\" }>\n title: string\n status: Default<\"draft\" | \"published\", \"draft\">\n}, {\n access: {\n read: Any<[Eq<\"status\", Literal<\"published\">>, Owner<\"author_id\">]>\n create: Owner<\"author_id\">\n update: Owner<\"author_id\">\n delete: Owner<\"author_id\">\n }\n}>\n```\n\n```sh\n$ supatype dev\n```\n\nThe table is named `post`, from the type name. Set `tableName: \"posts\"` in the second argument to keep the old name. Because the `create` rule is `Owner<\"author_id\">`, the column defaults to the caller's id, so an insert can leave it out.\n\n#### The query\n\n`before: supabase-js`:\n\n```ts\nimport { createClient } from \"@supabase/supabase-js\"\nimport type { Database } from \"./database.types\"\n\nconst supabase = createClient<Database>(url, key)\nconst { data, error } = await supabase.from(\"posts\").select(\"id, title\").eq(\"status\", \"published\")\n```\n\n`after: @supatype/client`:\n\n```ts\nimport { createClient } from \"../supatype/generated/client\"\n\nconst supatype = createClient({ url, anonKey })\nconst { data, error } = await supatype.from(\"post\").select(\"id, title\").eq(\"status\", \"published\")\n```\n\nThe query builder reads the same way. The differences are in the setup: `createClient` takes one object with `url` and `anonKey`, and it comes from the generated file, so there is no type argument to pass.\n\n### Small differences in the client\n\n- Session fields are camel case: `session.accessToken`, `session.refreshToken`, `session.expiresAt`.\n- Row changes are subscribed from the table: `supatype.from(\"comment\").subscribe(cb, { event: \"INSERT\" })`. Each change reaches only subscribers allowed to read that row.\n- `error` is a `SupatypeError` (an `Error`) with `message` and, when known, `code` and `status`. An insert an access rule refuses returns `42501`. See [Errors](https://www.supatype.com/docs/client.html#errors).\n- A function is a Deno module with a default export, `handler(req, ctx)`. The project URL and keys come from `ctx`, not the environment. `supatype functions new hello` writes one to start from.\n\n### Bringing an existing database\n\nTo bring the data too, dump only your own schema, usually `public`. Supabase's own schemas, such as `auth` and `storage`, are not yours to restore over Supatype's. The CLI has no restore command, so load the dump with `psql`. `supatype dev` points `DATABASE_URL` in `.env` at the local database. Rows with a foreign key to `auth.users` need their users to exist first, so move users before those rows.\n\n```sh\n$ pg_dump -h db.yourproject.supabase.co -U postgres -d postgres --schema=public --no-owner --no-privileges -f supabase-dump.sql\n$ psql \"$(grep '^DATABASE_URL=' .env | cut -d= -f2-)\" -f supabase-dump.sql\n```\n\n`supatype pull` reads a live database and drafts `schema/index.ts` from it. It prints the draft unless you pass `--out`.\n\n```sh\n$ supatype pull --connection \"postgres://...\" --out schema/index.ts\n$ supatype diff\n```\n\nRead the draft before you push it. It is a starting point, not a translation:\n\n- Every model is drafted with `Public` for all four rules. Your RLS policies are not read. Replace each rule with the one you mean.\n- An `id` column of type uuid is drafted as `SupatypeAuthUserId`. Change it to `UUID` on every table whose id is not a user's id.\n- A uuid column ending in `_id` is drafted as a plain `UUID` with a comment suggesting a relation. Make it a `RelatedTo<>`, or a `SupatypeAuthUserId` when it points at a user.\n- Model names come from table names, and the table name is derived back from the model name. Add `tableName` wherever the two differ, such as a plural table name.\n- Tables whose names start with `_` are skipped.\n\n#### Adopting tables Supatype did not create\n\nA table that already exists was not created by Supatype, so a push refuses it: the access rules your schema declares for it would not be in force. In a terminal, `supatype push` says which tables, then asks `Adopt them now?`. Answer yes and it shows what adoption will take and asks `Adopt these?` before it changes anything. After adopting, it pushes again.\n\n`--yes` does not answer the adoption questions. Agreeing to a push is not agreeing to take over tables, so with `--yes` or without a terminal the push stops and prints the command to run instead:\n\n```sh\n$ supatype adopt # shows what it would take, then asks\n$ supatype adopt --key table:post # adopt only the objects you name\n$ supatype push\n```\n\n`supatype adopt --release <object>` tells every push to leave an object alone. `--reclaim <object>` hands it back. Objects are named the way `supatype doctor` names them: `kind:table.name`, or `kind:name` for a table.\n\n### What does not carry over\n\n- **Your SQL migrations.** Supatype does not replay `supabase/migrations`. It plans changes from the schema and records the migrations it applies.\n- **Your RLS policies.** They are rewritten as access rules. Rules are types: there is no raw SQL escape hatch for access rules, so a policy the rule types cannot express needs another approach, such as a hook or a Postgres function you write yourself ([Server logic in a Postgres function](https://www.supatype.com/docs/schema.html#server-logic)). Your database is still Postgres, and you can run your own SQL in it.\n- **Generated types.** Delete `database.types.ts`. The client types come from the generated `supatype/generated` files.\n- **Function entry points.** The handler shape differs, so each function's entry needs a small rewrite. The code inside, being Deno, mostly stays.\n- **Function names and bodies in the client are not typed**, unlike tables.\n\n### Users and files\n\nThere is no command to import auth users or stored files. Plan each as its own step.\n\nFor users, either ask them to sign up again, or copy their rows. Supatype's auth server descends from the same code as Supabase Auth and keeps the same bcrypt hashes in `auth.users.encrypted_password`, so copied rows keep their passwords. The two `auth` schemas are not guaranteed to match column for column. Copy the columns you need, at least `id`, `email`, `encrypted_password`, `email_confirmed_at` and `raw_user_meta_data`, and try it on a copy first. This path is not a supported tool.\n\nFor files, declare each bucket in your schema and push. Then download each file from Supabase and upload it with a client that holds the service role key, from a one-off script on a server:\n\n`scripts/copy-files.ts`:\n\n```ts\nimport { createClient } from \"../supatype/generated/client\"\n\nconst supatype = createClient({\n url: process.env.PUBLIC_SUPATYPE_URL!,\n anonKey: process.env.ANON_KEY!,\n serviceRoleKey: process.env.SERVICE_ROLE_KEY!,\n})\n\nexport async function copyFile(sourceUrl: string, path: string): Promise<void> {\n const res = await fetch(sourceUrl)\n // An expired link or a private bucket answers with an error page, which must not become the file.\n if (!res.ok) throw new Error(`${path}: the source answered ${res.status}`)\n const { error } = await supatype.storage.from(\"avatars\").upload(path, await res.blob(), { upsert: true })\n if (error) throw new Error(`${path}: ${error.message}`)\n}\n```\n\n## Coming from Prisma\n\nSource: https://www.supatype.com/from-prisma.html\n\nPrisma gives you tables, migrations and a typed client from one schema file. Supatype does the same from TypeScript types, then goes on to access rules, an API, an admin UI, auth and storage, which with Prisma you write yourself.\n\n### What maps to what\n\n| In Prisma | In Supatype |\n| --- | --- |\n| `model` in `schema.prisma` | A `Model<>` type in `schema/index.ts`. See [Models](https://www.supatype.com/docs/schema.html#models) |\n| `prisma migrate dev` | `supatype dev`: each save is applied to the local database |\n| `prisma migrate deploy` | `supatype push`, which shows the plan and asks before anything that can lose data |\n| `prisma migrate diff` | `supatype diff`: the plan, without applying it |\n| `prisma db pull` | `supatype pull`: a draft schema from a live database |\n| `prisma generate` | Types are written by `supatype dev` and `supatype push`. `supatype generate` writes them on their own |\n| Prisma Client | `@supatype/client`. See [Client](https://www.supatype.com/docs/client.html) |\n| Prisma Studio | Supatype Studio, a CMS built from the schema. See [Studio roles](https://www.supatype.com/docs/studio-roles.html) |\n| `prisma db seed` | `supatype seed`. See [Seeding](https://www.supatype.com/docs/seeding.html) |\n\n#### Field by field\n\n| Prisma | Supatype |\n| --- | --- |\n| `String @id @default(uuid())` | `id: UUID`. The database fills it in |\n| `String?` | `Optional<string>`. Every other field is `NOT NULL` |\n| `@unique` | `Unique<T>` |\n| `@default(value)` | `Default<T, value>` |\n| `enum Status { draft published }` | `\"draft\" \\| \"published\"` |\n| `Json` | `JSON<T>`, typed as `T` in the client |\n| `@relation(fields: [authorId], references: [id])` | `RelatedTo<Author>`, which adds the column `author_id` |\n| The list side, `posts Post[]` | `HasMany<Post>`. It adds no column |\n| An implicit many-to-many | `ManyToMany<Tag>`, one junction table for the pair |\n| `@@index`, `@@map` | `indexes` and `tableName` in the model's second argument |\n\nThe full list is in [Field types](https://www.supatype.com/docs/schema.html#fields) and [Relations](https://www.supatype.com/docs/schema.html#relations).\n\n### Before and after\n\n#### Prisma\n\n`prisma/schema.prisma`:\n\n```prisma\nenum Status {\n draft\n published\n}\n\nmodel Author {\n id String @id @default(uuid())\n email String @unique\n name String\n posts Post[]\n}\n\nmodel Post {\n id String @id @default(uuid())\n title String\n status Status @default(draft)\n author Author @relation(fields: [authorId], references: [id], onDelete: Cascade)\n authorId String\n}\n```\n\n`before: Prisma Client`:\n\n```ts\nconst posts = await prisma.post.findMany({\n where: { status: \"published\" },\n select: { id: true, title: true, author: { select: { name: true } } },\n})\n```\n\n#### Supatype\n\n`schema/index.ts`:\n\n```ts\nimport type {\n Model, UUID, Email, Unique, Default, SupatypeAuthUserId,\n RelatedTo, HasMany, Public, Owner, Any, Eq, Literal,\n} from \"@supatype/types\"\n\nexport type Author = Model<{\n id: SupatypeAuthUserId\n email: Unique<Email>\n name: string\n posts: HasMany<Post>\n}, {\n access: { read: Public; create: Owner<\"id\">; update: Owner<\"id\">; delete: Owner<\"id\"> }\n}>\n\nexport type Post = Model<{\n id: UUID\n title: string\n status: Default<\"draft\" | \"published\", \"draft\">\n author: RelatedTo<Author, { required: true; onDelete: \"cascade\" }>\n}, {\n access: {\n read: Any<[Eq<\"status\", Literal<\"published\">>, Owner<\"author_id\">]>\n create: Owner<\"author_id\">\n update: Owner<\"author_id\">\n delete: Owner<\"author_id\">\n }\n}>\n```\n\n`after: @supatype/client`:\n\n```ts\nconst { data: posts, error } = await supatype\n .from(\"post\")\n .select(\"id, title, author(name)\")\n .eq(\"status\", \"published\")\n```\n\nThe author's id is a sign-in user's id, so each author row belongs to a user. The `access` blocks are the part Prisma has no place for: they become Postgres row level security, so the same query returns only what the caller may see, whether it runs on your server or in the browser.\n\n### What Supatype adds\n\n- **Access rules in the database.** Each model's rules become row level security, and field rules mask single columns. They hold for REST, GraphQL, realtime and the client alike. See [Access rules](https://www.supatype.com/docs/schema.html#access).\n- **An API you do not write.** Every model with access rules is reachable over REST and GraphQL. A model with no `access` at all is not.\n- **A client that runs in the browser.** It holds the anon key and the user's session, not a database connection.\n- **Studio.** A form for each model built from its fields, drafts and version history, a media library, and roles for the people who edit content. See [Studio roles](https://www.supatype.com/docs/studio-roles.html).\n- **Auth, storage, realtime and functions** in the same project. Buckets are declared in the schema next to the models. See [Auth](https://www.supatype.com/docs/client.html#auth), [Storage](https://www.supatype.com/docs/client.html#storage), [Realtime](https://www.supatype.com/docs/client.html#realtime) and [Functions](https://www.supatype.com/docs/client.html#functions).\n\n### Bringing an existing database\n\n`supatype pull` drafts a schema from a live database. Prisma's `_prisma_migrations` table is skipped, along with any table whose name starts with `_`.\n\n```sh\n$ supatype pull --connection \"postgres://...\" --out schema/index.ts\n$ supatype diff\n```\n\nPrisma's defaults and Supatype's differ, so expect to edit the draft:\n\n- Prisma names a table after the model, such as `\"Post\"`. Supatype derives the table name from the model name in snake case, so `Post` means `post`. Add `tableName: \"Post\"` to keep the existing table.\n- A field's name is its column's name. A relation's column is the field name plus `_id`, and there is no option to name it otherwise, so a Prisma `authorId` column does not line up with an `author` relation. Keep it as a plain field, or rename the column.\n- Every drafted model has `Public` for all four rules. Replace them with the rules you mean before you push.\n- An `id` column of type uuid is drafted as `SupatypeAuthUserId`. Change it to `UUID` on every table whose id is not a user's id.\n- Prisma fills `@default(uuid())` in the client, and stores a `String` id as text unless you used `@db.Uuid`. Such an id is drafted as a string, not a `UUID`.\n\nThe first push refuses tables that exist and that Supatype did not create. In a terminal it offers to adopt them: it asks `Adopt them now?`, shows what adoption will take, and asks again before changing anything. `--yes` does not answer those questions. Without a terminal, run `supatype adopt` and then push again. See [What a push refuses](https://www.supatype.com/docs/schema.html#push).\n\n### What does not carry over\n\n- **Other databases.** Supatype runs on Postgres 17 only. MySQL, SQLite, SQL Server and MongoDB projects need moving to Postgres first.\n- **Your migrations folder.** Supatype does not read `prisma/migrations`. It compares the schema with the database and plans the change itself.\n- **Nested writes and transactions.** The client writes one table per call and has no transaction API. Put a write that must touch several tables at once in a function.\n- **Raw queries.** There is no `$queryRaw`. Studio has a SQL runner for one-off queries.\n- **Client extensions and middleware.** Logic that ran around every query belongs in access rules, model hooks or functions.\n\n> **PRISMA 8:** Prisma 8, in release candidates at the time of writing, replaces `schema.prisma` with `contract.prisma` and renames the migrate commands. The mapping above is to Prisma 7.\n\n## Postgres\n\nSource: https://www.supatype.com/postgres.html\n\nPostgreSQL 17 with the extensions an app needs, our own extensions, and safe defaults. It is the database under every Supatype project. Use it on its own too. Open source under the PostgreSQL License, for linux/amd64 and linux/arm64.\n\n### Run it\n\n```sh\ndocker run -d \\\n --name supatype-postgres \\\n -e POSTGRES_PASSWORD=your-password \\\n -p 5432:5432 \\\n supatype/postgres:17-latest\n```\n\nThe default superuser is `supatype_admin`, set with `POSTGRES_USER`.\n\n### Our extensions\n\n- [`pg_keyspace`](https://www.supatype.com/postgres/pg-keyspace.html): Redis, inside your Postgres.\n- [`pg_topics`](https://www.supatype.com/postgres/pg-topics.html): Kafka topics, with no broker to run. Not in the image yet.\n- [`pg_guard`](https://www.supatype.com/postgres/pg-guard.html): Superuser features, without the superuser.\n- [`supatype_mask`](https://www.supatype.com/postgres/supatype-mask.html): Hide a column per row, not per table.\n\n### Also included\n\n| Extension | What it does |\n| --- | --- |\n| `PostGIS` | Geography and geometry types, and spatial queries. |\n| `pgvector` | Vector embeddings and similarity search. |\n| `pg_graphql` | A GraphQL API over your schema. |\n| `pg_net` | Async HTTP requests from triggers and functions. |\n| `pgjwt` | JWT signing and checking in SQL. |\n| `pg_cron` | Scheduled jobs inside Postgres. |\n| `pg_safeupdate` | Stops UPDATE and DELETE with no WHERE clause. It is in `shared_preload_libraries`, so it applies to every session: API requests, Studio's SQL runner and your own `psql`. Write `WHERE true` to mean every row, or `SET safeupdate.enabled = 0` to turn it off for the session. |\n| `pg_plan_filter` | Rejects queries over a cost limit. |\n| `wal2json` | Logical decoding as JSON, for realtime. |\n\n### Safe defaults\n\n- Row level security is on by default.\n- Passwords are stored as scram-sha-256.\n- The ordinary postgres role is not a superuser.\n- A table you make by hand in public is not granted to anon or authenticated until you grant it.\n- pg_guard loads on every connection, so roles can manage extensions without SUPERUSER.\n- A failed migration stops the container, so no client reaches a half-migrated database.\n\nMigrations run on first boot and on every start after, so pulling a newer tag over an existing volume applies what is new. `supatype migrate doctor` checks that the important ones took effect.\n\n### Tags\n\n| Tag | What it is |\n| --- | --- |\n| `supatype/postgres:17-latest` | The newest PG17 release. Moves only when a release is tagged. |\n| `supatype/postgres:x.y.z` | One release, pinned and never changed. |\n| `supatype/postgres:latest` | The same image as 17-latest. |\n| `supatype/postgres:develop` | The newest build of the develop branch. |\n\nNot using Docker? Each release also ships native archives for Linux, macOS and Windows, and the image runs under CloudNativePG. The [supatype/postgres repository](https://github.com/supatype/postgres) covers both.\n\n## pg_keyspace\n\nSource: https://www.supatype.com/postgres/pg-keyspace.html\n\nRedis, inside your Postgres. pg_keyspace runs a Redis and Valkey compatible server inside Postgres. Your Redis client connects unchanged, and SQL reads the same keys.\n\n### Why pg_keyspace\n\nMost teams that need a cache run Redis or Valkey beside Postgres. That is a second stateful service to deploy, secure, monitor and back up. It has its own users, its own backups and its own idea of what is current.\n\npg_keyspace moves the cache into Postgres. A background worker speaks the Redis protocol (RESP2 and RESP3) over a shared-memory keyspace. redis-cli, ioredis, redis-py and valkey-go connect without changes. The same bytes are readable from SQL, and a read inside a backend takes about 9 ns.\n\nIt keeps what you already trust. Redis AUTH maps to a Postgres role, keys can be scoped per tenant, and the wire can use TLS. Durability is a setting per key prefix, from memory only to fsync before the reply. Persisted keys live in ordinary tables, so your Postgres backups and point-in-time recovery cover the cache too.\n\n### An example\n\n```sh\n# Any Redis client works. Here, redis-cli on the RESP port.\nredis-cli -p 6379 SET session:42 '{\"user\":\"ada\"}' EX 3600\nredis-cli -p 6379 HSET user:42 name Ada plan pro\nredis-cli -p 6379 ZADD leaderboard 120 ada 95 grace\nredis-cli -p 6379 ZRANGE leaderboard 0 -1 WITHSCORES\n\n# The same keyspace, read from SQL in the same database.\npsql \"$DATABASE_URL\" -c \"\n SELECT convert_from(supacache.get('session:42'), 'UTF8');\"\n\n# Write from SQL with a 60 second TTL, read it back over RESP.\npsql \"$DATABASE_URL\" -c \"SELECT supacache.set('flag:beta', 'on', 60);\"\nredis-cli -p 6379 GET flag:beta # \"on\"\n\n# Tell RESP subscribers something from SQL, say from a trigger.\npsql \"$DATABASE_URL\" -c \"\n SELECT supacache.publish('orders', 'shipped:42');\"\n\n# Hit rate, entries and memory, as a normal Postgres view.\npsql \"$DATABASE_URL\" -c \"SELECT * FROM supacache.pg_stat_keyspace;\"\n```\n\n### pg_keyspace or a separate Redis or Valkey cluster\n\n| | a separate Redis or Valkey cluster | pg_keyspace |\n| --- | --- | --- |\n| What you run | A separate service or cluster to deploy, patch, secure and monitor. | A background worker inside the Postgres you already run. |\n| Clients | Any Redis client. | Stock Redis clients, unmodified, over RESP2 or RESP3, including client-side caching. |\n| Cache hit (GET, closed loop) | About 35 to 39 \u00B5s. | About 34 to 39 \u00B5s. |\n| Pipelined throughput, one worker | About 537k to 628k ops/s. Higher on GET. | About 500k to 556k ops/s. More workers scale it out. |\n| SQL access to the same data | None. It is a separate datastore. | Yes. supacache.get reads the same shared memory, about 9 ns in a backend. |\n| Auth and tenancy | Redis ACLs, in a separate user store. | AUTH maps to a Postgres role. Keys and channels are scoped per tenant. TLS can reuse the Postgres certificate. |\n| Durability | RDB snapshots and AOF, set for the whole instance. | Four tiers, from memory only to a synchronous standby, chosen per key prefix. |\n| Backups | A separate artefact on a separate schedule with a separate restore. | Persisted keys are Postgres tables, so base backups and point-in-time recovery include them. |\n| Monitoring | A Redis exporter to deploy and wire up. | pg_stat_keyspace views, granted to pg_monitor. Existing Postgres collectors read them. |\n| Command and type surface | Wider. Adds streams, scripting, HyperLogLog and geo. | Strings, hashes, lists, sets, sorted sets, bitmaps, Bloom and Cuckoo filters, pub/sub and transactions. |\n| Maturity | Mature, with a large ecosystem. | New, with a focused feature set. |\n\n### What it does not do\n\n- No streams, Lua scripting (EVAL) or blocking commands such as BLPOP yet. They are planned with no date, and a client that sends them gets ERR unknown command. Check for both before treating it as a drop-in.\n- FUNCTION and FCALL are declined. HyperLogLog is not planned, and geo is declined in favour of PostGIS.\n- Valkey has a higher raw write ceiling with persistence off. If you need maximum single-node write throughput or mature cluster tooling today, stay on Valkey.\n- It is opt-in. The library has to be preloaded, so turning it on is a restart. Its shared memory is reserved at startup whether or not the cache is full.\n- The default tier is ephemeral, so keys live in memory and are lost on restart. The durable tiers wait for a Postgres commit: a median of 1.04 ms per write against 39 \u00B5s for ephemeral in the published benchmark.\n- The replicated tier cannot be mixed with other tiers on one instance. It applies to the whole keyspace or not at all.\n- A streaming standby serves no RESP until it is promoted. On a replica the keyspace is reachable only through SQL.\n- With more than one worker and a persisted tier, clients need their cluster constructor, unless owner recovery addressing is on. Changing the worker count is a restart, and there is no online resharding.\n- The PostgREST row cache is off by default and eventually coherent. After an UPDATE, another session can read the previous row for 200 ms plus decode time by default, and for longer when many databases share the invalidation pool.\n- Pub/sub crosses instances only for channels you opt in, and delivery is at most once. Bloom and Cuckoo filters are reachable over RESP only, with no SQL functions yet.\n\n### Use it on its own\n\npg_keyspace ships in the [supatype/postgres](https://www.supatype.com/postgres.html) image. Use the image as your Postgres, with or without the rest of Supatype.\n\n```sh\n# pg_keyspace ships in the image but is not loaded by default.\n# SUPATYPE_KEYSPACE_ENABLED=1 adds it to shared_preload_libraries\n# and creates the extension in POSTGRES_DB on first start.\n# From 17.2.13, SUPATYPE_KEYSPACE_PASSWORD makes RESP require AUTH\n# and sets the credential `supatype` to it on every start.\ndocker run -d \\\n --name supatype-postgres \\\n -e POSTGRES_PASSWORD=your-password \\\n -e SUPATYPE_KEYSPACE_ENABLED=1 \\\n -e SUPATYPE_KEYSPACE_PASSWORD=\"$KEYSPACE_PASSWORD\" \\\n -e SUPATYPE_KEYSPACE_DURABILITY=ephemeral \\\n -e SUPATYPE_KEYSPACE_DURABILITY_OVERRIDES='acme:=durable' \\\n -p 5432:5432 \\\n -p 127.0.0.1:6379:6379 \\\n supatype/postgres:17-latest\n\nredis-cli --user supatype -a \"$KEYSPACE_PASSWORD\" -p 6379 PING # PONG\nredis-cli -p 6379 PING # NOAUTH Authentication required.\n\n# Without the password, RESP answers every client, and before 17.2.13\n# a client with no password could still list keys and FLUSHALL, so\n# the port above listens on this machine only.\n```\n\nTo keep the password out of the container's configuration, mount it as a file and name it with `SUPATYPE_KEYSPACE_PASSWORD_FILE` instead, as `POSTGRES_PASSWORD_FILE` works. Set one or the other: with both, or with a file that is empty, the container stops at start. To rotate a password given as a file, rewrite the file and run `SELECT pg_reload_conf();`. The new password works at once and the old one stops working, with no restart. Clients such as the Supatype server read their password when they start, so restart them with the new one.\n\n### With Supatype\n\nEvery Supatype project runs on this image, with migrations, access rules, an API, a typed client and Studio generated from your TypeScript types. [Run it locally](https://www.supatype.com/docs/#local-dev) in a few commands. On 17.2.13 and later the CLI generates a keyspace password for each project into `.env` as `SUPATYPE_KEYSPACE_PASSWORD` and gives it to the database, the server and Kong, so nothing else can read or flush the cache. The full reference is the extension's [README](https://github.com/supatype/postgres/blob/develop/extensions/pg_keyspace/README.md).\n\n## pg_topics\n\nSource: https://www.supatype.com/postgres/pg-topics.html\n\nKafka topics, with no broker to run. pg_topics turns a Postgres table into a Kafka topic. Stock Kafka clients produce and consume on a port the extension opens, and SQL can do the same work inside your own transaction.\n\n> **SOURCE ONLY:** Not in the supatype/postgres image yet. Build it from source in the supatype/postgres repository.\n\n### Why pg_topics\n\nMost teams that want an event log already run Postgres. The usual answer is a second system: a Kafka cluster with its own backups, patching, users and monitoring. Then every write that must also publish an event needs an outbox table to keep the two in step.\n\npg_topics puts the topic in the database. Each topic is a table. A Kafka client logs in with a Postgres role and its password, over TLS, and produces and consumes as it would against a broker. A SQL user calls topic.publish inside the same transaction as the rest of their writes, so the event commits with the data or not at all.\n\nHistory stays queryable with SQL, Postgres grants are the only permission system, and an optional worker keeps a normal table current from a topic so you can read the latest state with SELECT. It suits a team that needs up to tens of thousands of events a second, not hundreds of thousands.\n\n### An example\n\n`orders.sql`:\n\n```sql\n-- A topic is a table whose name ends in _q. A band is a Kafka partition.\nSELECT topic.create_topic('shop.orders_q', band_count => 4);\nSELECT topic.grant_consume('shop.orders_q', 'billing_service');\n\n-- Publish in the same transaction as your own writes. No outbox table.\nBEGIN;\nUPDATE shop.stock SET count = count - 1 WHERE sku = 'A-100';\nSELECT topic.publish('shop.orders_q', '{\"order_id\": 2, \"sku\": \"A-100\"}', key => 'customer-42');\nCOMMIT;\n\n-- Read it back in SQL.\nSELECT * FROM topic.fetch('shop.orders_q',\n band => topic.band_for('customer-42', 4), from_offset => 0);\n\n-- Or with a stock Kafka client: SASL_SSL, PLAIN, a Postgres role and its password.\n-- kafka-console-consumer --bootstrap-server kafka.example.internal:9092 \\\n-- --consumer.config client.properties --topic shop.orders_q --from-beginning\n\n-- Alert when ok = false.\nSELECT * FROM topic.health();\n```\n\n### pg_topics or a Kafka cluster\n\n| | a Kafka cluster | pg_topics |\n| --- | --- | --- |\n| What you run | A broker cluster beside your database, with its own backups, patching and monitoring. | Your PostgreSQL 17 server. There is no broker to run, back up or patch. |\n| Publish with a database write | Needs an outbox table, or a second write that can fail on its own. | topic.publish joins your transaction. A ROLLBACK removes the record. |\n| Access control | Its own users and ACLs, kept apart from the database's. | Postgres roles and grants. A Kafka client logs in as a role. |\n| Reading history | Consume the log, or copy it into a database first. | Every topic is a table that SQL can query, on the primary or a standby. |\n| Current state per key | Log compaction. | No compaction. A sync worker keeps a normal table current instead. |\n| Throughput | Scales out across brokers. | One primary does all the writes. About 10,000 records a second with low latency, and up to about 44,000 at top speed, on the test machine. |\n| Transactions and exactly once | Supported. | Not supported. Idempotent producers are supported. |\n| Monitoring | JMX metrics. | SQL views and topic.health(). There are no JMX metrics. |\n\n### What it does not do\n\n- PostgreSQL 17 only. Other versions are not built or tested.\n- A record value must be valid JSON, and a key must be UTF-8 text of 40 characters or fewer.\n- A topic name is schema.table_q, and clients must use the full name. A producer aimed at orders gets TOPIC_AUTHORIZATION_FAILED.\n- No Kafka transactions or exactly once. A transactional.id gets TRANSACTIONAL_ID_AUTHORIZATION_FAILED.\n- No log compaction, and no size based retention. Retention is by time only and drops whole partitions.\n- The band count is fixed when you make the topic. There is no CreatePartitions.\n- Only SASL PLAIN over TLS. No SCRAM, OAUTHBEARER, GSSAPI, mutual TLS or plain text.\n- Classic consumer groups only. The KIP-848 protocol, static membership and share groups are not offered.\n- Kafka Connect in distributed mode, Kafka Streams and Schema Registry make compacted topics, so they are expected to fail. They are not tested.\n- One broker and one primary. Publish throughput does not grow with more machines. Standbys give failover and SQL history reads.\n- Fetch returns the value as jsonb prints it, so a signature over the raw bytes does not match.\n- librdkafka clients must set partitioner=murmur2_random, or keyed records land on different bands from a SQL publish.\n- A restart of PostgreSQL makes every consumer group rebalance once.\n\n### Use it on its own\n\nNot in the supatype/postgres image yet. Build it from source in the supatype/postgres repository. Its README covers the install.\n\n`postgresql.conf`:\n\n```ini\n# Add pg_topics to your existing shared_preload_libraries list.\nshared_preload_libraries = 'pg_topics'\npg_topics.databases = 'app'\npg_topics.failover_is_fenced = on\n\n# The Kafka port speaks TLS only.\npg_topics.tls_cert_file = '/etc/pg_topics/server.crt'\npg_topics.tls_key_file = '/etc/pg_topics/server.key'\npg_topics.advertised_host = 'kafka.example.internal'\n\n# Restart PostgreSQL, then in the app database run:\n# CREATE EXTENSION pg_topics;\n```\n\n### With Supatype\n\nEvery Supatype project runs on this image, with migrations, access rules, an API, a typed client and Studio generated from your TypeScript types. [Run it locally](https://www.supatype.com/docs/#local-dev) in a few commands. The full reference is the extension's [README](https://github.com/supatype/postgres/blob/develop/extensions/pg_topics/README.md).\n\n## pg_guard\n\nSource: https://www.supatype.com/postgres/pg-guard.html\n\nSuperuser features, without the superuser. pg_guard lets a non-superuser role create extensions, event triggers and publications. It still cannot make itself a superuser.\n\n### Why pg_guard\n\nPostgres keeps a lot behind SUPERUSER. Event triggers, publications, foreign data wrappers and extensions such as hstore all need it. So teams hand out SUPERUSER, and with it the power to read server files, run programs and change any role.\n\npg_guard adds one privileged role. When that role creates a superuser-only object, pg_guard switches to a configured superuser, creates it, hands ownership back and switches back. Event triggers it creates skip superusers and reserved roles, so they cannot be used to escalate. It cannot create a SUPERUSER role or grant the attribute.\n\nEverything lives in postgresql.conf. There are no tables, functions or security labels in your database, so upgrades are simple and a reload applies a change. It is derived from supautils and runs in every supatype/postgres container.\n\n### An example\n\n`pg_guard.sql`:\n\n```sql\n-- postgres is not a superuser here. It is a member of\n-- supatype_privileged_role, the image's pg_guard.privileged_role.\nset role postgres;\nselect current_setting('is_superuser'); -- off\n\ncreate extension hstore; -- in pg_guard.privileged_extensions\ncreate publication app_changes for all tables;\nset session_replication_role = replica; -- in privileged_role_allowed_configs\n\n-- An event trigger. The function must not be superuser-owned.\ncreate function log_ddl() returns event_trigger\nlanguage plpgsql as $$\nbegin\n raise notice 'ddl by %', current_user;\nend;\n$$;\ncreate event trigger log_ddl on ddl_command_end\n execute procedure log_ddl();\n\ncreate role escalate superuser;\n-- ERROR: permission denied to create role\n```\n\n### pg_guard or handing out SUPERUSER\n\n| | handing out SUPERUSER | pg_guard |\n| --- | --- | --- |\n| Extensions that need a superuser | Only a superuser can create hstore, postgres_fdw and the like. | Non-superusers can create, update and drop any extension listed in pg_guard.privileged_extensions. Others behave as normal. |\n| Event triggers | Superuser only. A trigger fires for every role, superusers included. | The privileged role can create them. They are skipped for superusers and reserved roles. |\n| Publications and FDWs | Superuser only. | The privileged role creates them and owns them. |\n| Becoming a superuser | The role already is one. | The privileged role cannot create a SUPERUSER role or add the attribute to one. |\n| Roles your services log in as | Any superuser can alter or drop them, or grant pg_read_server_files. | Reserved roles cannot be altered or dropped by non-superusers. Reserved memberships cannot be granted. |\n| Where the rules live | Role attributes and grants, set role by role. | postgresql.conf only. Settings take effect on a reload, with no objects added to the database. |\n\n### What it does not do\n\n- Event triggers made by the privileged role do not fire when it creates publications, foreign data wrappers or extensions.\n- Those event triggers are skipped for superusers and reserved roles, so they do not see DDL from those roles.\n- It does not restrict superusers. Keep the real superuser for the platform, not for people.\n- It loads per session through session_preload_libraries. A role given its own list without pg_guard runs without it. supatype migrate doctor checks this for authenticator.\n- Extension parameter overrides support the schema parameter only. Custom scripts run before-create and after-create only.\n- Settings are cluster-wide. You cannot give one database a different list.\n- It is not in the cross-compiled linux-arm64 native archive. The Docker image is not affected.\n\n### Use it on its own\n\npg_guard ships in the [supatype/postgres](https://www.supatype.com/postgres.html) image. Use the image as your Postgres, with or without the rest of Supatype.\n\n```sh\n# pg_guard is on by default in the image\ndocker run -d --name supatype-postgres \\\n -e POSTGRES_PASSWORD=your-password -p 5432:5432 \\\n supatype/postgres:17-latest\n\n# Preloaded for every session, with its settings in their own file:\n# session_preload_libraries = 'pg_guard'\n# include = '/etc/postgresql-custom/pg_guard.conf'\ndocker exec supatype-postgres \\\n cat /etc/postgresql-custom/pg_guard.conf\n\n# Make one of your roles privileged (as supatype_admin)\npsql -h localhost -U supatype_admin -d postgres \\\n -c \"grant supatype_privileged_role to app_admin;\"\n\n# After editing pg_guard.conf, reload. No restart needed.\npsql -h localhost -U supatype_admin -d postgres \\\n -c \"select pg_reload_conf();\"\n```\n\n### With Supatype\n\nEvery Supatype project runs on this image, with migrations, access rules, an API, a typed client and Studio generated from your TypeScript types. [Run it locally](https://www.supatype.com/docs/#local-dev) in a few commands. The full reference is the extension's [README](https://github.com/supatype/postgres/blob/develop/extensions/pg_guard/README.md).\n\n## supatype_mask\n\nSource: https://www.supatype.com/postgres/supatype-mask.html\n\nHide a column per row, not per table. supatype_mask masks reads and rejects writes on a single column, row by row. The rule is a SQL function you name in a security label, and the planner enforces it on every query.\n\n### Why supatype_mask\n\nColumn privileges are all or nothing. Revoke SELECT on salary and a PostgREST request with no select list asks for every column, so the whole table answers 403 instead of a row with one field hidden. A view can put a CASE where the column was, but Postgres stores the view's column list when you create it. A column added later is invisible until someone re-runs CREATE OR REPLACE VIEW.\n\nsupatype_mask puts the rule on the column. You label it with a read predicate and a write predicate, and the planner rewrites every reference to that column into a CASE that calls your read predicate. That covers the select list, WHERE, ORDER BY, joins, subqueries, views, COPY TO and whole-row references such as to_jsonb(posts). A filter cannot be used to guess the hidden value.\n\nWrites are judged per row too. If a client reads a masked null and sends the whole object back, the real value is kept. A caller who can see the value but may not change it gets a 42501 error. The rules are plain SQL functions, so the C extension stays small and the logic stays where you can read it.\n\n### An example\n\n`mask.sql`:\n\n```sql\n-- Readable by the post's author. Called once per row.\nCREATE FUNCTION public.can_read_posts__salary(posts posts) RETURNS boolean\n LANGUAGE sql STABLE AS $$\n SELECT author_id = auth.uid() FROM (SELECT ($1).*) AS posts;\n $$;\n\n-- Writable by HR. No arguments, so it runs once per scan.\nCREATE FUNCTION public.can_write_posts__salary() RETURNS boolean\n LANGUAGE sql STABLE AS $$ SELECT auth.role() = 'hr' $$;\n\nSECURITY LABEL FOR supatype ON COLUMN public.posts.salary\n IS 'MASK READ public.can_read_posts__salary WRITE public.can_write_posts__salary';\n\n-- Every reference to posts.salary now plans as:\n-- CASE WHEN public.can_read_posts__salary(posts)\n-- THEN posts.salary ELSE NULL END\nSELECT * FROM posts; -- other authors' salary is NULL\nSELECT id FROM posts WHERE salary > 150; -- filters on the masked value\nSELECT sum(salary) FROM posts; -- error if any row is unreadable\n```\n\n### supatype_mask or column GRANTs or a view per role\n\n| | column GRANTs or a view per role | supatype_mask |\n| --- | --- | --- |\n| A request for every column | A column REVOKE makes PostgREST answer 403 for the whole table when no select list is given. | The column is returned, set to null on the rows the caller may not read. |\n| Who can see the value | A GRANT decides per role, for every row in the table. | A predicate decides per row, for example author_id = auth.uid(). |\n| Adding a column | A view stores a fixed column list, so a new column is missing until the view is recreated. | The label sits on the column and the table is queried directly. Nothing to recreate. |\n| Clients the rule reaches | A view protects the queries that go through the view. | The rewrite happens in the planner, so psql, PostgREST and anything else on the database get the same answer. |\n| Writing back a value you never saw | A view column built from CASE is read-only, so writes need a separate path and their own checks. | An unreadable value is kept. A readable value the caller may not change is rejected with an error. |\n| Totals over hidden rows | sum() over a null-masking view adds up only the visible rows and says nothing. | sum(), max() and window aggregates are rejected per unreadable row, so a total is correct or an error. |\n| Switching it off | Any role with the right privilege can GRANT the column back with one SQL statement. | No SQL statement disables masking for a role, a database or a session, not even as a superuser. It takes a config edit and a reload, or a restart. |\n\n### What it does not do\n\n- Postgres 17 or later only. The rewrite depends on planner internals that change between major versions.\n- Logical replication is not filtered. WAL records are not query results, so a subscriber has to apply the same predicates itself.\n- Roles in supatype_mask.exempt_roles and superusers see every column unmasked, by design.\n- A non-leakproof operator applied to the predicate's own inputs can still reveal something through an error message. References to the masked column itself are safe.\n- COPY FROM and MERGE are refused on a table with masked columns.\n- A whole-row predicate runs once per row per masked column. On a full scan with a per-row lookup that can cost around 100 times the unmasked scan. A predicate with no arguments runs once per scan instead.\n- An aggregate over a subquery that masked some rows skips those rows rather than raising an error.\n- The library must be in shared_preload_libraries, which needs a restart. CREATE EXTENSION without the preload does nothing.\n- A predicate declared IMMUTABLE, missing, or not returning boolean masks the column for everyone and logs a WARNING.\n\n### Use it on its own\n\nsupatype_mask ships in the [supatype/postgres](https://www.supatype.com/postgres.html) image. Use the image as your Postgres, with or without the rest of Supatype.\n\n```sh\n# The image preloads supatype_mask and creates the extension on first boot.\ndocker run -d --name supatype-postgres \\\n -e POSTGRES_PASSWORD=your-password \\\n -p 5432:5432 \\\n supatype/postgres:17-latest\n\n# Already set in the image's postgresql.conf:\n# shared_preload_libraries = '..., supatype_mask'\n# and in /etc/postgresql-custom/supatype_mask.conf:\n# supatype_mask.exempt_roles = 'service_role,supatype_sql_editor'\n\n# In any other database, create the extension yourself:\ndocker exec -it supatype-postgres psql -U supatype_admin -d mydb \\\n -c \"CREATE EXTENSION IF NOT EXISTS supatype_mask;\"\n```\n\n### With Supatype\n\nEvery Supatype project runs on this image, with migrations, access rules, an API, a typed client and Studio generated from your TypeScript types. [Run it locally](https://www.supatype.com/docs/#local-dev) in a few commands. The full reference is the extension's [README](https://github.com/supatype/postgres/blob/develop/extensions/supatype_mask/README.md).\n\n## CLI\n\nSource: https://www.supatype.com/docs/cli.html\n\nEvery `supatype` command, grouped by what it is for. Descriptions are the ones `supatype --help` prints.\n\nPre-1.0: APIs and config may change between releases.\n\n### Install and help\n\n```sh\n$ npm install -g @supatype/cli\n$ supatype --help\n$ supatype push --help\n```\n\nThe npm package needs Node.js 18 or later. It is the install to use on Windows.\n\nThe npm package runs the same program as the standalone install, so the React version your app uses, or any other package it installs, has no effect on the CLI. The first run of each version downloads that program from `releases.supatype.com` into `~/.supatype/cache/cli/<version>/` and checks it against the release's signed checksums. In a scaffolded project that happens during `npm install`, when the `prepare` script runs `supatype generate`. A production install with `--omit=dev` leaves the CLI out, and `prepare` then generates nothing and succeeds, since the build that needed the generated files ran with everything installed. If that site is not answering (a 5xx, or no connection), the CLI downloads the same files from the release's page on GitHub Releases, says so in one line, and still checks them against the signed checksums. A 404 or a checksum failure is never retried elsewhere. Releases published after v0.9.2 carry the files there. To use a mirror of the site instead, set `SUPATYPE_CDN_BASE` to its address; a mirror is used on its own, with no fallback to GitHub. A CLI built from source has no release public key embedded and refuses the download; set `SUPATYPE_RELEASE_PUBLIC_KEY` to the release minisign public key to verify the checksums against it. When set, it takes the place of the embedded key. The program is built for Linux and macOS on x64 and arm64, and for Windows on x64.\n\nOn a Linux or macOS machine without Node, such as a CI image or a server, install the standalone binary instead, with the script or with Homebrew:\n\n```sh\n$ curl -fsSL https://supatype.com/install.sh | bash\n$ brew install supatype/tap/supatype\n```\n\nThe script installs one binary to `~/.supatype/bin` and adds that directory to your shell profile. It checks the release signature with `openssl` before installing. Where `openssl` is missing or cannot check ed25519 signatures, as with the LibreSSL macOS ships, it says so and checks only the SHA256. On Alpine it installs the musl build, which needs `apk add libstdc++ libgcc`. The components `dev` downloads are built for glibc only, so run local stacks on a glibc image. `supatype self-update` updates a standalone install.\n\nRun commands from the project directory, where `supatype.config.ts` is. Every command also takes `--project-name <name>`, which names the project for this run over `supatype.config.ts`. `supatype --version` prints the CLI version.\n\n`--project-name` is the same as setting `SUPATYPE_PROJECT_NAME`, and it writes no file. The Compose project, the native database and the state directory under `~/.supatype/projects/` all follow it. Use it to run two stacks of one project side by side, each with its own `SUPATYPE_KONG_PORT`. The name may use lower case letters, digits, `-` and `_`, and must start with a letter or digit.\n\nMany commands that reach a database take `--connection <url>` to override the config, and `--env <name>` to pick an environment when the project is linked.\n\nCommands that use Docker first check that it answers. A Docker that says it cannot be reached fails the command at once. A Docker that is running but slow to answer, as on a machine carrying many containers, is waited for, with a line saying so, for up to 60 seconds in all; set `SUPATYPE_DOCKER_TIMEOUT` to a whole number of seconds to wait longer or shorter.\n\n> **CLOUD:** Commands marked **Cloud** need Supatype Cloud, which is in closed beta ([request access](https://www.supatype.com/#cloud)). Everything else works locally and on a self-hosted stack.\n\n### Project and local development\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `init [name]` | Scaffold a new Supatype project | `-y, --defaults`, `--no-install`, `--no-keys`, `--admin-email`, `--admin-password`, `--no-admin` |\n| `dev` | Start local Postgres, apply schema, and run supatype-server | `--no-watch`, `--stream`, `--port <port>`, `--reset-db` (Docker only), `--yes`, `--overwrite-drift` |\n| `keys` | Generate ANON_KEY and SERVICE_ROLE_KEY JWTs from your JWT_SECRET and fill the blank ones in .env (printed instead when there is no .env, or with --print) | `--print [target]`, `--env <name>` and `--allow-local` (with `--print frontend`), `--force`, `--secret <secret>`, `--exp-years <years>` (default 10), `--write` |\n| `status` | Show linked target status or local stack services | `--env <name>` |\n| `logs` | Tail logs from the local stack | `--service <name>`, `--since <duration>` (default 5m), `-f, --follow` |\n| `mcp` | Start an MCP server over stdio so a coding agent can read this project's schema, diff, status and logs, push the schema, generate types and search the docs. Run it from the project directory. It prints nothing itself. See [MCP servers](https://www.supatype.com/docs/mcp.html) | |\n| `app add [dir]` | Configure app routing: `--static` for a built site, or proxy to a dev server | `--static`, `--port <port>` (default 3000), `--upstream <url>` |\n| `app remove` | Set app.mode=none in supatype.config.ts | |\n| `admin create-user` | Create an admin user for the admin panel | `--email`, `--password` (asked for if left out), `--role` (default `admin`) |\n| `admin set-role` | Change an existing user's admin role | `--email` and `--role`, both required |\n| `admin list-users` | List users with Studio access | `--connection <url>` |\n| `pg start` | Start Postgres for the current project | Native provider only |\n| `pg stop` | Stop Postgres for the current project | |\n| `pg reset` | Stop Postgres, wipe the data directory, and re-initialise | `--force` |\n| `pg psql [dbname]` | Open a psql shell connected to the project database | |\n\n`--role` is `admin`, `developer`, `editor` or `viewer`. See [Studio roles](https://www.supatype.com/docs/studio-roles.html#grant). The first-run steps are in [Local development](https://www.supatype.com/docs/#local-dev).\n\n`keys` fills the blank keys in `.env` when there is one, and prints them when there is none or with `--print`. Add `--force` to replace keys already there. `--write` is kept for older scripts. `keys --print frontend` prints a deployment's API URL and anon key instead, under every framework's name, one `NAME=value` line each, for a host's settings or `$GITHUB_ENV`. It reads them as `build` does, below, and takes `--allow-local` for a local stack's values.\n\n`dev` and `self-host compose up` refuse a `JWT_SECRET` shorter than 32 characters before starting anything, because the REST API cannot start with one. `init` generates a 64-character secret. To replace a short one, generate a longer secret (for example with `openssl rand -base64 48`), put it in `.env` as `JWT_SECRET`, then run `supatype keys --write --force` to sign new keys with it.\n\n### Schema and database\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `push` | Push schema to the database: diff, prompt for destructive changes, apply migration, generate types. With `--dry-run` it prints the change list and the full SQL the push would apply, then stops: nothing is applied, asked or recorded, and no `--yes` is needed. Supatype Cloud and a linked self-host server cannot write SQL without applying it, so there it prints the change list and says so | `--yes`, `--dry-run`, `--connection <url>`, `--env <name>`, `--direct` (alias `--local`), `--overwrite-drift`, `--run-hooks` |\n| `diff` | Show planned schema changes without applying them (dry run). With `--sql` it then prints the SQL a push would apply, as `migrate` writes it | `--sql`, `--connection <url>`, `--env <name>`, `--direct` |\n| `generate` | Regenerate TypeScript types without running a migration | |\n| `migrate` | Write the SQL a push would apply, without applying it (to preview it on screen, `supatype diff --sql` or `supatype push --dry-run` print the same SQL after the change list). Plain, it takes no lock your application waits on and the file records nothing: applied by hand, the next push finds the tables unmanaged. With `--record` the file also records the migration as a push does | `-o, --output <file>`, `--record`, `--force` |\n| `migrations list` | List applied migrations with schema snapshot metadata | `--connection <url>`, `--env <name>` |\n| `rollback` | Roll back the last applied migration | `--sync-schema`, `--no-sync-schema` |\n| `reset` | Drop every managed table and its rows, apply the schema again, then run the seeds (destructive) | `--yes`, `--no-seed`, `--connection <url>` |\n| `rename [from] [to]` | Record a rename in supatype/renames.json, so every push applies it as a rename and keeps the data: `supatype rename member.name member.title`, or `supatype rename member members` for a table | `--prune` |\n| `doctor` | Report schema drift between schema/index.ts and the live database | `--strict`, `--rebaseline`, `--accept-access-drift`, `--yes` |\n| `adopt` | Hand Supatype the objects a push refuses because their names are taken; take objects back with `--release`, and hand them back with `--reclaim` | `--release <object...>`, `--reclaim <object...>`, `--key <object...>`, `--adopt-none`, `--yes` |\n| `pull` | Scaffold schema/index.ts from live database introspection (draft, review before push) | `--connection <url>`, `--out <path>`, `--dry-run` |\n| `introspect` | Introspect the live Postgres database (JSON or summary) | `--json`, `--out <path>` |\n| `db check` | Check whether a database meets Supatype's requirements (for external Postgres) | `--connection <url>`, `--schema <name>`, `--emit`, `--fix`, `--authenticator-password <password>` |\n| `types check` | Validate generated client augmentation wiring | |\n\n`--direct` skips the control plane of a linked project and runs the schema engine on this machine. `generate` reads only the schema, so it needs no database. In a Next.js app it also replaces the `app/supatype-env.js` route `init` 0.9.1 wrote, whose `export const dynamic` line Next refuses under `cacheComponents`, while that route is still as `init` wrote it, and warns about one changed since ([Next.js](https://www.supatype.com/docs/frameworks.html#nextjs)). `pull` prints its draft unless you pass `--out`. `migrations list` shows each migration's author, how many schema files its snapshot holds and their compressed size, and the renames it applied.\n\nA push never guesses a rename. A column that disappears while a new one appears is a drop and an add, and the drop loses data. In a terminal the push asks whether you meant a rename and records a yes in `supatype/renames.json`. Anywhere else it refuses and prints the `supatype rename` command that records it.\n\nAn object passed to `adopt` is named as `doctor` names it: `kind:table.name`, or `kind:name` for a table. Studio shows the result under [Schema objects](https://www.supatype.com/docs/studio.html#database).\n\n> **PULL:** `pull` writes a draft. Review it before you push: it types every uuid `id` column as `SupatypeAuthUserId` and does not write `tableName`, so fix those by hand.\n\n### Data and seeds\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `seed [file]` | Run database seeds: optional single file; else all seeds/*.ts (alphabetical); else seed.ts | `--status`, `--atomic`, `--connection <dsn>`, `--environment <name>`, `--env <name>`, `--local`, `--confirm-production` |\n| `cache rest list` | List cached REST GET entries | `--table <name>`, `--json` |\n| `cache rest get <key>` | Show one cache entry (full key) | `--json` |\n| `cache rest delete <key>` | Delete one cache entry | |\n| `cache rest flush` | Flush REST cache entries | `--table <name>`, `--yes` |\n\n`seed` on a linked project (Supatype Cloud, or a server linked with `supatype link`) sends the seeds to that server instead of connecting to the database. `--local` seeds the local stack instead, and `--force` is refused. See [Seeding](https://www.supatype.com/docs/seeding.html).\n\n#### Switching the server cache on\n\nA model's `cache` block says which tables may be cached. It does not switch anything on: the running stack keeps its own allowlist, `cache_tables`, and a table is served from the cache only when both agree. `push` and `dev` add each newly declared table to that allowlist through the running stack and never change an entry that already exists. If the stack is not answering they create `.supatype/api-config.json` from the server's default shape and write the entry there.\n\nBoth print a note while `cache_max_ttl` is 0, which it is until you set it: with a TTL of 0 nothing is cached. Set it under API, REST, Settings in Studio, or with the admin API, which is what the CLI calls:\n\nPATCH /admin/v1/config/rest Authorization: Bearer <service role key> { \"cache_max_ttl\": 60, \"cache_tables\": { \"posts\": { \"enabled\": true, \"allow_public\": false } } } All three fields are optional, and `schema` and `max_rows` are left alone when absent. `cache_max_ttl` is 0 to 86400 seconds. `cache_tables` **replaces the whole map**, so read it with `GET /admin/v1/config/rest` and send back the entries you want to keep. The schema's declaration is a ceiling: a table it does not declare, or declares with `enabled: false`, is switched off and listed in the answer's `adjusted` array, and a `cache_max_ttl` above a declared `maxTtl` is lowered to it. Every Cloud plan runs the cache, Free included. Free's is smaller: 10,000 entries of up to 1,024 bytes each, and no row cache. On Cloud, `push` stores the declaration but does not switch tables on, so enable them in Studio or with this call; against a local or self-hosted stack, `push` and `dev` do it for you.\n\n`reset` drops only the tables your schema manages. Sign-ins, Studio users and stored files are kept. It then clears the record of past seed runs, so a `runOnce` seed runs again, and runs the seeds unless you pass `--no-seed`. To start the whole database again, use `supatype dev --reset-db`.\n\n### Functions and hooks\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `functions new <name>` | Scaffold a new edge function | |\n| `functions serve` | Start a local Deno server that serves all functions with hot reload | `--port <port>` (default 18472), `--env-file <path>` (default `.env.local`) |\n| `functions invoke <name>` | Invoke a local or deployed function; exits 1 when it answers 400 or above | `--data <json>`, `--auth`, `--local` (a running `functions serve` if one answers, else the dev API), `--port <port>` (of that serve, default 18472) |\n| `functions deploy` | Deploy all functions (or `--only <name>` for one) to the linked project | `--only <name>`, `--env <name>`, `--dry-run` |\n| `functions list` **Cloud** | List all deployed functions for the linked project | |\n| `functions delete <name>` | Remove a deployed function and its env values from the linked project, on Cloud or on a self-hosted server. On a project that is not linked it removes nothing and says so | |\n| `functions logs <name>` **Cloud** | Tail logs for a deployed function | `--since <duration>` (default 1h) |\n| `functions env list`, `set <KEY=value>`, `unset <key>` **Cloud** | Manage function environment variables | `--function <name>` (one function's own values, which override a shared one) |\n| `hooks new <name>` | Scaffold a hook handler | |\n| `hooks list` | Show the hooks the schema declares and whether each one can run | |\n\nOn an unlinked project with a self-hosted Compose stack, `functions deploy` uploads nothing: the worker serves `functions/` from disk, so it lists the functions and prints the command that restarts the worker. Otherwise it deploys to the linked project, or to Supatype Cloud. On a self-hosted stack, read function logs in Studio. See [Functions](https://www.supatype.com/docs/functions.html).\n\n### Single sign-on\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `sso add <name>` | Register a SAML identity provider. <name> is how every other sso command refers to it | `--metadata-url <url>` or `--metadata-file <path>` (one is required), `--domains <list>`, `--attribute-mapping-file <path>`, `--name-id-format <format>` |\n| `sso list` | List the SAML identity providers | |\n| `sso show <name>` | Show one SAML identity provider | |\n| `sso update <name>` | Change a SAML identity provider in place. Only the flags given change; --domains replaces the list. New metadata must keep the provider's entity ID | The flags of `add`, all optional |\n| `sso remove <name>` | Remove a SAML identity provider. Users who signed in through it can no longer sign in that way | `-y, --yes` |\n| `sso info` | Print the service provider values to give an identity provider: entity ID, ACS URL, NameID, metadata, and the signing certificate (the next one too during a key rotation), read from the served metadata | |\n| `sso verify-domain <name> <domain>` | Prove this project owns <domain>, one of provider <name>'s domains, with a DNS TXT record: prints the record to add and checks it. Exits 1 while the domain is not verified | |\n| `sso rotate-key` | Rotate the SAML signing key: create SUPATYPE_SAML_NEXT_PRIVATE_KEY in .env, published beside the current key while identity providers take the new certificate; then --promote makes it the current key | `--promote`, `-y, --yes` |\n\nTurn SAML on with `auth.sso.saml.enabled` in `supatype.config.ts` first. The `sso` commands reach the linked self-hosted deployment, or else the local stack, which must be running; they do not work against Supatype Cloud yet. Each one warns while SAML is off. The server, not the CLI, fetches `--metadata-url`, and refuses one it cannot reach with `saml_metadata_fetch_failed`, naming the host and the reason. See [Single sign-on](https://www.supatype.com/docs/sso.html).\n\n### Self-host and deploy\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `self-host compose render` | Render deterministic self-host compose artifacts | |\n| `self-host compose up` | Render and start compose services | `-d, --detach` (on by default) |\n| `self-host compose down` | Stop compose services (volumes are kept unless `--volumes`) | `--volumes`, `-y, --yes` |\n| `self-host compose restart <service>` | Recreate one service with the current config and .env, leaving the others running | |\n| `self-host compose status` | Show compose service status | |\n| `self-host compose logs` | Tail compose logs | `--service <name>`, `-f, --follow` |\n| `add domain [domain]` | Add a custom domain with automatic HTTPS (self-host) | `--email <email>` for Let's Encrypt |\n| `link` | Link this project to cloud or self-host (unified .supatype/link.json). Refuses a different project or host than the one already linked, unless `--force` | `--url <url>`, `--token <token>`, `--env <name>`, `--fix-gitignore`, `--force` |\n| `unlink` | Remove this folder's link (`.supatype/link.json`, and the legacy `cloud.json` and `linked.json` if present) and say what was removed | |\n| `envs list` | List linked environments, and the default commands use: `environments` in supatype.config.ts when it names one, else this checkout&apos;s | |\n| `envs use <name>` | Set this checkout&apos;s default environment. `environments.default` in supatype.config.ts wins over it, and `envs use` says so | |\n| `build [command...]` | Run your app's production build with the deployment's API URL and anon key under every front-end name (VITE_, PUBLIC_, NEXT_PUBLIC_, EXPO_PUBLIC_). Runs the package.json build script unless a command follows --. Refuses to start when either value is missing | `--env <name>`, `--allow-local`, `-- <command...>` |\n| `deploy` | Deploy schema and app, Supatype Cloud by default when linked (`supatype link`); pass `--local` for engine + your database | `--env <name>` (default `production`), `--schema-only`, `--app-only`, `--skip-build`, `--preview`, `--yes`, `--overwrite-drift`, `--allow-local` |\n| `deploy rollback` | Roll back to the previous static site deployment | `--to <id>`, `--env <name>` |\n| `deploy status` | Show current deployment status | `--env <name>` |\n| `deploy logs [version]` | Show build logs for a deployment | `--env <name>` |\n\nEvery `self-host compose` command renders `.supatype/self-host/docker-compose.yml` again before it runs. The file names each bind mount by its absolute path on this machine, and names its Compose project `supatype-` plus `project.name`. So `docker compose -f .supatype/self-host/docker-compose.yml` run by hand reaches the same stack, and a project moved to another folder is picked up by the next command.\n\nA render keeps the stack in the mode it runs in. While `supatype dev` runs for the project, commands such as `push`, `update` and `self-host compose` render dev mode. Otherwise they use the mode of the running `server` container, so a push to a production stack leaves it standalone.\n\nCommands that reach the local stack's database or API need that stack running: `push`, `diff`, `adopt`, `doctor`, `seed`, `migrate`, `migrations list`, `rollback`, `reset`, `introspect`, `pull`, `admin`, `cache rest`, and `functions invoke` when no `functions serve` answers. With it stopped they start nothing and refuse with `The local stack isn't running. Start it with `supatype dev`, or `supatype self-host compose up -d` on a server, then run `supatype push` again.`, naming the command run. `seed` exits 2, the others 1. A linked project, `--connection`, `connection` in the config and an external database are reached as they are, and so is an API address named by `SUPATYPE_URL` or `SUPATYPE_API_URL` in `.env`.\n\n`build` takes each value from the first of: the environment (`SUPATYPE_URL`, `SUPATYPE_ANON_KEY` or any framework's name), the `/supatype-env.json` of the server the environment's URL names (for the anon key only, so CI can set just `SUPATYPE_URL`), the linked environment, and a `.env` that records a deployment (`PUBLIC_SUPATYPE_URL` or `API_EXTERNAL_URL`, and `ANON_KEY`). An anon key counts only for the URL being built for; one a source holds for another deployment is listed as skipped. It refuses a local address unless you pass `--allow-local`, never gives the build the service role key, writes no file, and exits with the build's own code. A package.json build script that is itself `supatype build` is refused rather than run again. `deploy` builds the app the same way. See [Deploy your frontend](https://www.supatype.com/docs/deploying-your-frontend.html).\n\nFor a self-hosted stack, `link --url` takes the stack's gateway URL and `--token` its `SERVICE_ROLE_KEY`. The link is made to the project the server says it serves, whatever this folder is called.\n\nA folder holds one link, to Supatype Cloud or to a self-hosted server, and `envs use` chooses between environments of that one link. `link` to a different project, or to the other kind of host, refuses and names the link that is there: run `supatype unlink` to remove it, or pass `--force` to replace it with a fresh one. Linking the same project again (to refresh a token, or to add an environment with `--env`) always works. To work against both hosts at once, keep a folder for each (a second clone or a `git worktree`) and link each to its own host. The full walkthrough is in [Self-host](https://www.supatype.com/docs/#self-host) and [Deploy to a VM with GitHub Actions](https://www.supatype.com/deploy-vm-github-actions.html).\n\n### Supatype Cloud\n\nAll of these need Supatype Cloud, which is in closed beta ([request access](https://www.supatype.com/#cloud)).\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `login` | Sign in to Supatype Cloud in your browser. It opens the accounts site, you approve, and type the code shown there into the terminal; the CLI stores a personal access token (`spt_...`) for push and deploy. The URL is always printed. The CLI asks the control plane where the accounts site is (`GET /api/v1/cli/login/config`), or you set `SUPATYPE_ACCOUNTS_URL`; if neither gives an address, login stops and says so. A Cloud behind a bot check refuses the CLI with `captcha_failed`; login then says that sign-in works only through the browser and points to `--token` for CI. Any other refusal prints the control plane's own message and exits 1. A new Cloud account cannot create a project until it is approved (closed beta) | `--api-url <url>` (a Cloud other than supatype.com; `SUPATYPE_API_URL` sets it too),`--name <name>` (the token's name, default `cli_<hostname>_<time>`), `--no-browser`, `--token <spt_...>` (store a token made in your account instead of signing in, for CI; `SUPATYPE_ACCESS_TOKEN` takes one too) |\n| `logout` | Clear stored Supatype Cloud credentials | |\n| `whoami` | Show the current Supatype Cloud session, checked against the control plane. Exit 0 when valid, 1 when rejected, 2 when the control plane cannot be reached | |\n| `link --project <slug>` | Link this project to cloud or self-host (unified .supatype/link.json). A cloud link asks the Cloud you signed in to with `login`, unless `--api-url` or `SUPATYPE_API_URL` names another | `--api-url <url>`, `--token <token>`, `--env <name>` |\n| `projects list` | List your projects. In a linked project it lists that project's organisation; before a link it lists every organisation you belong to (just the one, if you have one) | `--org <slug>` (one organisation only) |\n| `projects create <name>` | Create a new project, in your only organisation, or the one `--org` names (required when you belong to several and nothing is linked) | `--tier <tier>`, `--region <region>`, `--org <slug>` |\n| `projects pause <slug>` | Pause a project | `--org <slug>` |\n| `projects resume <slug>` | Resume a paused project | `--org <slug>` |\n| `domains list`, `add <domain>`, `remove <domainId>`, `verify <domainId>` | Manage custom domains for a project | |\n| `envs create <name>` | Create a cloud environment (staging/preview) | |\n| `db connection-string` | Show the database connection string for the linked project | `--transaction`, `--env <name>` |\n| `db reset-password` | Reset the database password for the linked project | `--env <name>` |\n\n### Binaries and updates\n\n| Command | Description | Useful flags |\n| --- | --- | --- |\n| `self-update` | Update the supatype CLI (npm or standalone CDN binary) | `--force` |\n| `update` | Download the latest component binaries and update versions in supatype.config.ts. On a Docker project it checks for a newer CLI release first and says to upgrade the CLI when one exists, because the image pins come from the CLI version, then pulls the images this CLI pins. `--check` reports the running CLI, the latest release and whether an upgrade would move the pins, and pulls nothing | `--check` |\n| `engine status` | Run the host engine binary's `--version` and show which binary answered | |\n| `cache list` | List cached component binaries and their sizes | `--project <path>` |\n| `cache clean [component] [version]` | Remove cached binaries not pinned by local project configs, and CLI programs of other versions (`cache clean cli` for those alone) | `--dry-run`, `--force`, `--project <path>` |\n| `migrate-from-v1` | Codemod runtime model() schema DSL into RFC v2 Model<> type aliases | `--schema <path>`, `--write` |\n\nBinaries are cached in `~/.supatype/cache/`. `cache clean --force` removes every cached binary, pinned or not.\n\nUpgrading an npm install leaves the previous version's program in `~/.supatype/cache/cli/`, since another project may still use it. Once the programs of other versions take more than 250 MB, the CLI says so when it starts, at most once a day. `cache clean` removes them, and never the running version; a project still on a removed version downloads it again on its next command.\n\n## Versions\n\nSource: https://www.supatype.com/docs/versions.html\n\nWhat each part of a Supatype release is at, so you can tell which versions go together.\n\nPre-1.0: APIs and config may change between releases.\n\n### What a release is made of\n\nA release is one number for the CLI and every `@supatype/*` package. The engine, server and Postgres images it runs, and the Deno that functions run on, are pinned by that release and move with it, not with the newest image on Docker Hub.\n\n| Component | Version | What it is |\n| --- | --- | --- |\n| CLI and npm packages | `0.11.0` | The latest release, 2026-11-29. The published `@supatype/*` packages, such as `@supatype/client` and `@supatype/react`, carry the same number |\n| Schema engine | `v0.12.0` | Parses the schema, plans and applies a push (`supatype/schema-engine`) |\n| Server | `v2.7.0` | The Supatype server: the API, auth and the services behind it (`supatype/server`) |\n| Postgres | `17.2.16` | The database image, with its extensions (`supatype/postgres`) |\n| Deno | `2.9.8` | The runtime for functions and hooks |\n\nThe pins come from `release/images.json` in the repository, and the page is generated from it, so it is out of date only between a pin changing and the next site sync.\n\n### There is no 0.4, 0.5 or 0.6\n\nThe CLI went from 0.3.6 straight to 0.7.0, on npm and as git tags. Nothing is missing from the [changelog](https://www.supatype.com/changelog.html): those versions were never released.\n\n### Check what you run\n\n`supatype --version` prints the CLI version. A self-hosted stack pins the images in its rendered compose file; `supatype self-host compose up -d` renders it again after an upgrade.\n\n## Licensing\n\nSource: https://www.supatype.com/licensing.html\n\nWhat you can do with Supatype, in plain words. This page is a guide and is not legal advice. It does not change any licence: where it and a licence differ, the licence governs.\n\nPre-1.0: APIs and config may change between releases.\n\n### In one minute\n\n**SDKs and server** (MIT): The client SDKs, framework bindings and plugins, and the API server (`supatype/server`). Use them for anything.\n\n**CLI and services** (APACHE 2.0): The CLI, Studio and the services in this repository (storage, realtime, functions worker). Use them for anything.\n\n**Schema engine** (BSL 1.1): Source-available under the Business Source License 1.1 (SPDX `BUSL-1.1`), and its source is at [github.com/supatype/schema-engine](https://github.com/supatype/schema-engine). You can read it, change it, redistribute it and run it in production.\n\n- The Postgres image (`supatype/postgres`) is under the **PostgreSQL License**. Use it for anything.\n- The one thing you cannot do without a commercial licence: offer Supatype or the engine to others as a hosted or managed service, paid or free, or sell a product whose primary value is the engine.\n- Each engine version becomes **Apache 2.0** on its Change Date, four years after that version's release.\n\nThe engine's licence, with its Additional Use Grant, is in the `LICENSE` file at the root of the [engine's repository](https://github.com/supatype/schema-engine) and ships with every engine release, beside the binary on `releases.supatype.com` and at `/LICENSE` in the `supatype/schema-engine` image. `supatype-engine licence` prints the exact terms for the version you have.\n\n### Can I? Yes\n\n| Can I... | Answer |\n| --- | --- |\n| Build and sell my own app on Supatype? | Yes, commercial apps included. That is what the engine is for. |\n| Self-host Supatype for my company? | Yes, on infrastructure you own, rent or control, for your own applications and products. |\n| Run it for my clients as an agency? | Yes. You can build, host and maintain applications for clients, including one Supatype stack per client's app. |\n| Let my app's users define their own fields? | Yes, where that schema management is incidental to what your app does (custom fields in a CRM, for example). |\n| Modify the engine and use it internally? | Yes. Your changes stay under BSL 1.1. |\n| Fork it? | Yes. A fork carries the same licence and the same limits. |\n| Use it in a free open source project? | Yes, as long as the project is not itself a hosted Supatype-style service for others. |\n| Use it inside a group of companies? | Yes. Affiliates under common control count as you, so an internal platform team can serve the whole group. |\n\n### Can I? Not without a commercial licence\n\n- **Give others the engine's functionality as a hosted or managed service.** Paid or free, to anyone other than your employees and contractors, in whole or in substantial part. The licence calls this a Competing Service. It includes offering Supatype or the engine as a hosted or managed database, backend or schema management service on which others define, migrate or manage database schemas they control, or build and run their own applications.\n- **Sell a product whose primary value is the engine.** Sold, licensed or otherwise provided for a fee, including through paid support or subscriptions. For example, a schema management, schema migration or database change management tool built on it, or a backend platform that includes or requires it. The licence calls this a Competing Product.\n\nIf your product is not competing when you first make it generally available, it does not become competing later because Supatype ships a new version or a new product.\n\n> **FREE HOSTING COUNTS:** Some source-available licences only restrict paid offerings. Ours restricts free hosted offerings too, because a free hosted Supatype competes with Supatype Cloud just as much.\n\n### Grey areas, worked through\n\n| Situation | Allowed? |\n| --- | --- |\n| A SaaS where each customer adds custom fields to their records | Yes. Field management is incidental to the product. |\n| An internal platform team running Supatype for many teams in the same company or group | Yes. That is internal use by affiliates under common control. |\n| An agency hosting several clients' apps, each on its own Supatype stack | Yes. |\n| An agency offering clients a general platform on which they build their own apps | No, that is a Competing Service. |\n| A hosting company offering one-click Supatype for its customers | Needs a commercial licence. |\n| A hosted app builder whose customers design their own databases | Needs a commercial licence. |\n\nNot sure where you fall? Ask at [licensing@supatype.com](mailto:licensing@supatype.com).\n\n### Versions and dates\n\n- **Each version has its own Change Date**, set when it is released, to the release date plus four years. It is written in that version's `LICENSE`.\n- **On the Change Date** that version, and only that version, becomes available under the Apache License 2.0. Later versions keep their own dates.\n- **Commits between releases** on the engine's `main` branch are part of the next release and take its Change Date.\n- **All earlier versions and commits** are made available under the same BSL 1.1 terms, with the same Additional Use Grant and the same Change Date as 0.7.0. That includes 0.1.5 to 0.6.0, which were distributed as binaries without a licence, and commits from before the engine's repository had a `LICENSE` file.\n\n### The other packages\n\n| Component | Licence |\n| --- | --- |\n| `client`, `types`, `react`, `react-native`, `vue`, `svelte`, `solid`, `ssr`, the auth UI packages, the plugin packages, `ui`, `common` | MIT |\n| CLI, Studio, storage, realtime, functions worker, self-host control plane, and the rest of the `supatype/supatype` repository | Apache 2.0 |\n| API server ([`supatype/server`](https://github.com/supatype/server)) | MIT |\n| Postgres image ([`supatype/postgres`](https://github.com/supatype/postgres)) | PostgreSQL License |\n| Schema engine (`supatype-engine`, image `supatype/schema-engine`) | BSL 1.1, Apache 2.0 on each version's Change Date |\n\nThe CLI downloads the engine as a separate binary; the CLI's own licence is unaffected. Your application code, schemas and data are yours, whatever you build them with.\n\n### Contributing\n\nContributions need a signed [Contributor License Agreement](https://github.com/supatype/supatype/blob/main/CLA.md), signed once through CLA Assistant on your first pull request. It is a licence, not an assignment: you keep the copyright and grant Supatype Ltd the right to use and relicense your contribution, which is what lets each version move to Apache 2.0 and be offered under commercial terms. Contributing gives you no extra rights in the product, and takes none away.\n\n### Commercial licences\n\nTo run a hosted service on the engine, embed it in a product you sell, or anything else the grant does not cover, contact [licensing@supatype.com](mailto:licensing@supatype.com). The Licensor is Supatype Ltd.\n\n### Why BSL\n\nWe want you to be able to read the code that changes your database, run it wherever you like, and never depend on us to keep your app alive. We also need a business that can pay for the engine. The BSL lets us give you the first without a hosting company taking the engine and competing with Supatype Cloud on day one. Every version still becomes Apache 2.0 after four years.\n\n## Changelog\n\nSource: https://www.supatype.com/changelog.html\n\nWhat changed in each Supatype release, in short. Every pull request is listed on [GitHub releases](https://github.com/supatype/supatype/releases).\n\n### Next release\n\nNot released yet\n\n- **MCP servers.** `supatype mcp` starts a developer MCP server over stdio, so a coding agent can read the schema, diff, push, generate types, read status and logs, and search the docs. A destructive push, or a push to a linked `production` environment, is refused unless the call passes `confirmDestructive: true`.\n- **Project MCP.** A self-hosted stack serves an MCP endpoint at `/mcp` on its API URL. An agent signs in with a Studio login and approves in the browser, then works with records, drafts and publishing using that person's Studio role. See [MCP servers](https://www.supatype.com/docs/mcp.html).\n\n### 0.7.0\n\n27 October 2026\n\n- **Supatype knows what it owns.** `supatype adopt` takes over a table a push refused, `--release` hands it back, and `--reclaim` takes a released one again. Studio has a Schema objects view of all of it.\n- **`supatype doctor`** shows drifted, conflicting and released objects, and `--rebaseline` starts the record afresh.\n- **Safer pushes.** A push asks before it puts back access changed outside Supatype, and offers to declare a rename before it asks to drop data. A change that rewrites a whole table needs your consent.\n- **Realtime** delivers deletes with the old row, judged by the same read rules as everything else.\n- **Auth providers** are set with `auth.providers` in the config.\n- **Studio** gains a Realtime Inspector for self-hosted stacks.\n- Secrets and the database URL no longer appear on any child process's command line.\n\n### 0.3\n\n23 September to 2 October 2026\n\n- **Publishing, drafts and versions** for content models.\n- **Functions** run concurrently, with their logs.\n- **Storage** moves to SeaweedFS.\n- **Model caches.** A model can declare a cache, and a push refuses one that cannot be served.\n- **Vue, Svelte and Solid** reach parity with React.\n- A model can set its own Studio labels (0.3.6).\n\n### 0.2\n\n2 to 3 September 2026\n\n- **Supatype's own auth** replaces GoTrue in the CLI, the client and Studio.\n- A push refuses a schema that the database engine in use cannot enforce.\n\n### Earlier\n\nReleases before 0.2 are on [GitHub releases](https://github.com/supatype/supatype/releases).\n";
2
+ //# sourceMappingURL=llms-docs.d.ts.map