/better-supabase:better-supabasefrom better-supabase
Generates typed repositories, Results, and codegen for Supabase. Handles schema migrations, RLS policies, grants, and type synchronization.
Ships in better-supabase. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
The data layer is betterSupabase = createSupabase(schema) in src/lib/supabase/index.ts.
schema comes from the generated module (config.output, usually
src/lib/supabase/generated.ts). Never edit generated files.
The better-supabase command ships in the better-supabase package, so
pnpm better-supabase <command> works once the package is installed. There
is no separate CLI package to add.
supabase/schemas/*.sql, then run
supabase db schema declarative sync -f <name>, or supabase migration new for data and role settings. The sync needs
[experimental.pgdelta] enabled = true in supabase/config.toml;
doctor reports BS316 when a project is still on the legacy migra engine.
database.sql.workflow in the config picks how the SQL modules reach a migration:
pg-delta (the default), migra (declarative schemas 1.0, supabase db diff) or migrations (no supabase/schemas: add and upgrade write
<stamp>_better_supabase_modules.sql, applied with supabase migration up).enable row level security, a policy per role and command the app uses, and an index on
every column a policy filters by. Write tenant checks as
organization_id in (select better_supabase.member_organization_ids()), which
Postgres runs once per statement, not has_organization_role(organization_id),
which runs once per row. List the table in expose in
better-supabase.config.ts and run pnpm better-supabase add grants:
new tables get no Data API grants on their own.supabase db reset (or supabase migration up).pnpm better-supabase gen, then fix the type errors it surfaces. It
also runs every other generator the config sets up (upgrade, spec emit, the seed client); set gen.tasks to change the
list. Put flags you would repeat in better-supabase.config.ts (with a
$ci block for CI) instead of on the command line.pnpm better-supabase doctor and fix every error it reports (RLS off,
missing policies, missing grants, unindexed foreign keys, drift).better-supabase gen --check, which
prints a diff of each stale file.Done when gen --check and doctor exit 0 and the project typechecks.
db from the request context (see below), never from a global client,
so RLS applies.Result.better-supabase-testing skill).Done when the call typechecks without casts, the error path returns the
DbError (not a thrown exception), and a test shows another tenant's rows
stay hidden.
pnpm better-supabase codemod <name> --dry-run for each codemod the
release lists (codemod without a name lists them), then without
--dry-run, and fix the lines it lists for review. codemod naming
applies the renames in api/naming.json.pnpm better-supabase upgrade, so the SQL modules get the
release's SQL and any forward steps land in a migration, then write a
migration from the changed files (under the migrations workflow it
writes that migration itself).pnpm better-supabase gen and commit the result. Since 0.3, a
composite foreign key such as (customer_id, organization_id) is named
after the remaining column (customer); set tables.<name>.relations in
the config to keep an old relation name.pnpm better-supabase skills install --check and reinstall the skills
when it reports them stale.pnpm better-supabase doctor. BS607 means node_modules, the
lockfile and the block SQL name different releases: run the install
command it prints, then upgrade --check.Temporal (see below).Done when gen --check, doctor and the typecheck pass.
db comes fromName the definition betterSupabase (in lib/supabase/index.ts) and every runtime instance bsb (lib/supabase/server.ts, lib/supabase/client.ts, or the Hono, oRPC or Edge Function entry).
const { db } = await bsb.context(), bsb.route(...), bsb.action(...)bsb.claims() in a 'use cache: private' function inside <Suspense>, pass the promise to <SessionProvider> and read it with useSession()/[organizationId]/...): bsb.context({ tenant: organizationId }), bsb.cached({ tenant }) inside a 'use cache: private' function that takes the tenant as an argument, and bsb.action({ input, tenant: (input) => input.organizationId }, fn). The tenant gets the resolver's membership checks. Client Components get the id as a prop and pass it to actions and to useLiveQuery(spec, { tenant }); the browser client only knows the claim's tenantbsb.durableCached(fn, { name, tables, life }). It runs as the caller under RLS, one entry per user, tenant and authorization version, and a write to one of tables expires it. Add share: "tenant" only for tables the authorization provider lists as shared. Never fill a cache with a service-role clientc.var.db after bsb.middleware()context.db after bsb.middleware()bsb.handler((request, { db }) => ...)res.locals.db; Fastify: request.locals.db; Koa: ctx.state.db; NestJS: @Ctx("db")event.locals.db; H3, Nitro and Nuxt: event.context.db; TanStack Start: the middleware context.dbbsb.locals(Astro).db; SolidStart: (await bsb.require()).dbbsb.contextClient(ctx.auth) sends the caller's token to PostgREST, Storage and Realtime, so RLS applies. bsb.admin().$client is the shared secret-key client, for work no user ownsbsb.db, or the hooks from createHooks<typeof bsb>()bsb.loader(fn) from createExpo, with bsb.currentUser(request, { rpc }) for the session, the live authorization version and the page data in one call. iOS and Android with PowerSync: syncWithAuth plus the native SessionProvider; the better-supabase-auth skill's references/native.md has bothBLOCK_CATALOG): references/blocks-and-presets.mdbotIdGuard and firewallRateLimit from better-supabase/vercel-security, verify a Passport caller with verifyPassport from better-supabase/vercel-passport, and pass the SDK module in for the domains block (vercelDomainProvider), signing keys (vercelKmsKeyProvider as keys) and attachments or drive files (vercelBlobStore as files). Postgres keeps deciding who may upload. See https://bettersupabase.com/docs/vercelnpx shadcn add @better-supabase/<item>.For who the caller is (sessions, claims, OAuth clients, agents, scopes), use
the better-supabase-auth skill.
blocks key is an instance. It installs the block named by the key, or
by block: labels: { block: "tags" } installs tags a second time. Rename
a block's nouns with names (tasks: { names: { work_item: "ticket" } }),
limit it to record types with on, and pick a dependency's instance with
uses. Never copy a block's table to get a second one.defineBlocks(blockConfig, { labels: tagsBlock }),
and bsb.record(<type>Record) from @/lib/supabase/records/<type> for a
record's timeline, actions and tags.bsb add <block>, follow its numbered checklist. Keys go in
.env.example; set them in .env.local. Fill in the provider stubs in
lib/supabase/providers.ts and spread them:
defineBlocks(blockConfig, { ...blocks, ...providers }). Doctor fails on a
missing env key (BS504) or an unwired required provider (BS505)..from("<block table>").insert() or another supabase-js write: that skips
the block's events, hooks and checks, and doctor warns BS351. Your own
columns on a block table go in the method's fields (add them with
alter table ... add column in your own schema file, or list the columns of
a table you create in its comment as @bsb fields a, b); they are written in the same
insert or update, so a not null column or a check across columns holds.access_token, client_secret)
next to field-encryption or credentials is BS352: set encrypted: true
under tables.<name>.columns, or move the secret to Vault.preset: { blocks, instances }); your
own blocks entry for the same key wins.supabase/schemas. A block
whose table your schema already creates runs over it: it adds only the
missing columns, names its policies and triggers there bsb_..., and
never recreates the table or revokes grants. There is no ownership: "adopt" any more (codemod 0.15 removes it). Don't edit block files: an
edited file fails upgrade until you move the change into your own file
or pass --force.tables.<name> entry over a table you already have adds the scope
column with a not valid not-null check: new rows need an owner, old rows
stay reachable only by the service role. Fill them with
pnpm better-supabase db backfill <table>.<column> --from <table.column> via <column>
(or --value), then run pnpm better-supabase doctor --yes to validate
the check. Doctor reports the rows as BS238. See
https://bettersupabase.com/docs/blocks/own-schemas.npx shadcn add @better-supabase/use-<block> writes hooks/use-<block>.ts, and the app
imports from @/hooks/use-<block>. Vue, Svelte and Solid call
useBlockController(create<Name>Controller, options) from
better-supabase/vue, /svelte or /solid. There is no
better-supabase/blocks/<block>/react entry.bsb.action({ input, requireTenant: true, authorize: (session, input) => can(session, "members.invite") }, (input, { db, tenant, session }) => ...).
requireTenant types tenant as a string; a refusal is a forbidden
ActionResult. bsb.route(handler, { requireTenant, authorize }) takes the same.const form = useActionForm(action, { onSuccess }) from
better-supabase/react, then <form {...form.formProps}>, form.pending
and form.fieldErrors.<field>. Fields survive a failed submit. Pass
resetOnSuccess: false for edit forms.const remove = useAction(action, { onError }),
remove.run(input), and remove.pendingInputs to mark the row in flight.createErrorMessages({ ...one entry per DbError kind }) from
better-supabase; a missing kind is a type error.await bsb.require({ authorize }) throws
forbidden() or unauthorized() (needs experimental.authInterrupts).
Under Cache Components, check the privately cached session and call
forbidden() instead, so the page stays prefetchable.tenantOf(session), on the server and in
the browser.const result = await db.customers.list({
select: ["id", "name"],
where: { status: "active", notes: { some: { kind: "call" } } },
include: { organization: { select: ["name"] } },
orderBy: { name: "asc" },
limit: 20,
});
if (!result.ok) return result; // DbError: kind, message, status, code
const customers = result.data;
Result, and database errors never throw. Use .orThrow() only where an exception is really wanted. The DbException it throws has the DbError as error and cause, plus its own kind, status, code, details, hint and table; kind-specific fields such as constraint stay on error.withBetterResult(db, toResult) from better-supabase/better-result returns a db whose repositories, $rpc and $list(list, query) return better-result values; toBetterResult(result, Result, mapError) converts one result, and defineBetterResultErrors(Result, { not_found: NotFound }, DbFailure) maps DbError kinds to TaggedError classes once. Annotate the expected Result<T, E> type instead of casting.casing: 'camel' means organizationId). Raw escape hatches ($client, and queryRaw on the better-supabase/postgres clients) use database names.create (one row or an array), update(id, patch), update({ where }), upsert, delete.page({ after: null, size: 25, orderBy }), then pass nextCursor back as after with the same orderBy and where. Use page numbers only when users jump to a page and need a total, and page({ offset, limit, count: 'exact' }) when the caller already has an offset; both return the rows and the total in one request.Result directly. Adapters turn errors into RFC 9457 Problem Details with the right status.bsb.forContext(job.context) for a job enqueued with { context: db.$context }, bsb.actingAs(userId, { tenant_id }) for a webhook or script. bsb.admin() bypasses RLS: use it only for work no user owns, never for a user's request.createQueue({ sql }) is Supabase Queues with Supabase Cron. Pass scheduler: vercelScheduler(Schedules, { bridge }) and serve vercelScheduleBridgeRoute on the bridge topic for Vercel Schedules, or sqlScheduler(sql, { mode: "drain" }) with blocks.queue.options.httpTick for Supabase Cron on Vercel Queues. Call the drain from schedules in vercel.json, not crons.db.$rpc()) or use postgres.transaction() on the server.$rpc types each returns table column and scalar result | null, because Postgres can't declare them not null. Don't cast them: add @notNull(a, b) to the function's comment (or gen.functions.<name>.notNull in the config), type the column with a not null domain, or return setof a table. gen prints a notice for each function still nullable. Arguments accept null too; that only widens the input.codecs: { timestamptz: 'instant' } in the config, timestamptz columns decode to Temporal.Instant and timestamp columns to Temporal.PlainDateTime, with microseconds. Without the codec they stay ISO strings.now options, job and webhook timestamps and bucket.sweep({ olderThan }) take Temporal values. Auth's now stays in epoch milliseconds.Temporal, add temporal-polyfill and pass its namespace: createSupabase(schema, { temporal: Temporal }) (block creators take the same temporal option). import "temporal-polyfill/global" once at startup also works. Without either, calls that need Temporal return an unexpected DbError that names both.$DATABASE_URL, $SUPABASE_DB_URL or database.source.dbUrl, or pipe it in with --db-url-stdin.--json follows CLI result v2 (https://unpkg.com/better-supabase/schemas/cli-result-v2.json). A run that succeeds, or reports findings, prints one document on stdout with status (success, or error for a report), data, warnings and next. A run that fails prints one error document line on stderr and nothing on stdout, with reason, message, type, next, data, userActionRequired and retryable. --yes and CI turn prompts off.--check drift, doctor errors), 2 a usage, config or environment problem, or an input the user has to give, 65 when gen --metadata rejects its document, 130 when the run is interrupted or a prompt is cancelled, 143 on SIGTERM. Each error reason is listed at https://bettersupabase.com/docs/cli/errors.reason, message, next, data, userActionRequired, retryable). Exit code 2 with input_required lists data.missing flags and their data.choices; run the next command with the value filled in. confirmation_required means the user must agree first (--force over their files, db seed --yes on a remote database): ask them, then run the next command with --yes --effects-digest <digest>. Never pass --effects-digest without asking. See https://bettersupabase.com/docs/cli/agent-mode.better-supabase mcp serves the same commands as MCP tools on stdio, read-only unless started with --allow-writes. A write tool first returns confirmation_required with a data.digest; ask the user, then call it again with the same arguments and effectsDigest set to the digest. See https://bettersupabase.com/docs/cli/mcp.declare module augmentation for types; everything comes from schema.DbError; return it, or map it with mapDbError.as Customer). If a type is wrong, the schema or the generated file is out of date: rerun gen.Temporal values to Date to compare them; use .equals() or Temporal.Instant.compare.See references/troubleshooting.md for each
DbError kind and the usual cause.
https://bettersupabase.com/docs. Every page is also served as Markdown at
https://bettersupabase.com/docs/<path>.md, and
https://bettersupabase.com/llms.txt lists them all.
For Supabase itself (Auth, Storage, RLS, Postgres performance), install
Supabase's skills next to these: npx skills add supabase/agent-skills.
references/block-extensions.md (opens in a new tab)references/blocks-and-presets.md (opens in a new tab)references/catalog-admin-and-compliance.md (opens in a new tab)references/catalog-ai.md (opens in a new tab)references/catalog-automation.md (opens in a new tab)references/catalog-billing-and-commerce.md (opens in a new tab)references/catalog-collaboration.md (opens in a new tab)references/catalog-content-and-files.md (opens in a new tab)references/catalog-crm-and-sales.md (opens in a new tab)references/catalog-database-primitives.md (opens in a new tab)references/catalog-developer-platform.md (opens in a new tab)references/catalog-growth-and-engagement.md (opens in a new tab)references/catalog-identity-and-access.md (opens in a new tab)references/catalog-index.md (opens in a new tab)references/catalog-notifications-and-messaging.md (opens in a new tab)references/catalog-people.md (opens in a new tab)references/catalog-scheduling.md (opens in a new tab)references/catalog-tenancy-and-accounts.md (opens in a new tab)references/catalog-work-management.md (opens in a new tab)references/e-invoicing-and-audit-files.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
supabase, codegen, typed-repositories, schema-migration, rls
npx claudepluginhub scaledockhq/better-supabase --plugin better-supabase4 skills in this plugin
/better-supabase-apiBuild HTTP APIs, Edge Functions and MCP servers on Supabase with better-supabase adapters. Use when adding a route, REST resource, oRPC procedure, Edge Function, MCP tool, AI chat route, knowledge or memory, stored agent, MCP connector, eve agent, Chat SDK bot, resumable stream, third-party credential, OAuth or agent scopes, webhook, background job, cleanup cron or idempotent endpoint./better-supabase-authRead and check the caller in better-supabase apps, including sessions, typed claims, user profiles, OAuth clients and agents acting for a user, scopes, ended sessions and authorization providers. Use when code reads auth, session or claims, when adding a custom access token hook, an OAuth or agent integration, sign-out, account deletion or role changes, or when better-supabase.config.ts has an authorization key./better-supabase-testingTest Supabase RLS policies, APIs and SQL against the local stack with better-supabase/testing, typed seeds and pgTAP. Use when writing or fixing tests that touch the database, policies, auth, OAuth or agent scopes, or Temporal time values.Other plugins' skills for the same job