gen
Generate database types, typed models, relation metadata and validators.
better-supabase gen [--only <list>] [--check] [--snapshot <file>] [--db-url-stdin | --project-ref <ref>]
better-supabase gen --metadata <path|-> [--only <file> | --out <dir> [--check]]gen is the one command to run after a schema or config change. It writes
the typed client from the database, then every other generated file the
config sets up, so the config holds the options instead of each command line.
Side effects: Writes files, reads the database, calls the Supabase Management API with --project-ref.
Tasks
| Task | Runs by default when | Does what |
|---|---|---|
types | always | Writes the files this page describes |
sql | blocks lists a module, or realtime.policies is set | upgrade: rewrites the SQL module files |
powersync | gen.powersync is set | powersync streams: writes the sync streams, the schema and the publication migration |
spec | the api.specs.entry file exists | spec emit, with api.specs.failOn and api.specs.manifest |
seed | the database.seed.entry file exists | seed: renders the fixtures to SQL |
env | never; list it to run it | env: writes the local stack's keys to env.output |
The tasks run in that order, since later ones read what earlier ones write.
Pin the list in the config with gen.tasks, or pass --only for one run:
export default defineConfig({
gen: { tasks: ["types", "sql", "spec"], watchInterval: 1000 },
});better-supabase gen --only spec,seedA listed task always runs, even when the config doesn't set it up, so a
missing entry file fails loudly instead of being skipped. A run that writes
stops at the first task that fails. --check runs every task and reports
everything that is out of date, and leaves env out because it writes local
keys rather than a committed file. With one task, the output is that task's
own; with several, each gets a section headed by its name.
When --check finds stale SQL files, it adds a line that splits them into
subject, search and other files (for example Drift: 3 subject files, 2 search files), so a new subject case reads differently from unrelated drift. The
JSON output carries the same counts in data.drift.
gen --metadata reads the schema from a document and runs no other task.
gen introspects your database with
@supabase/postgrest-typegen,
the same generator behind supabase gen types typescript, and writes:
database.types.ts, whatsupabase gen typesprints for the same schema (CI checks this against the Supabase CLI), socreateClient<Database>()works as usual;- the main module (
output), with models in your casing, enum and CHECK constants, typed constraint names, and theschemaobject; - the runtime metadata next to it (
generated.meta.js, withgenerated.meta.d.ts): tables, columns, relations with foreign key actions, and functions. Relations follow each foreign key to the table it references; the copies PostgREST lists for views over that table are left out, so adding a view never renames another table's relations. It is plain JavaScript typed asSchemaMeta, so TypeScript doesn't check a large object literal in every program that imports the main module. Each table and function is one line of JSON, which keeps the module small to load and a schema change visible per entry in a diff. Commit both files with the main module; - with
blocksconfigured,blocks.config.tsnext to the main module: each installed block's schema, API schema and the options its SQL and TypeScript halves share, with the module defaults filled in, as data only, fordefineBlocks(blockConfig, ...)andcreateClient(app, { blocks: blockConfig }). Browser code imports it without pulling in any block client.blocks.generated.tsre-exportsblockConfigand addsblocks, each instance's manifest under its key, forbetterSupabase.blocks(): import it from server code only. Withgen.clientBlocksset,blocks.client.tsholdsclientBlocks,defineBlocksover just the listed instances, so the browser bundle carries those clients and no others. Withgen.serverBlocksset ({ shell: ["permissions", "organizations"] }),blocks.shell.tsholdsshellBlocksandshellInstancesthe same way for the server, so a route that builds its server from the set (createNext(app.blocks(shellBlocks))) bundles those blocks and no others. Thereadsconstant lists, next to each table a read touches, the typed key of every view your schema files project over it (job_attachmentsoverattachments), so a cached read served from the view is invalidated by a write to the table. None of this needs a database, only the config; - with blocks that have a record binding installed, a
record type per type in
config.recordTypes, inrecords/<type>.tsnext to the main module, unlessgen.recordsisfalse; - with
gen.hooksset,hooks.tsnext to the main module: a list hook and a record hook per table (useCustomers,useCustomer) for the data hooks of that framework. A block table that one of your views projects gets no hooks; its view's hooks read it; - one file per configured generator (
zod(),valibot(),jsonSchema(),standardSchema()); - with
readSetsconfigured, theread-setsSQL module file: one function per read set.genimports those modules after writing the main module, since they import it.
It doesn't need Docker or the Supabase CLI: it only needs a way to run SQL.
Files are only rewritten when their contents change, so watchers and bundlers
don't rebuild for nothing. Line endings don't count as a change: a checkout
with core.autocrlf keeps its \r\n files, and --check passes on them.
database.types.ts is formatted with oxfmt,
an optional peer. Without it, gen writes the file unformatted and says so;
install it with pnpm add -D oxfmt. better-supabase accepts any oxfmt from
0.66.0 up to, but not including, 1.0. @supabase/postgrest-typegen pins exactly 0.66.0 as its
peer, the version that formats like supabase gen types, so pnpm
warns about a newer oxfmt until you allow it in pnpm-workspace.yaml:
peerDependencyRules:
allowedVersions:
"@supabase/postgrest-typegen>oxfmt": "0.71.0"Names are sorted by code point, not by locale, so every machine writes the same files.
Introspection cache
Before reading a database, gen runs one query that hashes the system
catalogs (tables, columns, constraints, policies, functions, grants, comments,
role memberships and role settings; planner statistics are left out). When the hash, the
schemas, the better-supabase version and the pinned typegen version match the
last run, it reuses the
snapshot cached in node_modules/.cache/better-supabase and skips
introspection. Deleting that folder clears the cache.
dev keeps one connection open and runs that query
whenever a file changes or the polling interval passes, so it reads the full
schema only after a change. gen --watch was removed in favor of dev;
--no-cache skips the cache for one run and
cache purge deletes it. Connecting gives up after 10
seconds, and each introspection query after 2 minutes.
Content mapper
With gen.contentMapper: true, gen writes schema.bsb and a
generated.ts that re-exports its types, and no database.types.ts;
TypeScript 7.1 gets the types from the
content mapper. The types task also writes the
mapper's cache, and when the types change, a stamp file in
node_modules/.cache/better-supabase that the editor watches, so dev
reloads the types in the editor too. --check checks the mapper-mode files.
Enum and column constants
gen.constants: true writes two modules next to the generated module, and
neither imports anything. enums.ts holds every enum and every CHECK value
list as a constant array and its union type (noteKindValues, NoteKind), so a
browser form or a script reads them without the runtime package. columns.ts
holds one constant per table that maps each column's row name, in the
configured casing, to its database name (customersColumns.createdAt is
"created_at"), for $client, queryRaw and SQL. It is off by default.
Table modules
By default gen writes one module per table, tables/<table>.ts, next to the
generated module (gen.tableModules: false writes the single module instead). Each one exports the table's runtime metadata as
<key>Table (customersTable), and generated.meta.js lists no table. A page
that imports one table module does not load the others. gen.types.tables.only
lists the relations database.types.ts includes; the rest are omitted, and
gen.types.also lists more files that get a copy of it, for a monorepo whose apps share the types. The
server's schema moves to generated-schema.ts, which imports every table. The
generated module keeps the types, buckets, the extensions and clientSchema,
a schema with no tables for a browser client.
A client on clientSchema registers the tables it uses. Pass the module to
bsb.table, which returns the repository, or to a generated hook, which reads
through it. A table you embed with with is registered the same way before the
query.
import { createSupabase } from "better-supabase";
import { createClient } from "better-supabase/client";
import { clientSchema } from "./generated";
import { customersTable } from "./tables/customers";
const bsb = createClient(createSupabase(clientSchema), { env });
const customers = bsb.table(customersTable);
await customers.list({ where: { status: "active" } });The generated hooks.ts does this for every gen.hooks framework (React, Vue,
Solid and Svelte): each hook is made with the table module and reads through
client.table. The file also exports AppDb, an interface over the app's
db, so each hook resolves one named type. Doctor reports a "use client" file
that imports generated-schema, blocks.generated or blocks.config
(BS621).
defineListQuery takes a table module in place of a table name, so a module
that defines a list for a client component loads one table. Keep server code on
schema from generated-schema.ts: a page that imports it loads every table.
tests/next-build in this repository holds the Next.js example to that rule.
--metadata output and the content mapper write the single-module output. An
existing project moves to this layout with better-supabase codemod table-modules:
it imports schema from generated-schema and, in a "use client" file,
rewrites bsb.db.customers to bsb.table(customersTable) with the import.
Block modules
By default gen writes blocks/slices.ts, one export per
installed block instance (commentsConfig, customFieldsConfig), and
blocks/permissions.ts with permissions and PermissionKey. A slice is the
instance's schema, API schema, function names and options as plain data.
blocks.config.ts composes the slices into blockConfig for server code, and
each records/<type>.ts imports only the slices of the blocks it binds, so a
record no longer carries the config of every installed block.
Client code imports the slices it uses and passes them to the client:
import { commentsConfig, tagsConfig } from "@/lib/supabase/blocks/slices";
export const bsb = createClient(clientApp, {
env,
blocks: { comments: commentsConfig, tags: tagsConfig },
});A client component that imported blockConfig loads every slice, so import the
slice instead (commentsConfig.api). A record's own slices fill in the blocks
the client's blocks option leaves out. The slices live in one module because a
bundler drops the exports a page doesn't import, and a module per instance adds
a wrapper to the chunk for each one. gen.blockModules: false writes
blockConfig as one object.
The slices are plain data. The block API types stay in blocks.generated.ts
as aliases over the block packages, because writing a concrete interface per
instance needs a type extraction step that gen does not have. Import those
types with import type, which costs nothing at runtime.
Permission catalog
With gen.permissionCatalog: true and blocks.permissions.model: "catalog",
gen writes <stamp>_better_supabase_permission_catalog.sql, a migration that
inserts a row for every permission key the installed blocks check or declare on
their entities, and the default grants of the owner, admin and member
roles. A new block's pages no longer answer 403 for the owner until you write a
catalog migration by hand. When the installed blocks or their keys change, the
next gen writes a new migration that holds every statement again, and
gen --check reports the file as stale. Every statement skips rows that exist,
and the migration runs again whole, so it grants a key's defaults again after
you removed one. Change a role's grants in your own migration only for keys the
generated one does not hold.
The same run writes permission-scopes.ts next to blocks.config.ts:
| Export | Holds |
|---|---|
apiKeyScopes | Every tenant permission key, for scopes of an API key |
oauthScopes | The same keys without the manage keys, for the scopes an OAuth client requests |
It also writes proxy-permissions.generated.ts, which exports
proxyPermissions ({ hash, keys }, the keys in bit order). A proxy that
passes it as catalog reads the token's permission bitset without importing
the catalog's source. The hash covers the key order, so a catalog with extra
keys (legacy ones, for example) needs its own permissionCatalog() call.
Platform keys get a catalog row and no default grant. The command needs the
managed catalog tables; it stops with config_invalid when
blocks.permissions.tables or columns rename them.
Entity pages
With gen.entityPages, gen writes the list of each page you declare with
defineEntityPage. The block manifest of
the entity supplies its sorts, facets, filters and search, so the descriptor
stays small. For a page named risks, the run writes:
| File | Holds |
|---|---|
pages/risks.list.ts next to output | risksList, a defineEntityListQuery over the declared surface |
<appDir>/api/risks/list/route.ts | The GET handler that parses the URL, runs the list and answers 400 with the issues |
<stamp>_better_supabase_entity_page_indexes.sql | A migration with one create index if not exists per sort, facet and searched column that is a column of the table |
<scaleDir>/scale_list_risks.test.sql | A pgTAP file that plans each sort and facet with sequential, bitmap and sort plans off |
pages/risks.columns.ts | risksColumns with the label, kind, sort and filter of each columns entry (only with columns) |
pages/risks.detail.ts | risksDetail: the route, the sections and href(id) (only with sections) |
pages/risks.form.ts | risksCreateForm and risksEditForm over the block's input and change schemas (only when the block exports them) |
pages/risks.seed.ts | risksSeed: the table, tenant column, tiers and seed.demo rows (only with seed) |
pages/risks.navigation.ts | risksNav: area, label, href, recordHref and titleKey (only with area) |
<appDir>/api/risks/export/route.ts | GET /api/risks/export: exportResponse over page under the list's filters (only with export) |
pages/routes.manifest.ts | entityRoutes: list, API, detail and export routes and the message keys of every page |
pages/coverage.ts | pageCoverage: the routes of each block's pages, keyed by block, for the app's coverage map |
An index is a btree on (tenant, column, id) for a sort and (tenant, column)
for a facet, or a trigram index for a searched column. A name that is not a
column of the table, such as a derived sort, has no index. A facet index whose columns equal a btree index the table already has
(a block's own (tenant_id, status) index) is not written again, so doctor never reports a duplicate. Each entry of sortLists, a
multi-column sort the page offers, adds one btree on (tenant, a, b, id); gen stops with
config_invalid for an entry with fewer than two or more than three keys, or a key outside the
entity's sorts. The scale file covers single sorts and facets only. It fails
when a sort needs a sort step or a facet count does not read an index, and it
reads the rows of the running stack, so run pnpm db:seed:scale first to
measure a large table. BS636 reports the same gap in a
running database.
The settings:
| Key | Default | Effect |
|---|---|---|
pages | none | The descriptors |
appDir | src/app, or app without a src folder | Where the route handlers go |
server | @/lib/supabase/server-core, bsbCore | The module and export the routes get route() from |
scaleDir | supabase/tests/scale | Where the pgTAP files go; it may sit outside the project |
A block that takes organizationId on every call sets tenantOption: "organizationId", and the routes pass the
request's tenant under that name. An entity no block owns is named app.<entity> and sets app with its surface,
its table and the module that reads it, so gen writes its routes, indexes and scale test without a manifest.
gen stops with config_invalid when the block is not installed, when its
manifest declares no list for the entity, when a columns entry is not a column of the table, when a
section name is not lowercase words joined by -, or when two pages share a name.
Options
| Option | Effect |
|---|---|
--only <list> | The tasks to run, comma-separated. Defaults to gen.tasks, then every task the config sets up. |
--check | Writes nothing; exits 1 when a generated file is out of date and prints a diff of each one. Use it in CI. |
--dry-run | Prints a diff of each file that would change, and writes nothing. |
--offline | Never connects: reads the saved snapshot (--snapshot or source.snapshot) and fails without one, so gen --check --offline runs in CI without a database. |
--force | Overwrites a generated file that lost its Generated by better-supabase header. |
--snapshot <file> | Reads a saved snapshot instead of connecting. |
--db-url-stdin | Reads the connection string from stdin; overrides the config, $DATABASE_URL and $SUPABASE_DB_URL. |
--project-ref <ref> | Reads a hosted project through the Management API. |
--metadata <path|-> | Reads a GeneratorMetadata document (- for stdin) and prints one file on stdout. See From a GeneratorMetadata document. |
--only <file> | With --metadata, the file to print: schema (default), types, zod, valibot, json-schema or standard-schema. |
--out <dir> | With --metadata, writes every generated file into this directory instead of printing one. |
With --json, the envelope's data is { "tables", "written" } for gen
and { "upToDate", "stale" } for gen --check. When several tasks run,
data is { "tasks": { "<task>": { "code", "data" } } } instead, with each
task's result under its name.
A connection string holds the database password, so no command takes one as
an argument, where it would land in shell history and the process list. Set
$DATABASE_URL or $SUPABASE_DB_URL, or pipe it in:
printf %s "$PROD_DB_URL" | better-supabase gen --check --db-url-stdinExpose only the functions you use
With sql.api or a block's api, every function a role may execute gets a
wrapper in the API schema, and PostgREST loads each one into its schema cache.
Set gen.api.expose to "used" to keep a wrapper only for the functions your
sources name, plus the functions a block's own TypeScript client calls.
export default defineConfig({
gen: {
api: {
expose: "used",
// Functions that only a database job or another service calls.
exposeAlso: ["purge_rate_limits"],
},
},
});gen reads the words in the files matched by doctor.sources, leaves the
generated folder out and keeps the wrappers whose names appear. The default,
"all", keeps every wrapper. Each change to the list is a DDL batch, so ship it in one
migration per deploy. Doctor rule BS244 warns when the schema
cache grows past the point where this pays off.
Where the schema comes from
In order:
--snapshot,--db-url-stdinor--project-ref;database.source.snapshotin the config, when none of those flags is passed;database.source.dbUrlordatabase.source.projectRefin the config;- a Supabase Lite project's
[db] driverinsupabase/config.toml(turn this off withdatabase.source.lite: false); $DATABASE_URL;$SUPABASE_DB_URL, the name the Supabase CLI andbetter-supabase dev envuse;$POSTGRES_URL_NON_POOLING, then$POSTGRES_URL: the direct and pooled strings the Vercel Marketplace integration sets, whichvercel env pullorvercel env run -- better-supabase genputs in the environment (the direct one comes first, because introspection needs a session);- the local stack, on the
[db] portfromsupabase/config.toml. Whenconfig.tomlsets no port, as on the CLI's stack engine ([experimental] stack = true), theDB_URLfromsupabase status. When neither answers, the command fails withnot_foundand names both, instead of guessing port 54322, which could be another project's stack.
On a Lite project, the postgres driver reads its [db] url. The pglite
and sqlite-postgres drivers replay supabase/migrations and then the
declarative schema files into an in-memory PGlite with Lite's auth schema,
and introspect that, so gen needs no running server. The bare sqlite
driver takes native SQLite DDL, which gen can't read: switch to
sqlite-postgres, or save a snapshot.
Hosted projects without a database password
database.source.projectRef (or --project-ref) runs the introspection queries
through the Management API's read-only SQL endpoint
(POST /v1/projects/{ref}/database/query/read-only). You need a
personal access token in
SUPABASE_ACCESS_TOKEN, not the database password, and the queries run as a
read-only role.
Create a scoped token for this: limit it to the project and the read-only query permission the personal access tokens guide lists for that endpoint. A classic token carries your whole account, on every organization and project, which is more than CI or an agent needs. A scoped token that lacks the permission answers "You do not have permission to perform this action".
export default defineConfig({
database: { source: { projectRef: "abcdefghijklmnopqrst" } },
});SUPABASE_ACCESS_TOKEN=sbp_... better-supabase gen --checkSUPABASE_API_URL points it at another Management API host.
SQL in the config
Before it reads the schema, gen parses the SQL the config carries: the
authorization provider's functions templates, the through.where conditions
of roleSources and platformRoles, the setup statements of personas and
fixtureRoles, the boost, predicate and order of vectorSearch, and the
{ sql } values of realtime.triggers payloads and of a block's
events.payload. Placeholders such as {user} and {row} stand for a value.
SQL that does not parse stops gen with the config key and the parser's
message, for example authorization.functions.canAssign is not valid SQL,
instead of failing later in a migration.
Installed modules
gen also renders the modules of the blocks you installed and parses each file
with the Postgres reader. A module that renders SQL Postgres rejects stops gen
with the module name, the file position and the statement. That is a bug in the
module template, so report it. gen --out skips the check.
What the metadata knows
The generated schema carries what the runtime needs to stay correct without
extra round trips:
-
Read-only columns. Generated columns,
identity alwayscolumns and view columns Postgres marks as not insertable or updatable are left out of theInsertandUpdatetypes, and writes to them fail before a request is sent. -
Unique keys and constraint names.
getaccepts the primary key or any named unique key, andUniqueConstraint,CheckConstraintandForeignKeyConstrainttypes narrowisConflict(error, 'customers_kvk_key'). See unique keys and errors. -
Foreign key actions.
on delete cascade,set nullandset defaultare recorded on relations, so a delete invalidates the tables it changes. See caching. -
Codecs. With
codecsin the config,int8,numericandtimestamptzcolumns are read exactly (asbigint,stringorTemporal.Instant;timestampbecomesTemporal.PlainDateTime), and the generated validators match. See Temporal. -
Columns a CHECK makes not null. A nullable column with
check (slug is not null), alone or as a term of a top-leveland, is typed and validated as not null. It is required on insert unless it has a default or a row-levelbefore inserttrigger fills it before the CHECK runs.genreads the trigger's PL/pgSQL body: the column counts as filled when the body assigns it (new.slug := …,new.slug = …orselect … into new.slug). A trigger that only validates leaves it required. Whengencan't tell (another language, or the body replaces the whole row withnew := …), the column stays optional. A term underorornot, and anot validconstraint, change nothing. Prefernot nullon the column itself when you can. -
Columns the database fills on insert. A not-null column without a default is required in
InsertOfand the insert validators. When a trigger or another database rule fills it, list its database name intables.<table>.insertOptionalandgenmakes it optional on insert while the row type stays not null:better-supabase.config.ts export default defineConfig({ tables: { invoices: { insertOptional: ["number"] } }, });genfails when a listed name is not a column of the table. ThecolumnandsequenceColumnof each numbering entity with atableare optional on insert without being listed, unless the block is incustommode. -
Generated columns. A generated column (
generated always as (...) stored) or an identity columnalwaysis inRowand typed?: neverinInsertandUpdate.WritableColumnOf<"table">is the union of the columns the database lets you write, andGeneratedColumnOf<"table">is the rest. The generic forms,WritableColumns<Models, T>andGeneratedColumns<Models, T>, come frombetter-supabase. Use them to check a column list against the table, for example the columns an offline client uploads (see PowerSync). -
Function arguments and results. Every argument in
Functionsacceptsnull, since Postgres passesnullto any function, and arguments with a default are optional. Functions that return rows of a table or areturns table (...)record get aresultentry, sodb.$rpcreturns them in your casing. -
Overloaded functions. A function with several signatures gets a union of
{ Args; Returns }inFunctions, one member per overload in signature order, as indatabase.types.ts. PostgREST picks an overload by the argument names, sodb.$rpcdoes too: a call type-checks against any overload, returns the type of the overload whose names it passes, and decodes the result with that overload'sresult. Overloads with the same argument names (pick(value integer)andpick(value text)) return the union of their types, and PostgREST can't choose between them at runtime either. An overload without arguments is typedRecord<PropertyKey, never>, so it never matches a call that passes one. -
Nullable function results. Postgres can't promise that a function returns a value: a
strictfunction returnsnullfor anullargument, a SQL function returnsnullwhen its query finds no row, and an aggregate in areturns tablecolumn isnullover no rows. So a scalar result, each element of asetofscalar, a single table row and eachreturns tablecolumn are typed| null. Rows ofreturns setofa table are not, and neither isvoidorJson, which already includesnull. When you know a result is never null, say so in the config:better-supabase.config.ts export default defineConfig({ functions: { open_ticket_count: { notNull: true }, customer_note_counts: { notNull: ["customer_id", "note_count"] }, }, });notNull: truecovers the whole result, and a list names thereturns tablecolumns (database names) that are never null.genfails on a function or column it can't find.You can also keep the promise next to the SQL.
genreads an@notNulltag from the function's comment, and@notNull(a, b)names the columns:comment on function public.customer_note_counts(uuid[]) is 'Notes per customer. @notNull(customer_id, note_count)';A config entry for the same function wins over its tag, and a tag that names a column the function doesn't return fails
genthe same way. Doctor's BS338 lists the config entries a tag could replace.A function that returns
jsonorjsonbtakes its result type from the config too, the waygen.jsondoes for a column.returns: { schema: "./invoice.ts#InvoiceTotal" }names a Standard Schema export: the result is typed from it and checked at runtime, as the@bsb returnscomment tag does.returns: { import: "./types.ts#InvoiceTotal" }imports a type, andreturns: { type: "{ total: number }" }writes one. The config wins over the tag.Postgres has no syntax for
not nullon areturns tablecolumn, and the catalog records none, sogencan't infer it from the function body. Two things do carry it: a function thatreturns setofa table gets that table's column nullability, and a column whose type is a domain declarednot nullis typed without| null:create domain public.customer_ref as uuid not null; create function public.customer_note_counts(customer_ids uuid[]) returns table (customer_id public.customer_ref, note_count bigint) ...When a
returns tablefunction still has a nullable column and neither a tag nor a config entry covers it,genprints a notice that names the function.notNull: []in the config keeps every column nullable and silences the notice. -
Nullable arguments. Every argument type includes
| null, because Postgres passesnullto any argument. This only widens what you may pass to$rpc; it never changes a result type. Astrictfunction returnsnullfor anullargument, which is why its result stays| null.
Documentation in the validators
The zod(), valibot(), jsonSchema() and standardSchema() generators carry what the
database says about a table into the schemas, so an OpenAPI document or an MCP
tool built from them describes each field:
- Each table schema gets a title from the table name (
customer_tagsbecomesCustomer tags, thenCustomer tags insertandCustomer tags update) and a description fromcomment on table. - Each field gets a description from
comment on column. A comment line that starts with@exampleadds an example: JSON when it parses (@example 42,@example "Acme B.V."), text otherwise. Examples the column's type rejects are left out. - Simple CHECK constraints become bounds the validators enforce. Comparisons
of a numeric column with a constant (
price >= 0,rating between 1 and 5) becomeminimum,maximumand their exclusive forms, and comparisons oflengthorchar_lengthwith a constant becomeminLengthandmaxLength. Terms joined byor, other functions and comparisons between columns are left out.
create table public.customers (
name text not null check (char_length(name) between 1 and 200)
-- ...
);
comment on table public.customers is 'Companies the organization sells to.';
comment on column public.customers.name is 'Trading name.
@example "Acme B.V."';export const customersInsert = z
.object({
name: z
.string()
.min(1)
.max(200)
.meta({ description: "Trading name.", examples: ["Acme B.V."] }),
// ...
})
.meta({
title: "Customers insert",
description: "Companies the organization sells to.",
});Valibot gets the same through v.title, v.description, v.examples,
v.minLength and v.minValue in a pipe, and the JSON Schema through
title, description, examples, minLength and minimum. The
standardSchema() output carries them in each field spec.
The generated metadata carries the comments too, so the API documents that
defineApi and createOpenApi render describe each table
and column without a validator. A table or column comment becomes
description in the metadata (without its @example lines), and a comment
line that starts with @deprecated sets deprecated: true. In the
document, the table's description goes on its schemas and its tag, each
column's on its property, and a deprecated table marks its schemas and
operations deprecated. A tag description set on the resource wins over the
table comment.
Examples stay in the validators; pass examples to defineApi to put rows
in the document.
Coming from supabase-to-zod
supabase-to-zod converts the database.types.ts file into zod 3 schemas
through ts-to-zod. The zod() generator writes zod 4 schemas from the
database catalog instead, so they carry the CHECK bounds, comments and codecs
above, and it keeps separate Row, Insert and Update schemas per table.
Replace the supabase-to-zod script with generators: [zod()] and import
<table>Row from generated.zod.ts.
Schemas for functions and blocks
The zod(), valibot(), jsonSchema() and standardSchema() generators
also write a schema for each database function's arguments and result, and
for the inputs of every installed entity block, next to the table schemas:
| Export | From |
|---|---|
<function>Args, <function>Result | each function: listTasksArgs, customerStatsResult |
<entity>Input, <entity>Change | a block entity's create and update inputs: taskInput |
<entity>ListFilter | a block entity's list options: taskListFilter |
Block schemas carry the names the config gives the entities, so with
work_item: "task" the file has taskInput with a taskId field. An
overloaded function gets no schema, because one schema can't pick a
signature. A composite column and a composite function result become a nested
object. A domain column uses the domain's base type, and a not null domain
or a VALUE IS NOT NULL check drops | null. A simple VALUE comparison
(VALUE >= 0) becomes the same bound a table CHECK does. geometry and
geography are json, because PostgREST returns GeoJSON. A returns table
function with no backing table gets a Result schema from its columns.
A type gen does not know stays unknown (it used to be guessed as
string), and gen prints one notice that names those columns. Map one in
gen.json, or name the column in standardSchema({ json }). text,
varchar, citext, ranges, inet, interval and the other types
PostgREST returns as text stay strings. Use them as action inputs or in forms.
What gen does not generate
Some payloads have no description in the catalog, so gen does not invent a
schema for them:
- Overloaded functions. One schema cannot pick a signature.
- Realtime broadcast and presence payloads. The app defines them.
- Edge Function inputs and outputs. Nothing in the database describes them.
- pgmq, cron and vault payloads. They are untyped
jsonb.
Form metadata
fieldMeta: true adds a fieldMeta export: for each writable table and
each input schema, a label, a required flag, the enum options and the
bounds of every field.
generators: [zod({ fieldMeta: true })],export const fieldMeta = {
customers: {
name: {
label: "Trading name",
required: true,
minLength: 1,
maxLength: 200,
},
status: {
label: "Status",
required: false,
options: ["active", "churned"],
},
},
} as const;The label is the column's comment when it is short, one line of at most 60 characters; otherwise it comes from the column name.
Search params for nuqs
nuqs() from better-supabase/generators/nuqs writes <output>.nuqs.ts, with
search-param parsers for a list of each table: a filter for every column
with a closed set of values, orderBy over the sortable columns,
direction, cursor and limit. Each set comes with a cache for Server
Components, a loader and a serializer for links. The file imports
nuqs/server, an optional peer the app installs.
import { defineConfig } from "better-supabase/config";
import { nuqs } from "better-supabase/generators/nuqs";
export default defineConfig({
gen: { generators: [nuqs({ tables: ["tasks", "customers"], limit: 50 })] },
});A Server Component reads the params through the cache, and a Client Component writes them with nuqs' own hooks:
import { tasksSearchParamsCache } from "@/lib/supabase/generated.nuqs";
export default async function TasksPage({ searchParams }: PageProps<"/tasks">) {
const { state, orderBy, direction, limit } =
await tasksSearchParamsCache.parse(searchParams);
// ...
}"use client";
import { useQueryStates } from "nuqs";
import { tasksSearchParams } from "@/lib/supabase/generated.nuqs";
export function TaskFilters() {
const [params, setParams] = useQueryStates(tasksSearchParams);
// ...
}| Option | What it does |
|---|---|
tables | The table keys to write parsers for; defaults to every table, block tables included |
limit | The default page size; defaults to 25 |
output | The file path; defaults to <output>.nuqs.ts |
Block tables appear under their final names, such as tasksSearchParams.
load<Name> parses a URL, a Request or searchParams, and
serialize<Name> writes the params into a link.
Tag functions
tags() from better-supabase/generators/tags writes <output>.tags.ts: one
defineTags call over the table keys, so tags.customers(org) is the cache
tag a read and an action share. A reader lists it in
bsb.tenant(org, permission, { tags: [tags.customers(org.id)] }), and an action
in tags: ({ tenant }) => [tags.customers(tenant)].
import { defineConfig } from "better-supabase/config";
import { tags } from "better-supabase/generators/tags";
export default defineConfig({ gen: { generators: [tags()] } });| Option | What it does |
|---|---|
tables | The table keys to write tags for; defaults to every table |
domains | Feature tags such as crm (camelCase) written next to the table tags |
output | The file path; defaults to <output>.tags.ts |
Standard Schema without a validation library
standardSchema() writes <output>.standard.ts: a schema per table for its
Row, Insert and Update shapes that needs no zod or valibot install. Each one
implements Standard Schema (~standard.validate)
and Standard JSON Schema (~standard.jsonSchema), so it works anywhere a
Standard Schema does: the validation extension,
validate(), form libraries, oRPC and MCP tool inputs.
import { defineConfig } from "better-supabase/config";
import { standardSchema } from "better-supabase/generators/standard-schema";
export default defineConfig({
gen: {
file: "src/lib/supabase/generated.ts",
generators: [
standardSchema({
json: { "customers.metadata": "./schemas.ts#metadata" },
}),
],
},
});import { type TableSchema, tableSchema } from "better-supabase";
export const customersInsert: TableSchema<InsertOf<"customers">> = tableSchema({
title: "Customers insert",
fields: {
name: { kind: "string", minLength: 1, maxLength: 200 },
status: {
kind: "enum",
values: ["lead", "active", "archived"],
optional: true,
},
metadata: {
kind: "json",
nullable: true,
optional: true,
schema: metadata,
},
},
});
export const validators = {
customers: { insert: customersInsert, update: customersUpdate },
};The checks match the zod() output: uuid, integer and ISO date formats,
enum values, CHECK bounds, null only on nullable columns, and Temporal
values on instant and plainDateTime codec columns. A present key never
accepts undefined, and unknown keys are dropped from the validated value.
json takes a Standard Schema per typed jsonb column; its issues keep their
path under the column, and its JSON Schema is used when it has one.
~standard.jsonSchema.input() and output() return the same JSON Schema the
jsonSchema() generator writes for that shape, for the draft-2020-12,
draft-07 and openapi-3.0 targets:
const schema = customersInsert["~standard"].jsonSchema.input({
target: "draft-07",
});Saving a snapshot
better-supabase gen --save-snapshot
better-supabase gen --save-snapshot --check
better-supabase gen --snapshot supabase/snapshot.jsongen --save-snapshot reads your database the way gen does and writes what
it found to supabase/snapshot.json instead of generating code. Commit the
file, set database.source.snapshot in the config, and CI and contributors
can run gen and doctor without a database.
| Option | Effect |
|---|---|
--out <file> | Where to write. Defaults to supabase/snapshot.json, or supabase/generator-metadata.json. |
--kind <kind> | snapshot (the default) or generator-metadata, postgrest-typegen's input on its own. |
--check | Writes nothing; exits 1 when the file no longer matches the database. |
--dry-run | Prints a diff of the file and writes nothing. |
--snapshot <file> reads a saved snapshot instead of the database, to
convert it with --kind, and --db-url-stdin and --project-ref work as
they do for gen. With --json, the envelope's data is
{ "tables", "files" }, plus upToDate for --check. It always reads the
full schema, without the introspection cache.
The snapshot stores postgrest-typegen's own metadata plus the extras
better-supabase reads (policies, indexes, triggers, buckets, realtime), and
follows
snapshot-v3.json.
Row counts are left out so the file stays stable; tables Postgres estimates
at 10,000 rows or more only get large: true, which the
unbounded-read lint rule reads.
The output is the same after supabase db reset and on every machine:
object ids come from names, and the arguments of each function keep their
declaration order. That matters for extension functions with unnamed
arguments, such as pgvector's distance functions and citext's casts, whose
argument order the catalog query alone does not fix. The snapshot leaves out
rpcFunctions, which postgrest-typegen derives from functions; the
generator resolves it again from the stable, ordered functions. A
GeneratorMetadata document passed to gen --metadata is treated the same
way, so rpcFunctions never names a schema gen doesn't generate.
From a GeneratorMetadata document
gen --metadata generates from the JSON document that
@supabase/postgrest-typegen defines (GeneratorMetadata, versioned by
GENERATOR_METADATA_VERSION), the same document
@supabase/typegen
pipes to out-of-process generators. Pass a file, or - to read stdin:
better-supabase gen --metadata - < metadata.json > src/lib/supabase/generated.tsIt follows the registry's contract for an out-of-process tool:
- stdout holds only the generated file. Notices, warnings and the oxfmt notice go to stderr.
- It exits 0 on success, 1 when generation fails (for example without
@supabase/postgrest-typegeninstalled), 2 on a usage error, and 65 (the code the registry maps toMetadataRejectedError, as for Dart'ssupabase_typegen) when it can't read the document, the document is not JSON, itsversionis not theGENERATOR_METADATA_VERSIONthis release reads, or the schema rejects it. The reason is on stderr. - It reads
better-supabase.config.tsfrom the working directory when there is one (casing,schemas,tables,codecs, generator options), and the defaults otherwise.
--only picks the file:
--only | Prints |
|---|---|
schema | The defineSchema module, with the metadata written into it instead of a separate generated.meta.js. It imports Database from databaseTypesOutput. |
types | database.types.ts, formatted when oxfmt is installed. |
zod | The zod() generator's file, with the options from the config when it lists zod(). |
valibot | The valibot() generator's file, likewise. |
json-schema | The jsonSchema() generator's document, likewise. |
standard-schema | The standardSchema() generator's file, likewise. |
--out <dir> writes the usual files (database.types.ts, the main module,
its metadata module and each configured generator's file) into one directory
instead, and --check compares them there. A generator with its own output
keeps that path. It leaves the read-set SQL module
and the files an earlier gen wrote alone.
The document carries no more than the Data API types need, so a few things
the database connection adds are missing. Relations, primary keys, enums,
single-column unique keys and single-column CHECK unions stay typed; unique
keys and checks get the names Postgres gives them by default
(<table>_<column>_key, <table>_<column>_check). Multi-column unique keys
and checks, foreign key actions, indexes, triggers, policies, grants, buckets
and the realtime publication are absent, and a notice on stderr says so. Run
gen against the database for the full model.
doctor --metadata reads the same document. Checks that need what it lacks
are skipped with an info finding, and the advisors and live checks are
skipped as for a saved snapshot.
As a @supabase/typegen language
The registry runs an out-of-process language in the project directory with
the sorted document on stdin. An externalLanguage entry for better-supabase
runs npx better-supabase gen --metadata -:
import { externalLanguage } from "./external.ts";
export const betterSupabase = externalLanguage(
"better-supabase",
[
{
name: "emit",
audience: "user",
kind: "choice",
choices: [
"schema",
"types",
"zod",
"valibot",
"json-schema",
"standard-schema",
],
default: "schema",
help: "The file to generate: the defineSchema module, database.types.ts or a validator file",
},
],
{
command: "npx",
args: (_metadata, options) => [
"--no-install",
"better-supabase",
"gen",
"--metadata",
"-",
"--only",
String(options.emit),
],
installHint:
"Install Node.js, then run `npm install -D better-supabase @supabase/postgrest-typegen` in the project.",
classify: (result) => {
if (
result.stderr.includes("could not determine executable to run") ||
result.stderr.includes(
'needs the "@supabase/postgrest-typegen" package',
)
) {
return {
kind: "not-installed",
tool: "the better-supabase package",
installHint:
"Run `npm install -D better-supabase @supabase/postgrest-typegen` in the project that should receive the types, then generate from that directory.",
};
}
if (result.exitCode === 65) return { kind: "metadata-rejected" };
return undefined;
},
},
);Once the entry is in the registry's languages, user options become flags
of supabase gen types, so supabase gen types --lang better-supabase --only zod
prints what better-supabase gen --metadata - --only zod prints for the same
database. The upstream registry doesn't ship this entry, so without it, pipe
the document to better-supabase gen --metadata - yourself.
Last updated on