Existing apps
Bring better-supabase into an app that already has its own tables, permissions, events and middleware, one module at a time.
An app with users in production can move to better-supabase without renaming
a table, changing a claim or logging anyone out. Each SQL module runs over your
existing tables, the access contract reads your permission model, and the
session cookie is the one @supabase/ssr already writes. You move one module
at a time and keep the rest of your code as it is.
Move the schema into files
SQL modules are written into supabase/schemas, and pg-delta (Declarative
Schemas 2.0) turns those files into migrations. When the app's schema lives
only in migrations or in the dashboard, export it first:
supabase db pull # a baseline migration, when supabase/migrations is empty
supabase db schema declarative generate --remoteThen check supabase/config.toml:
[experimental.pgdelta]
enabled = true
# only when your migrations call pg_net, for example database webhooks
[experimental.webhooks]
enabled = trueDeclare every extension your schema files use (create extension if not exists pgcrypto;), including those the local stack already ships, and remove
[db.migrations] schema_paths: pg-delta orders the files by dependency.
supabase db schema declarative sync should then report no changes, since
the files and the migration history describe the same database.
Keep migrations only
An app that writes every migration by hand can skip declarative schemas.
Set the workflow in the config, or run better-supabase init --workflow migrations:
export default defineConfig({
database: { sql: { workflow: "migrations" } },
blocks: ["memberships", "audit"],
});add and upgrade then write the modules into
supabase/migrations/<stamp>_better_supabase_modules.sql, and you apply it
with supabase migration up. Save a schema snapshot with
better-supabase gen --save-snapshot too, so the CLI sees the tables your
migrations create. An app still on declarative schemas 1.0 sets
workflow: "migra" to keep supabase db diff. See
Workflows.
Blocks run over the tables you have
You don't tell a block which tables are yours. The CLI reads your own schema
files (and migrations it didn't write) and the saved schema snapshot, and
decides per table: a block table you already have, at its default name or at
the name blocks.<name>.tables maps, keeps your definition, and the block
creates only the tables you don't have. So a block covers both the features
you already built (organizations, invitations, an audit log, an events
table) and the ones you don't have, and adding a table to your schema later
moves it over without a config change.
Over your table, the block skips its create table, adds only the columns
it needs that your table lacks with add column if not exists, casts its
writes to your column types where they may differ (an enum status, for
example), and never recreates your table or revokes your grants. Its
policies and triggers there are named bsb_<table>_<command> and
bsb_<name>, so they never replace one of yours.
Your own schemas explains the detection, the
names, the doctor findings and how block files are protected from edits.
blocks.<name>.ownership has two values. managed (the default) is the
behavior above. custom writes no SQL: you keep your own functions and
write the block's contract yourself (the functions your policies, other
blocks and the TypeScript APIs call). Use it for a function you can't
replace yet; doctor checks its signature against the contract (BS307), and
blocks view --sql <block> lists the signatures. The
Block SQL page shows
which blocks support custom.
An ownership: "adopt" from before 0.15 is rejected when the config loads.
Run better-supabase codemod 0.15 to remove it (it keeps tables and
columns), then better-supabase upgrade.
Map your names
The block never needs your tables to use its names. Map each logical table and
column to yours, and set a column to null when you don't have it:
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
permissions: {},
webhooks: {},
memberships: {
tables: { memberships: "public.organization_users" },
columns: {
memberships: {
tenant: "organization_id",
role: "role_id",
lastUsedAt: null,
},
},
},
organizations: {
tables: { organizations: "public.organizations" },
columns: { organizations: { createdBy: null, deletedAt: null } },
permissions: { update: "organization.settings.manage" },
callbacks: {
schema: "public",
functions: { after_organization_create: "seed_organization" },
},
options: { attributes: ["website", "logo_path", "default_currency"] },
},
outbox: {
tables: { events: "public.workflow_events" },
columns: {
events: {
type: "kind",
tenant: "organization_id",
key: "idempotency_key",
xid: null,
},
},
options: { defaultSource: "domain", blockSource: "domain" },
},
},
});permissions maps each block action to your permission keys, callbacks points
the block at functions you already have (seeding a new organization, writing a
contact profile), and options covers the rest: extra columns a function
accepts, token storage, slug rules, source values your check constraints
allow. An attribute your input leaves out keeps its column default. An unknown
table or column stops add and upgrade with the valid names, so a typo
fails before it reaches the database.
better-supabase add --adopt <block> --tables <schema.table>
proposes the tables and columns of an entry from the tables in your
database.
Give your own tables a scope
A table only your app has, such as projects, can get the same scope column,
row level security and policies as the block tables through a
tables.<name> entry. When your schema already creates the table, the entry
enriches it: it adds only the missing id, scope column (organization_id
or user_id), created_at and updated_at, the scope's policies and, per
tenant, the restrictive bsb_tenant_scope policy. The scope column gets a
not valid not-null check, so new rows must name an owner while existing
rows stay until you fill them with
better-supabase db backfill and validate the
check with better-supabase doctor --yes. See
App tables.
Choose an access model
Policies and block functions ask one question, better_supabase.can(scope, id, permission), and blocks.permissions.model decides
where the answer comes from.
| Your app has | Model |
|---|---|
| a role per membership and no permission tables | roles |
| roles, permissions and role-permission tables of its own | catalog |
| an authorization provider | provider |
| something else | custom |
With catalog, map your tables (roles, permissions, role_permissions,
per-tenant overrides) and the columns that disable a tenant or a user. A
helper such as organization_ids_with_permission(key) in your policies becomes
better_supabase.tenant_ids_with(key); both return the same set, so you can
switch policy by policy.
The active organization can stay where it is. Set blocks.permissions.activeTenant
to { profileColumn: "public.profiles.active_organization_id", key: "user_id" }
when you store it on the profile, or 'resolver' when the URL decides.
Keep your events and your receivers
An outbox over your events table writes to it. SQL modules emit in the same
transaction as the change, with the source in blockSource, and
emit_event calls without a source get defaultSource. Your existing
webhook receivers keep their signature format through a
signer: hmacSigner writes v1=<hex> over
timestamp.body under your header names, so you can move to Standard
Webhooks later, per destination.
Upgrade without breaking users
- SQL objects. Run
better-supabase upgradeafter each package update. It writes forward steps into a migration before the schema diff runs, andupgrade --checkfails CI when a module is behind. A renamed function or claim keeps a wrapper under the old name for at least one minor release, and doctor reports code that still uses it (BS309). - TypeScript.
better-supabase codemod <version>rewrites renamed imports and members; run it with--dry-runfirst. The stability page lists what a minor release may change. - Triggers.
track_updated_at()andaudit()warn when a table already has a trigger doing the same work; passreplace_trigger => trueto swap it in the same call.
Keep your supabase-js code
The repositories and your hand-written supabase-js calls use the same
session and the same Data API, so they work side by side. Move a query when
you touch it, not all at once; the supabase-js guide
maps each call. The raw client stays available as $client for anything the
repositories don't cover.
Keep your sessions
better-supabase reads and writes the sb-<project>-auth-token cookie in the
@supabase/ssr format, chunks included, so a user signed in before the
switch stays signed in after it, and a page still on @supabase/ssr reads the
session better-supabase wrote. See sessions.
Keep your middleware
bsb.proxy owns the session refresh; your other middleware goes in before,
and your route rules in protect:
import createMiddleware from "next-intl/middleware";
import type { NextRequest } from "next/server";
import { routing } from "@/i18n/routing";
import { bsb } from "@/lib/supabase/server";
const intl = createMiddleware(routing);
export const proxy = (request: NextRequest) =>
bsb.proxy(request, {
before: intl,
protect: (auth, req) => (auth.kind === "user" ? undefined : toLogin(req)),
});The refreshed cookie lands on next-intl's rewrite, and the locale header it sets reaches Server Components. The middleware page explains the order.
A suggested order
- Move the schema into
supabase/schemason pg-delta (or setdatabase.sql.workflow: "migrations"to keep migrations only), addbetter-supabase.config.tswithaccessin the model your app uses, and runbetter-supabase doctorto see what it finds. - Add
membershipsover your memberships table, mapped withtablesandcolumns, and swap one policy helper fortenant_ids_with. - Add the blocks for the features you already have (organizations,
invitations, audit, the events table), one per pull request. Each runs
over your table; run
better-supabase upgrade, read the comments it writes over your tables, and run your tests after each. - Add the blocks you don't have yet; they create their own tables.
- Add
tables.<name>entries for your own tables, runbetter-supabase db backfillfor each scope column doctor reports (BS238), thenbetter-supabase doctor --yes. - Move the session handling to an adapter and
bsb.proxy, then move queries to repositories as you touch them.
Last updated on
Overview
Guides for upgrading between better-supabase versions and for moving an existing app or library onto better-supabase.
From 0.53 to 0.54
What to check when upgrading from better-supabase 0.53 to 0.54. Doctor BS315 is an error, tests.authenticate_as looks users up through security definer helpers, withContext takes an async factory, and the tasks module gains set forms. Notes on db.$decode and single-row misses (PGRST116).