Changelog
Every better-supabase release with its changes, newest first, built from the CHANGELOG.md at the repository root.
0.94.0 (2026-11-30)
-
bsb.bootstrap()is nowbsb.currentUser(): it returns the signed-in user with their session state, authorization version and the app function's data. This is a breaking rename with no alias. The SQL wrappers (bootstrap_<rpc>) and the sessions block'sbootstrapoption keep their names for now.Old New bsb.bootstrap(options)bsb.currentUser(options)Bootstrap,UserBootstrapCurrentUser,SignedInCurrentUserBootstrapOptions,BootstrapCallOptionsCurrentUserOptions,CurrentUserCallOptionsBootstrapPermissions,expandBootstrapPermissions,compactBootstrapPermissionsCurrentUserPermissions,expandCurrentUserPermissions,compactCurrentUserPermissionsExpoBootstrapOptionsExpoCurrentUserOptions -
bsb.kept()is nowbsb.durableCached(), because the old name said nothing about what it does: it caches a read in a store that outlives requests and deploys. This is a breaking rename with no alias.Old New bsb.kept(fn, options)bsb.durableCached(fn, options)createNext({ kept: { store, onSkip } })createNext({ durableCache: { store, onSkip } })bsb.cached({ keep })bsb.cached({ durableReads })bsb.bootstrap({ kept })bsb.bootstrap({ durable })KeptStore,KeptLease,KEPT_LIMITSDurableCacheStore,DurableCacheLease,DURABLE_CACHE_LIMITSmemoryKeptStore,postgresKeptStore,postgresKeptLeasememoryDurableCacheStore,postgresDurableCacheStore,postgresDurableCacheLeaseKeptOptions,KeptFunction,KeepReadsOptionsDurableCachedOptions,DurableCachedFunction,DurableReadsOptionsstats kind "kept",keptHits"durable",durableHitsStore keys now start with
durable:, so entries written before the upgrade miss once and refill. -
With
selfDecideWhenTopOfChain, the expenses and leave blocks now let a requester who holds the approve permission and has no active manager up their reporting chain decide their own expense or leave request, even while other approvers can decide it too. The earlier rule, where the owner decides only when nobody else can, still applies, and a claim filed for someone else stays with the other approvers. The audit summary of a self-decided expense now reads "approved an expense as its owner or creator (self-decided)".
0.93.0 (2026-11-29)
-
eve 1.6 is the peer floor (
>=1.6.0 <2).@vercel/sandbox5 is in range (>=4.1.0 <6, so eve's bundled 4.x still fits) and@supabase/mcp-server-supabase0.21 is the catalog pin.sessionHistorynow returns eve's history parts by default: text, a user file and a completed tool call. Passinclude: "text"for the previous{ id, role, text }shape.capEvePartskeeps a composer at eve's 64-part limit.supabaseSubscriptionsrelays outbox row events to eve channel subscriptions, scoped to the subscriber's tenant. The sync also stores a failed turn's full error onusage.errorInfoand marks a session failed when it ends with an error.Dynamic schedules are imported from
eve/schedules.eve/experimental/schedulesstill exports them.
0.92.0 (2026-11-28)
-
The
projectscomposite now installs comments, files, tags, the timeline, relations, saved views and record teams, and it ships a glue module for project updates and initiatives.overviewreads one project for a page,cardsreads the counts on a task list, anddependenciesflags a blocking project whose target date is after the dependent's start.Tasks treats a project as a subject, with archive, restore and remove, milestones, a triage accept, decline, duplicate and snooze, and optional per-project identifiers (
WEB-130whenidentifiersis"project"). Iterations gain a cadence, a daily snapshot and a burnup. A notification can be snoozed, and a favorite can sit in a folder.An existing
projectsinstall gains the new parts and the glue module onupgrade. Runbetter-supabase upgradeand generate a migration. The tasks module moves from version 9 to 10, notifications from 11 to 12, and collections from 2 to 3. -
createNext()takesdebug.log, which writes onebsb.requestline per request once its response is done: the database calls, waves and time, and the slowest calls with their wave. Pages whose shell comes from the CDN never send the stats header to the browser, so this is how to see their database work in the platform's logs.debug.log: { slowMs: 200 }logs only the slow ones.
0.91.1 (2026-11-27)
- With
createNext()debug on, a query inside a"use cache"orunstable_cachescope no longer readsheaders()to find the request's stats recorder, so a remote cache entry is no longer marked as request-bound and its set no longer fails on every navigation. Queries there are not counted on the request; remote entries still count through their handed-off request id.
0.91.0 (2026-11-27)
- The approvals block's
approval_eligible_ids_inno longer runs the approver hooks once per pending request. A block'sdecidesrule runs once per subject type through the newoptions.deciderManyof leave, expenses and time entries, the set form ofoptions.decider. The provider'sisApproverruns once per distinct kind, tenant, requester and approvers, and only for requests nothing else lets the caller decide, or once in all through the newauthorization.functions.isApproverManytemplate. Approvals module version 8. - Breaking: a sessions bootstrap wrapper returns the authorization provider's permissions only for a call that names a tenant. A call without a tenant, such as a shell bootstrap, gets
permissions: nullinstead of one permission bitset per tenant the caller belongs to, which every cache miss paid for and most pages never read. Setpermissions: "all"on a bootstrap entry to keep the old behavior, or pass the page's tenant tobsb.bootstrap({ rpc, tenant }).permissions: falsestill leaves them out. Runbetter-supabase upgradeand generate a migration to rewrite the wrappers. - Breaking:
createProxyfrombetter-supabase/next/proxyno longer accepts the options onlycreateNextreads (support,postgres,kept,authorizer,authorization,versions,credentials,auditandapproval). The proxy never used them, and passing them pulled a SQL support store, a Postgres pool or the authorizer into the proxy bundle and its cold start. Remove them fromproxy.ts; a JavaScript caller that still passes one gets a warning.CreateProxyOptionsis the new options type.better-supabase/next/proxyalso exportsvercelRuntimeCache, so a proxy that shares its JWKS through the Vercel Runtime Cache no longer importsbetter-supabase/server. - Doctor BS405 measures the session cookie the way
@supabase/ssrwrites it: the claims are base64-encoded twice, once in the token and again in the cookie, so a payload above about 1,540 bytes needs a second cookie chunk withtokens-onlycookies. It reports that as its own warning (target:cookie), below the 2048-byte token limit, and the chunk count in the token warning uses the same formula. Before, it counted the claims once and reported one chunk for payloads that split into two. warm()opens the PostgREST connection with anOPTIONSrequest instead of aGETof/rest/v1/, which made PostgREST build the OpenAPI description of every exposed schema during a cold start.better-supabase/next/instrumentationaddswarmInBackground(bsb)forregister(), which starts the warm-up without making the request that started the instance wait for it.
0.90.0 (2026-11-27)
- The approvals block adds
approval_eligible_ids_in(tenants, outside), the pending requests the caller may decide in their member tenants (or the tenants passed) from one call, and withoutside => truethe ones outside them, tenantless requests included. Each permission is checked once throughtenant_ids_withinstead of onecancall per tenant and permission, and a block'sselfDecidesrule runs only for the caller's own requests (the expenses block answers them with oneexpense_self_decides_manycall). The function staysstableand writes no settings.approval_eligible_ids(tenant)calls it and keeps its signature. The approvals page recommends a two-part policy: the member tenants in one call, and the outside set only for rows outside them. With 60 tenants, 2,400 pending requests and a caller who owns 14, three scans in one statement went from 38 ms (filtered to one tenant) and 122 ms (every tenant) with one call per member tenant plus one without a tenant to 6.3 ms and 18 ms. Runbetter-supabase upgradeand generate a migration, then move the policy to the two-part shape. Approvals module version 7, no data step. - Security fix:
sameTenant.autono longer drops a generatedbsb_same_tenant_<column>check because an app trigger merely readsnew.<column>orold.<column>. Such a trigger silently removed the cross-tenant check on that foreign key. A trigger now turns the check off only when its function declares@bsb same-tenant-guard column=<column>. Doctor BS398 warns when a marked trigger never mentions the tenant column, and the new info finding BS733 lists every column a marker turns the check off for. Runbetter-supabase upgradeand generate a migration: columns that lost their check get it back. Add the marker to an app trigger that really compares the tenant if you want only one check (ADR 1268). A block's own trigger counts as a guard only with the marker; the drive block's node triggers carry it forparent_idanddrive_idand now also run when the tenant column changes, so they replace the generated checks on those columns. codemod namingno longer renames objects the library does not own. Its migration leaves alone a policy that your schema files create, such as the policies an authorization provider installs on block tables, and the unnamed check of a column that your files add to a block table, such asflags_kind_check. Before, renaming those made the next schema diff drop and recreate them. The codemod also rewrites calls to renamed SQL functions throughapi.<name>(in SQL and pgTAP files, and throughrpc/<name>paths in TypeScript.drive_transfer_ownershipno longer fails when the new owner can't own one of the drives, such as a second personal drive that the app's unique index or check over the owner column refuses. That drive stays with the old owner together with its drive grants and the top-role grants on its files, the other drives move, and the result lists it inkeptDriveIds(DriveTransfer.keptDriveIdsin the client). Any other unique or check violation still fails the transfer.driveOffboardingSinkpasses kept drives to a newonKeptoption, or logs a warning without it.
0.89.0 (2026-11-27)
-
shares.tablesandshares.functionsdeclare tables and functions the app shares per tenant, merged with the authorization provider's. An identical entry is a restated default. A disagreeing entry keeps the provider's settings, and doctor reports it as BS652. -
bsb.blockActiontakes a fourth argument that maps the data of a success, as the third argument ofbsb.actiondoes, so a block action can answer with{ id }and not the whole row.tagsstill receives the method's own data. The Next.js example moves 171 single-call actions tobsb.blockAction. -
genno longer turns a column type it does not know intostring. The column staysunknown, andgenprints one notice naming those columns. Composite types become nested objects in the zod, valibot, JSON Schema and Standard Schema output, a domain column uses its base type (includingnot nulland simpleVALUEchecks), andgeometryandgeographyvalidate as JSON. Areturns tablefunction gets a result schema from its columns.better-supabase/result-schemaexportsresultSchema(readSet)andspecResultSchema(meta, spec). Each returns a Standard Schema of the composed read, built from the columns the query selects. Unknown keys are dropped unless you passunknownKeys: "reject". A record binding stays unchecked untilregisterRpcReturnnames a schema for it. -
bsb.record(type).getandtimelineread a page's bindings in one request. Theread-setsblock now writesread_batch(calls jsonb), astable,security invokerfunction that runs up to 50stableJSON reads of the exposed schema as the caller and returns one result per call. The first read of every binding goes into oneread_batchcall, and each binding gets the same data orDbErrora direct call returns. Reads that write, and every read in a project without the function, run on their own as before.Run
better-supabase upgradeand generate a migration (supabase db diff) to add the function. Ask for every binding a page shows in onegetto get the saving. -
better-supabase codemod audit-statementrewrites a table's row audit trigger, or itsaudit()call, into static statement triggers that a schema diff keeps. Doctor BS651 reports a table that has both, which would write every change twice. -
chain_link()no longer throws when a row trigger runs without the statement-audit temp table. The owner check reads the table oid fromto_regclass, which returns null when the table is absent, instead of casting a name that Postgres resolves while planning the statement.The published config schema no longer lists
blocks.tasks.options.identifiers. The tasks options have no such property, and the default oftenantwas not one the config reads.The audit pgTAP file drops the statement probe it creates.
-
Doctor reads the schema of a schema-qualified
authorization.tablesname even whenschemasdoes not list it, so BS428 can check that table instead of reporting it missing. -
bsb.cached({ keep: { tables } })keeps a stable function call and adb.$many()batch as one entry, tagged with those tables. A volatile function still reaches the database, and a failed call is not stored. A function the schema does not name is kept when the tables are listed, so a block read andread_batchcan be kept too. Doctor rule BS609 also namesread_batchandbsb.record(type).getnext to the read set. -
Doctor BS204 checks every table in
schemas, including private schemas, and uses each table's own tenant column. A partial index and an index that contains the column further along each get their own message, with thecreate indexstatement to add.
0.88.0 (2026-11-26)
-
Behaviour change: the audit log now records a service write made for a member (
admin(context, { as }), thex-bsb-actorheader) withactor_kind = 'user', where it recordedservice;actor_rolekeepsservice_role. A filter or report that read such writes asserviceneedsactor_roleinstead. Runbetter-supabase upgradeand diff to pick up the audit functions.server.admin(context, { as, headers })sendsheaderson every request too, such as the request id and client address the audit log reads.bsb.bootstrap({ redirect, require: "user" })also redirects a caller without a user session, with?reason=signed_out(reasons.signedOut), and types the result asUserBootstrap, an active user session.requirewithoutredirectis a type error and throws.syncWithAuth(db, auth, { connectOptions })passesconnectOptionsto everyconnect, such as PowerSync's{ checkpointMode: "requests" }.createUploadConnector({ onUploaded })gets each batch's changes aftercomplete()succeeds, without the upload waiting for it.CrudEntryLikecarriespreviousValues.createClient,bindClientandcreateNativeClienttakeverifySession: { rpc, schema? }: a session that signs in or loads from storage is checked against the sessions block'sbootstrap_<rpc>wrapper (in the schemagenrecorded, elsebetter_supabase), and signed out locally when the server ended it and the same user is still signed in.
-
bsb.actiontakesevictSession. After a successful call the library drops every cached entry of the caller, asbsb.evictSession(userId)does.Before After await bsb.evictSession(auth.user.id)in the bodyevictSession: true -
bsb.actiontakestagsandrefresh. After a successful call the library expires the tagstags({ tenant, input, data })returns and, withrefresh: true, callsrefresh()fromnext/cache.Before After updateTag(tag)inside the action bodytags: ({ tenant }) => [tag(tenant)]refresh()in every callerrefresh: true -
Add
createNext({ actions: { envelope, guard, from } })for rules everybsb.actionshares,ActionDefaultsProviderinbetter-supabase/reactfor app-wideonSuccessandonErrorofuseAction,useOptimisticActionanduseActionForm, anddefineTags(tables)for tags a reader and an action declare once.Before After a wrapper around bsb.actionfor the envelopecreateNext(bs, { actions: { envelope } })the same toast in every useActioncall<ActionDefaultsProvider value={{ onError }}>a hand-written *-cache.tstag helperconst tags = defineTags(["customers"]);tags.customers(id) -
The authorization refresh joins its Realtime channel when the browser is idle (
requestIdleCallback, else a timer), keeps one channel per client, topic and event, and skips thecaller_authz_version()call on the first join whenSessionProvidergetsliveVersion(the bootstrap'sauthzVersion). A join after a reconnect still reads the version. PassliveVersionto save the call on every page load. -
bsb.cached({ keep: { name } })keeps the reads ofctx.dbin the kept store, per user and table, so a cold page or a new instance answers them without calling the database, and parallel renders share one fill.bsb.bootstrap({ rpc, kept: true })keeps the wrapper's answer the same way.db.$wrapExecutor(wrap)puts a wrapper around a client's executor, outside the plugins and the call counts. -
doctorchecks--outbefore it reads the project, so a path outside the project or a directory fails at once instead of after the run. It logs the time of each phase, prints the times under the text report and lists them asphasesin the JSON report (doctor-report-v1.json). A text report of 20 findings or more starts with one line per rule and its count. BS609 prints the read set that replaces the parallel reads it found, withsas the builder and one key per table. -
Add
bsb.expireTags(tags), which expires tags in Next's cache (updateTagin a Server Action,revalidateTagin a Route Handler) and in thebsb.kept()store, and resolves once the store has them. Doctor gains BS648 (updateTagorrevalidateTagbesidebsb.kept) and BS649 (refresh()that expires nothing besidebsb.kept), andbetter-supabase codemod expire-tagslists the calls to change. -
Add the
better-supabase/generators/tagsgenerator, which writes<output>.tags.tswith adefineTagscall over the schema's tables.Before After defineTags(["customers", "invoices"])by handgen: { generators: [tags()] }andimport { tags } -
Reads are
get*everywhere (ADR 1250). The functions that read a source lose theirloadandreadverb, the record bindingloadmember isget, andbetter-supabase codemod namingrenames the functions in your app.Old New loadConfig,loadProject,loadSnapshotgetConfig,getProject,getSnapshotloadEnv,loadJsonPathgetEnv,getJsonPathloadBindings,loadMyWork,loadTimelinegetBindings,getMyWork,getTimelinereadCatalog,readSecurityCataloggetCatalog,getSecurityCatalogreadDesignFilegetDesignFilereadPolicies,readGrants,readRulePoliciesgetPolicies,getGrants,getRulePoliciesreadArgSource,readArgSqlTypegetArgSource,getArgSqlTypereadStatus,readBitstringStatusgetStatus,getBitstringStatusreadC2paManifestgetC2paManifestbsb.record(...).load(id),recordListServer.loadbsb.record(...).get(id),recordListServer.getrecord binding loadgetSchemaMeta.tableLoaders,SchemaMeta.loadFunctionsSchemaMeta.tableGetters,SchemaMeta.getFunctionsgenerated load<Name>SearchParamsget<Name>SearchParams -
Request stats gain
keptHits, the kept entries that served a read without a fill, per phase. Thebsb.actionlog line prints it askeptHits=render:4. -
createProxy({ auth, env, jwks, debug })runs without the app definition, soproxy.tsno longer imports the schema or the blocks.genwritesproxy-permissions.generated.ts(permission key to bit index) whengen.permissionCatalogis on, sopermissionsOfreads the token bitset without the catalog. A new doctor rule, BS650, reads the proxy's file trace from the lastnext buildand reports above 400 KB. The oldcreateProxy(betterSupabase, options)form keeps working. -
SQL functions use the data verbs (ADR 1251). The module functions named with
save,addandremoveareupsert,createanddelete, and two reads areget. The next schema diff drops each old function and creates the new one with its grants, so runbetter-supabase codemod namingon your own SQL and apply the migration together.better-supabase doctorreports calls to an old name, andcodemod namingrewritesbetter_supabase.<old>in app SQL.Old New better_supabase.save_accounting_accountbetter_supabase.upsert_accounting_accountbetter_supabase.save_accounting_budgetbetter_supabase.upsert_accounting_budgetbetter_supabase.save_accounting_dimensionbetter_supabase.upsert_accounting_dimensionbetter_supabase.save_accounting_dimension_valuebetter_supabase.upsert_accounting_dimension_valuebetter_supabase.save_accounting_entrybetter_supabase.upsert_accounting_entrybetter_supabase.save_accounting_journalbetter_supabase.upsert_accounting_journalbetter_supabase.save_accounting_opening_balancesbetter_supabase.upsert_accounting_opening_balancesbetter_supabase.save_activity_notesbetter_supabase.upsert_activity_notesbetter_supabase.save_activity_transcriptbetter_supabase.upsert_activity_transcriptbetter_supabase.save_advisorybetter_supabase.upsert_advisorybetter_supabase.save_advisory_productbetter_supabase.upsert_advisory_productbetter_supabase.save_vex_statementbetter_supabase.upsert_vex_statementbetter_supabase.save_vulnerabilitybetter_supabase.upsert_vulnerabilitybetter_supabase.save_agentbetter_supabase.upsert_agentbetter_supabase.add_ai_chat_participantbetter_supabase.create_ai_chat_participantbetter_supabase.add_ai_chat_partybetter_supabase.create_ai_chat_partybetter_supabase.load_ai_harness_sessionbetter_supabase.get_ai_harness_sessionbetter_supabase.remove_ai_chat_participantbetter_supabase.delete_ai_chat_participantbetter_supabase.remove_ai_chat_partybetter_supabase.delete_ai_chat_partybetter_supabase.save_ai_assistant_messagebetter_supabase.upsert_ai_assistant_messagebetter_supabase.save_ai_harness_sessionbetter_supabase.upsert_ai_harness_sessionbetter_supabase.save_ai_projectbetter_supabase.upsert_ai_projectbetter_supabase.add_eval_itemsbetter_supabase.create_eval_itemsbetter_supabase.add_eval_items_from_feedbackbetter_supabase.create_eval_items_from_feedbackbetter_supabase.save_ai_batch_itemsbetter_supabase.upsert_ai_batch_itemsbetter_supabase.save_ai_provider_keybetter_supabase.upsert_ai_provider_keybetter_supabase.save_ai_taskbetter_supabase.upsert_ai_taskbetter_supabase.save_announcementbetter_supabase.upsert_announcementbetter_supabase.remove_approval_policybetter_supabase.delete_approval_policybetter_supabase.save_approval_policybetter_supabase.upsert_approval_policybetter_supabase.remove_assignment_queuebetter_supabase.delete_assignment_queuebetter_supabase.save_assignment_queuebetter_supabase.upsert_assignment_queuebetter_supabase.remove_rulebetter_supabase.delete_rulebetter_supabase.save_rulebetter_supabase.upsert_rulebetter_supabase.save_bank_accountbetter_supabase.upsert_bank_accountbetter_supabase.save_bank_rulebetter_supabase.upsert_bank_rulebetter_supabase.add_booking_exceptionbetter_supabase.create_booking_exceptionbetter_supabase.save_booking_resourcebetter_supabase.upsert_booking_resourcebetter_supabase.save_booking_servicebetter_supabase.upsert_booking_servicebetter_supabase.remove_calendar_attendeebetter_supabase.delete_calendar_attendeebetter_supabase.remove_calendar_grantbetter_supabase.delete_calendar_grantbetter_supabase.save_calendar_eventbetter_supabase.upsert_calendar_eventbetter_supabase.add_care_plan_actionbetter_supabase.create_care_plan_actionbetter_supabase.add_care_plan_goalbetter_supabase.create_care_plan_goalbetter_supabase.add_care_plan_problembetter_supabase.create_care_plan_problembetter_supabase.remove_case_actionbetter_supabase.delete_case_actionbetter_supabase.save_case_kindbetter_supabase.upsert_case_kindbetter_supabase.add_product_mediabetter_supabase.create_product_mediabetter_supabase.remove_product_mediabetter_supabase.delete_product_mediabetter_supabase.save_catalog_channelbetter_supabase.upsert_catalog_channelbetter_supabase.save_categorybetter_supabase.upsert_categorybetter_supabase.save_collectionbetter_supabase.upsert_collectionbetter_supabase.save_discount_groupbetter_supabase.upsert_discount_groupbetter_supabase.save_discount_rulebetter_supabase.upsert_discount_rulebetter_supabase.save_price_listbetter_supabase.upsert_price_listbetter_supabase.save_productbetter_supabase.upsert_productbetter_supabase.save_product_identifierbetter_supabase.upsert_product_identifierbetter_supabase.save_product_optionbetter_supabase.upsert_product_optionbetter_supabase.save_product_relationbetter_supabase.upsert_product_relationbetter_supabase.save_supplier_itembetter_supabase.upsert_supplier_itembetter_supabase.save_variantbetter_supabase.upsert_variantbetter_supabase.save_care_rulebetter_supabase.upsert_care_rulebetter_supabase.add_collection_entriesbetter_supabase.create_collection_entriesbetter_supabase.remove_collection_entriesbetter_supabase.delete_collection_entriesbetter_supabase.remove_saved_itembetter_supabase.delete_saved_itembetter_supabase.save_for_laterbetter_supabase.upsert_for_laterbetter_supabase.save_commission_planbetter_supabase.upsert_commission_planbetter_supabase.add_control_evidencebetter_supabase.create_control_evidencebetter_supabase.remove_control_evidencebetter_supabase.delete_control_evidencebetter_supabase.save_compliance_policybetter_supabase.upsert_compliance_policybetter_supabase.save_controlbetter_supabase.upsert_controlbetter_supabase.save_control_frameworkbetter_supabase.upsert_control_frameworkbetter_supabase.save_evidence_taskbetter_supabase.upsert_evidence_taskbetter_supabase.save_connector_serverbetter_supabase.upsert_connector_serverbetter_supabase.save_connector_sessionbetter_supabase.upsert_connector_sessionbetter_supabase.save_consent_purposebetter_supabase.upsert_consent_purposebetter_supabase.add_person_identitybetter_supabase.create_person_identitybetter_supabase.remove_company_personbetter_supabase.delete_company_personbetter_supabase.remove_person_identitybetter_supabase.delete_person_identitybetter_supabase.save_companybetter_supabase.upsert_companybetter_supabase.save_payment_termbetter_supabase.upsert_payment_termbetter_supabase.save_personbetter_supabase.upsert_personbetter_supabase.save_contract_obligationbetter_supabase.upsert_contract_obligationbetter_supabase.save_coursebetter_supabase.upsert_coursebetter_supabase.save_course_lessonbetter_supabase.upsert_course_lessonbetter_supabase.save_course_modulebetter_supabase.upsert_course_modulebetter_supabase.read_field_valuesbetter_supabase.get_field_valuesbetter_supabase.save_field_definitionbetter_supabase.upsert_field_definitionbetter_supabase.remove_retention_policybetter_supabase.delete_retention_policybetter_supabase.save_rule_versionbetter_supabase.upsert_rule_versionbetter_supabase.remove_work_order_partbetter_supabase.delete_work_order_partbetter_supabase.save_document_templatebetter_supabase.upsert_document_templatebetter_supabase.save_document_text_blockbetter_supabase.upsert_document_text_blockbetter_supabase.save_document_versionbetter_supabase.upsert_document_versionbetter_supabase.add_hostnamebetter_supabase.create_hostnamebetter_supabase.remove_hostnamebetter_supabase.delete_hostnamebetter_supabase.save_donation_fundbetter_supabase.upsert_donation_fundbetter_supabase.add_employee_contractbetter_supabase.create_employee_contractbetter_supabase.save_employee_private_detailsbetter_supabase.upsert_employee_private_detailsbetter_supabase.save_enrollment_programbetter_supabase.upsert_enrollment_programbetter_supabase.add_expense_linebetter_supabase.create_expense_linebetter_supabase.remove_expense_linebetter_supabase.delete_expense_linebetter_supabase.save_expense_categorybetter_supabase.upsert_expense_categorybetter_supabase.save_flagbetter_supabase.upsert_flagbetter_supabase.save_flag_segmentbetter_supabase.upsert_flag_segmentbetter_supabase.save_funding_awardbetter_supabase.upsert_funding_awardbetter_supabase.save_funding_productbetter_supabase.upsert_funding_productbetter_supabase.save_goalbetter_supabase.upsert_goalbetter_supabase.save_jobbetter_supabase.upsert_jobbetter_supabase.save_inbox_draftbetter_supabase.upsert_inbox_draftbetter_supabase.add_incident_postmortem_actionbetter_supabase.create_incident_postmortem_actionbetter_supabase.remove_incident_postmortem_actionbetter_supabase.delete_incident_postmortem_actionbetter_supabase.save_incident_postmortembetter_supabase.upsert_incident_postmortembetter_supabase.save_incident_regulatory_profilebetter_supabase.upsert_incident_regulatory_profilebetter_supabase.save_status_componentbetter_supabase.upsert_status_componentbetter_supabase.save_status_pagebetter_supabase.upsert_status_pagebetter_supabase.add_inspection_findingbetter_supabase.create_inspection_findingbetter_supabase.save_inspection_checklistbetter_supabase.upsert_inspection_checklistbetter_supabase.save_inspection_programbetter_supabase.upsert_inspection_programbetter_supabase.save_binbetter_supabase.upsert_binbetter_supabase.save_locationbetter_supabase.upsert_locationbetter_supabase.save_lotbetter_supabase.upsert_lotbetter_supabase.save_purchase_orderbetter_supabase.upsert_purchase_orderbetter_supabase.add_invoice_chargebetter_supabase.create_invoice_chargebetter_supabase.remove_invoice_chargebetter_supabase.delete_invoice_chargebetter_supabase.save_leave_typebetter_supabase.upsert_leave_typebetter_supabase.save_lims_methodbetter_supabase.upsert_lims_methodbetter_supabase.save_bombetter_supabase.upsert_bombetter_supabase.save_work_centerbetter_supabase.upsert_work_centerbetter_supabase.save_medicationbetter_supabase.upsert_medicationbetter_supabase.add_meeting_action_itembetter_supabase.create_meeting_action_itembetter_supabase.remove_meeting_attendeebetter_supabase.delete_meeting_attendeebetter_supabase.save_meeting_agenda_itembetter_supabase.upsert_meeting_agenda_itembetter_supabase.add_member_rolebetter_supabase.create_member_rolebetter_supabase.remove_member_rolebetter_supabase.delete_member_rolebetter_supabase.add_conversation_membersbetter_supabase.create_conversation_membersbetter_supabase.remove_conversation_memberbetter_supabase.delete_conversation_memberbetter_supabase.save_thread_summarybetter_supabase.upsert_thread_summarybetter_supabase.save_observation_definitionbetter_supabase.upsert_observation_definitionbetter_supabase.save_option_setbetter_supabase.upsert_option_setbetter_supabase.save_option_set_itembetter_supabase.upsert_option_set_itembetter_supabase.save_kitchen_stationbetter_supabase.upsert_kitchen_stationbetter_supabase.save_shipping_ratebetter_supabase.upsert_shipping_ratebetter_supabase.remove_memberbetter_supabase.delete_memberbetter_supabase.save_pipelinebetter_supabase.upsert_pipelinebetter_supabase.save_pipeline_stagebetter_supabase.upsert_pipeline_stagebetter_supabase.save_post_boardbetter_supabase.upsert_post_boardbetter_supabase.save_promotionbetter_supabase.upsert_promotionbetter_supabase.add_qualification_requirementbetter_supabase.create_qualification_requirementbetter_supabase.remove_qualification_requirementbetter_supabase.delete_qualification_requirementbetter_supabase.save_qualification_typebetter_supabase.upsert_qualification_typebetter_supabase.save_custom_emojibetter_supabase.upsert_custom_emojibetter_supabase.save_reminderbetter_supabase.upsert_reminderbetter_supabase.save_risk_matrixbetter_supabase.upsert_risk_matrixbetter_supabase.save_viewbetter_supabase.upsert_viewbetter_supabase.save_score_modelbetter_supabase.upsert_score_modelbetter_supabase.remove_segmentbetter_supabase.delete_segmentbetter_supabase.save_segmentbetter_supabase.upsert_segmentbetter_supabase.save_sequencebetter_supabase.upsert_sequencebetter_supabase.save_shiftbetter_supabase.upsert_shiftbetter_supabase.save_shift_templatebetter_supabase.upsert_shift_templatebetter_supabase.save_intrastat_linebetter_supabase.upsert_intrastat_linebetter_supabase.add_signing_keybetter_supabase.create_signing_keybetter_supabase.save_sla_policybetter_supabase.upsert_sla_policybetter_supabase.add_organization_domainbetter_supabase.create_organization_domainbetter_supabase.remove_organization_domainbetter_supabase.delete_organization_domainbetter_supabase.add_subject_memberbetter_supabase.create_subject_memberbetter_supabase.save_iterationbetter_supabase.upsert_iterationbetter_supabase.save_projectbetter_supabase.upsert_projectbetter_supabase.save_task_checklist_itembetter_supabase.upsert_task_checklist_itembetter_supabase.save_task_material_linebetter_supabase.upsert_task_material_linebetter_supabase.save_task_specification_linebetter_supabase.upsert_task_specification_linebetter_supabase.save_tax_codebetter_supabase.upsert_tax_codebetter_supabase.save_tax_ratebetter_supabase.upsert_tax_ratebetter_supabase.add_team_memberbetter_supabase.create_team_memberbetter_supabase.remove_team_memberbetter_supabase.delete_team_memberbetter_supabase.remove_templatebetter_supabase.delete_templatebetter_supabase.remove_template_schedulebetter_supabase.delete_template_schedulebetter_supabase.save_templatebetter_supabase.upsert_templatebetter_supabase.save_template_draftbetter_supabase.upsert_template_draftbetter_supabase.save_template_schedulebetter_supabase.upsert_template_schedulebetter_supabase.remove_usage_quotabetter_supabase.delete_usage_quotabetter_supabase.remove_marketplace_installationbetter_supabase.delete_marketplace_installationbetter_supabase.save_bin_slotbetter_supabase.upsert_bin_slotbetter_supabase.save_putaway_rulebetter_supabase.upsert_putaway_rulebetter_supabase.save_variant_sizebetter_supabase.upsert_variant_sizebetter_supabase.remove_workflow_alertbetter_supabase.delete_workflow_alertbetter_supabase.remove_workflow_credentialbetter_supabase.delete_workflow_credentialbetter_supabase.remove_workflow_definitionbetter_supabase.delete_workflow_definitionbetter_supabase.remove_workflow_triggerbetter_supabase.delete_workflow_triggerbetter_supabase.save_workflow_alertbetter_supabase.upsert_workflow_alertbetter_supabase.save_workflow_credentialbetter_supabase.upsert_workflow_credentialbetter_supabase.save_workflow_definitionbetter_supabase.upsert_workflow_definitionbetter_supabase.save_workflow_draftbetter_supabase.upsert_workflow_draftbetter_supabase.save_workflow_triggerbetter_supabase.upsert_workflow_triggerbetter_supabase.remove_workflow_schedulebetter_supabase.delete_workflow_schedule -
Request stats now count services that call
betterSupabase.connect()themselves:connect(supabase, { claims }),connect({ executor: postgresExecutor(sql), storage })and the clientcontextFromSession()returns find the current request's recorder, so one page'scallsmatchespg_stat_statements. Stats gaindecodes(session cookie parses) next toverifications, andphaseswith calls per phase.bsb.phase(name, run)marks a wrapper's calls asauthorization,writeor any phase, and thebsb.actionlog line ends with the phase counts anddecodes.bsb.debugRoute()answers 404 with a JSONreasonwhen debug is off or?id=is missing. -
Add the
domainsoption to thetags()generator, so feature tags such ascrmare declared once next to the table tags.Before After export const CRM_TAG = tagFor("crm")tags({ domains: ["crm"] }),tags.crm() -
Add
gate: trueto the options ofbsb.tenant(),bsb.activeTenant()andbsb.auth(), and addbsb.shared(ref, permission, read). A gated scope returns before the permission check settles and itsdbsettles each read after it, so a cold call costs one round trip.bsb.sharedchecks the caller outside the cache, then returns a"use cache"read shared by every member of the tenant.Before After scope returned after the check bsb.tenant(ref, permission, { gate: true })a tenant read cached once per user bsb.shared(ref, permission, (t) => readOf(t.id)) -
Add
bsb.auth(),bsb.tenant(ref, permission?, options?)andbsb.activeTenant()tocreateNextfor cached reads. They resolve the tenant through the newtenantsoption, check the caller, and end the render withunauthorized(),notFound()orforbidden()when the caller is refused. Add.orNull()and.or(fallback)to every read result: anot_founderror becomesnullor the fallback, other errors throw.Before After a nullladder aroundbsb.cached()await bsb.tenant(org, permission, options)result.orThrow()plus anullcheckresult.orNull()bsb.tenant()(root param, unchanged)bsb.tenant()orbsb.activeTenant() -
Move the resource routes and the sign-in flows off
createNextonto their own subpaths, so an app that does not import them does not ship them.Before After bsb.resources(map)createResources(bsb)(map)frombetter-supabase/next/resourcesbsb.signInWithPassword(input)createAuthFlows(bsb).signInWithPassword(input)frombetter-supabase/next/sign-inbsb.verifyOtp,signInWithOtp,signUp,resend,resetPasswordForEmail,signInWithOAuth,exchangeCodeForSession,verifyMfa,signOutthe same names on createAuthFlows(bsb) -
doctormatches a provider call the way Postgres stores it. BS428 and the table share check readpg_policies.qual, where a key literal carries a cast ('tasks.read'::text), the function may lose its schema or be quoted, and a key list isARRAY['a'::text, 'b'::text]or'{a,b}'::text[]. All of those now count as the keys the policy checks. BS430 already read the function body as a parsed tree and handled casts, and BS429 reads no key literals.
0.87.0 (2026-11-25)
reveal_audit_entryandreveal_audit_entrieslet platform staff reveal restricted audit details only withpermissions.revealPlatform, which falls back to therevealkey on the platform, instead of the read-all key. Platform staff who only read every tenant's log no longer see IP addresses, user agents and row snapshots. SetrevealPlatformto your platform reveal key and runbetter-supabase upgrade.- A restore (
restore_data_row, thedata_lifecycle_rowimport entity) no longer writes the tables that decide access, billing, usage, keys or platform state, such as memberships, permission overrides, usage quotas, billing subscriptions and support sessions, anddata_restore_tables()leaves them out.blocks.data-lifecycle.options.restoreExcludelists tables of your own to leave out as well. The member who started the import run needspermissions.restore(organization.deleteby default), so an admin with only the import key can't restore. Runbetter-supabase upgradeto regenerate the data-lifecycle module. Upgrade note: a restore started by a member without the restore key (organization.deleteunless you setpermissions.restore) now fails every row. - The invoices, quotes and deals blocks take
options.lineDiscountRatesfor a line table whose discount column keeps basis points whilelineRates: "percent"covers its tax rate. Before,lineRates: "percent"divided every discount by 100 on write, so such a table stored discounts 100 times too small. Set it and runbetter-supabase upgrade. send_notificationacceptsactionsonly from the service role and refuses them from a signed-in sender withNOTIFICATION_ACTIONS_FORBIDDEN. A button runs its operation for whoever presses it, so a member could otherwise send a colleague a one-click button that approves or pays on their behalf. Send notifications with actions from your server, and runbetter-supabase upgradeto regenerate the notifications module. Upgrade note: a sender that adds actions on the user's token now fails.- The banking block records
payment_batch.created,payment_batch.postedandpayment_batch.cancelled, each with an audit entry, so every payout batch leaves a trail of who created, posted or cancelled it. Runbetter-supabase upgradeto regenerate the banking module. - Creating, posting and cancelling a payment batch now checks the banking block's
managekey instead ofreconcile, so a role that only reconciles bank transactions can no longer pay out supplier bills. Setpermissions.createBatch,permissions.postBatchandpermissions.cancelBatchto grant each operation to a key of your own, such as a finance role's. Runbetter-supabase upgradeto regenerate the banking module, and give the batch key to the roles that pay bills. Upgrade note: roles that hold only the reconcile key can no longer create, post or cancel payment batches. rotate_api_keyrefuses a personal key (one with a user) unless the caller is that user or the service role, withAPI_KEY_FORBIDDEN. Before, a holder ofapi_keys.managecould rotate a colleague's key and receive a secret that acts as that colleague. Revoking stays open to key managers. Runbetter-supabase upgradeto regenerate the api-keys module. Upgrade note: admins can no longer rotate another member's personal key; offer revoke for those keys.- Without
permissions.revealPlatform, the audit block no longer lets platform staff reveal restricted details at all; only the service role and tenant members with the reveal key do. Upgrade note: setrevealPlatformto a platform key and grant it to the staff who need it. Runbetter-supabase upgrade. read_field_valuesunderreadAccess: "record"no longer returns values of a record type that declares no read permission to any signed-in caller: such a type keeps thecustom_fields.readtenant key. Runbetter-supabase upgradeto regenerate the custom-fields module.- The drive block takes an optional
permissions.deletekey. When it is set,delete(id)(drive_delete, which skips the bin) andpurge(binId)also need that tenant key next to the share role, so an app whose share role is its editing role can keep hard deletes for the members that hold the key. Runbetter-supabase upgradeafter setting it. create_employeeandupdate_employeesrefuse to set or change an employee'suserIdunless the caller also holds the employees block'sreadSensitiveandcontractsReadkeys (EMPLOYEE_LINK_FORBIDDEN). Before,employees.writealone could link a colleague's record to the caller's own account and open that colleague's private details and contracts. Runbetter-supabase upgradeto regenerate the employees module. Upgrade note: an HR role without the sensitive read keys can no longer create an employee with auserId; an app that lets clients update its own employees table's user column directly is not covered by this check.- An accounting account or journal import item that names a
parentId,defaultAccountId,contraAccountIdorbankAccountIdoutside the run's organization now fails withIMPORT_ITEM_INVALIDinstead of being written without that link. Runbetter-supabase upgradeto regenerate the accounting module. - Import targets accept an id only when it belongs to the run's organization: accounting entries, opening balances and accounts look up
journalId,accountId,parentIdand the default account ids inside the organization, and party contacts, contact methods, locations and bank accounts refuse a company, person or party of another organization (IMPORT_ITEM_INVALID). Before, an item could post into another organization's journal or link to its parties. Runbetter-supabase upgradeto regenerate the accounting and contacts modules. - The generated access matrix counts column-level grants, so a table that grants a role INSERT on some columns no longer reads as denied for it, and a "reaches no row" cell accepts a statement that a trigger or constraint refuses, as such a statement reaches no row either. Regenerate your access matrix tests to pick it up.
{n:W}in a numbering format pads to at least W digits and no longer cuts a wider number, so a counter that outgrows its width keeps issuing unique numbers instead of repeating one. Runbetter-supabase upgradeto regenerate the numbering module.outbox_claimreads the oldest running transaction once per call, so an event that commits between the claim's read and its cursor move is no longer skipped when the consumer's types match nothing in the batch. Runbetter-supabase upgradeto regenerate the outbox module.- The outbox sets an event's
xidto the writing transaction's id on every insert and keeps it on an update, so an app that lets clients insert events can't have one plant anxidthat stalls or skips every consumer. Runbetter-supabase upgradeto regenerate the outbox module. - With the contacts block installed,
create_payment_batchpays a supplier that has a registered bank account only to one of its registered IBANs. Leaveibanout to pay the primary account; an IBAN the supplier didn't register fails withPAYMENT_BATCH_CREDITOR_INVALID, so the caller can no longer redirect a payment to an account of their choice. Runbetter-supabase upgradeto regenerate the banking module. A supplier with no registered bank account is still paid to the IBAN the caller gives. - A quote row written directly through the Data API can no longer plant the public link token or a customer decision: an insert outside an import or the service role clears them.
variantOfmust name a quote of the same organization (QUOTE_VARIANT_TENANT), so the variant functions can't be pointed at another organization's quote. Runbetter-supabase upgradeto regenerate the quotes module. - A quote's lines carry
taxCodeId,unitCost,discountAmount,costSource,locationId,binIdand the billing party columns when the line table has them, so a published version keeps them and accepting a quote with unpublished changes no longer blanks them on the restored lines. The customer's views (public_quote,portal_quote) leave the cost, stock and billing keys out. Runbetter-supabase upgradeto regenerate the quotes module. The published version'ssnapshotnow holds these internal columns as well; if your quote policy lets customers readquote_versions, keep them on the customer views. - A restore also leaves out the tables that grant access in the teams, guests, approvals, access-requests, agents, share-links, oauth-server, mfa, identities, organizations, connectors and agent-checkout blocks, and the grant, member, approval and secret tables of drive, inspections, invoices, knowledge, messaging, deals, subjects, webhooks and workflow-editor. A test now fails when a block adds a tenant table that decides access without classifying it. Run
better-supabase upgradeto regenerate the data-lifecycle module. - A state machine refuses a new record in a status the initial status can't reach in one step (
STATE_TRANSITION_INVALID), unless the insert runs in an import or as the service role. Before, a client with insert access could create a quote that was already accepted. Runbetter-supabase upgradeto regenerate the state-machine module. - The state machine's insert check now runs as the invoker and holds only client roles (
anon,authenticated) to the first statuses, so a security definer function a signed-in user calls can insert a record further along again. A machine'sinsertStatuseslists more statuses a client may insert in, and["*"]turns the check off. Upgrade note: a client that inserted records past the first step now getsSTATE_TRANSITION_INVALID; move that insert into a security definer function or the service role, or list the status ininsertStatuses. Runbetter-supabase upgrade.
0.86.0 (2026-11-25)
-
scheduling.bookWithReminderwith a reminder in minutes and the newbookings.holdWithReminderrun as one database call. Thebook_with_reminderfunction books and confirms the slot and saves the reminder in one transaction, so a failed reminder now rolls the booking back. The TypeScript hooks ofbookings.holdandreminders.upsertno longer fire inside it; the composite's own hook does. A reminder at an instant keeps the two-call path. -
finance.closePeriodand the newaccounting.closePeriodIfClearrun as one database call. Theclose_accounting_period_if_clearfunction checks the blockers and closes the period in one transaction, and a blocked period returns its blockers. The TypeScript hooks ofaccounting.closeBlockersandaccounting.closePeriodno longer fire insidefinance.closePeriod; the composite's own hook does. -
cms.publishWithVersionsnapshots{ type: "content_entry", id: entryId }when you pass nosubject, andcreateSupporttakes aticketSubjectoption (default"task") for the subject type of the ticket's SLA clocks. -
DbStatsnow carries atraceof every database call with its name, start and end in milliseconds, wave and phase (actioninsidebsb.action,renderfor every other call). The stats endpoint of the testing API returns it, so a harness can name each call of a page or action. -
doctorwarns with BS732 about statements thatauthenticated,anonandservice_roleran at least 5 times with a mean of 100 ms or more, read frompg_stat_statements(and frompg_stat_user_functionswhentrack_functionsis on). It reports nothing when the extension is not installed. -
RemoteCacheKey, whichbsb.remote()andbsb.sessionHandle()return, has two new fields:schema, a hash of the generated schema meta, andlibrary, the better-supabase version. Absb.kept()key carries the version too. An entry filled before a migration andgen, or by another release, is then never read, also when Next.js'sexperimental.durableUseCacheEntrieskeeps"use cache"entries across deploys. Every remote and kept entry starts again once after the upgrade.Doctor rule BS646 warns when
next.configturns that flag on and the app fills shared entries withbsb.public()or the remote scope: their key doesn't follow the database's policies or the Supabase project. The Cache Components page has a new section on when to use the flag and whenbsb.kept(), fromtests/next-durable-cache, which builds the example with the flag and checks which reader reads the previous build's entry. -
organizations.inviteWithinSeatsandsaas.inviteWithinSeatsrun as one database call. The newinvite_within_seatsfunction checks the invite permission, counts the members against theseatsentitlement and invites in one transaction. The parts' TypeScript hooks (organizations.members,entitlements.seatsLeft,organizations.invite) no longer fire inside the composite; the composite's own hook does. A full plan answersinvalid_requestinstead ofquota_exceeded. -
people.offboardwithout id lists, and the newemployees.offboardWithWork, run as one database call. Theoffboard_with_workfunction offboards the employee, cancels their active enrollments and unassigns their open shifts in one transaction. The parts' TypeScript hooks (employees.offboard,enrollments.cancel,shifts.unassign) no longer fire on that path; the composite's own hook does.invite_within_seatsnow runs with the caller's rights. -
people.onboardand the newemployees.onboardWithProgramrun as one database call. Theonboard_with_programfunction creates the employee, enrolls them and sets the enrollment dates in one transaction, so a failed enrollment now rolls the employee back instead of leaving them created. The TypeScript hooks ofemployees.createandenrollments.enrollno longer fire insidepeople.onboard; the composite's own hook does. -
support.openTicketand the newtasks.createWithSlarun as one database call. The create function makes the task and starts its SLA clocks in one transaction, so a failed clock start no longer leaves an open ticket behind. The TypeScript hooks oftasks.createandsla.startno longer fire insideopenTicket; the composite's own hook does. -
procurement.payDueBillsand the newbanking.payBatchrun as one database call. Thepay_payment_batchfunction creates the batch and posts it in one transaction, and the client writes the SEPA file from the bank accounts the call returns. A bill that needs approval now leaves no draft batch behind. The TypeScript hooks ofcreatePaymentBatch,postPaymentBatchandexportSepaCreditTransferno longer fire insidepayDueBills; the composite's own hook does. -
The
permissionsclaim can carry a bitset per tenant ({ h, b }, about 60 bytes for 300 keys) instead of the key list. The built-in roles and catalog models generatebetter_supabase.permission_claims_bitset(user, tenant)for the access token hook,permissionCataloginbetter-supabase/claimsbuilds the catalog that expands it, andpermissionsOf,permissionsAuthorizerandpermissionsShareKeyread it. A catalog that differs from the hook's returnsundefined, so the caller readsmy_permissions().genalso writespermissionKeys, the catalog key list, topermission-scopes.ts. -
finance.reconcileand the newbanking.reconcilerun as one database call. Thereconcile_bank_accountfunction reads the account's unmatched transactions and matches each to its best open invoice in one transaction, listing the ones that fail. The TypeScript hooks ofbanking.reviewQueueandbanking.acceptBestMatchno longer fire insidefinance.reconcile; the composite's own hook does. -
createNexttakesheldPermissions, a function that returns the caller's keys without a database call. Record loaders andrecordListServerread theircanflags from it and callmy_permissionsonly when it returnsnull. -
Doctor BS430 reports every reason a shared function can't run in a
share: "tenant"fill, numbered in one finding, and checks the functions it calls the same way. It matchessharedFunctionsonschema.name, so listingpublic.xno longer admits a call toprivate.x. A call to abetter_supabasehelper that passes the check on its own needs no listing; the doctor page lists those helpers.better-supabase config functions --shareable 'public.*_payload'runs the check on functions you haven't listed yet and prints each verdict with its reasons and the functions it calls.Authorization providers can declare
permissionFilters: helpers that return the tenants where the caller holds a permission, with the argument that holds the key. A shared function may call one with a literal key that the entry'spermissionslist, so it can filter the way a tenant table's select policy does.With an authorization provider set, the snapshot also keeps the bodies of the
language sql, security invoker, non-volatile functions in the read schemas, so BS430 and--shareablecan read them. On the repo's own schema that adds 0.4 MB tosupabase/snapshot.json. -
The Workflow SDK block and
better-supabase/workflow-sdk/worldmove to Workflow 5.8 and@workflow/world-postgres5.5, andbetter-supabase/eveto eve 1.5. The World speaks@workflow/world5.4.0, so the peer ranges becomeworkflow >=5.8.0 <6,@workflow/world >=5.4.0 <5.5,@workflow/world-postgres >=5.5.0 <5.6andeve >=1.5.0 <2. Theworkflow-sdkSQL module is at version 10: it addsworkflow.workflow_rate_limits(world-postgres migration 0033), closed to the API roles.The other peer floors move to the releases the repo tests, among them
ai >=7.0.181 <8,@ai-sdk/react >=4.0.186 <5,@ai-sdk/workflow >=2.0.113 <3,@orpc/server >=2.0.0-beta.53 <3,@nestjs/common >=12.6.0 <13,astro >=7.4.13 <8,hono >=4.13.21 <5,nuxt >=4.7.0 <5,react-router >=8.5.2 <9,@sveltejs/kit >=3.4.0 <4,@tanstack/react-start >=1.169.7 <2,stripe >=23.2.0 <24,redis >=6.4.0 <7andundici >=8.13.1 <9.Behaviour changes to check:
- Run
better-supabase upgrade(or apply theworkflow-sdkversion 10 migration) before you deploy world-postgres 5.5.0. assertWorldMigrations, which the World runs at startup, throws on a@workflow/world-postgresolder than 5.5.0.- The World's
capabilitiesreportrateLimits: falseandrateEventsInBatch: false. It mints spec 8 runs, so world-postgres 5.5's rate limits stay off and the new table stays empty. EveAuthRejectioncarries eve 1.5's error lineage, so eve'sHttpError.isaccepts it androuteAuthanswers with its response. Under eve 1.4 the check matched by name.- The React hooks write their latest-callback refs in a layout effect instead of during render, which the React Compiler requires. A test that mocks
reacthas to provideuseLayoutEffect. signInreturns aredirectTothat is not a valid URL unchanged, and Supabase Auth rejects it, instead of throwing. An eve connection whose callback URL is not a valid URL fails withConnectionAuthorizationFailedError(reason: "invalid_callback_url") instead of aTypeError.
- Run
-
The request stats list the names of the tags a request expired (
expiredTags) and record the size of eachbsb.keptentry in bytes. -
The request stats record a miss for
bsb.cached()andbsb.public()entries when their body runs, with the new entry kindsprivateandpublic. -
createNexttakesdebug: { coldStart: true }, which reports the first request of a process: how longbetter-supabase/nexttook to evaluate, when it was ready, and the firstcreateNext,warm(),getClaimsand query. The stats header gets acold=eval:…,ready:…,create:…,warm:…,claims:…,query:…field while a step is new, and the first query logs onebsb.coldline, so an app can tell which part of a slow first request is the library's. It uses onlyperformance.now(), so it runs on every runtime, and it collects request stats outside development likedebug.enabled. -
Doctor warns (BS647) when the app calls
bsb.kept()and sets nokept.storeincreateNext, or setsmemoryKeptStore(), because each instance then keeps its own copy of every entry. -
doctorruns without a database. When none runs and none is configured, the checks that read the schema use the saved snapshot (source.snapshot, elsesupabase/snapshot.jsonfromgen --save-snapshot) and doctor says so on stderr. When the run includes checks that need the database itself, such as the advisors or BS208, the error names them so you can leave them out with--ignoreor--only. -
createFlagsProviderandcreateBetterSupabaseAdaptertakestaleTtl(default 300000 ms). Afterttlthe previous flag definitions keep serving while one reload runs behind the evaluation, so one request per 30 seconds no longer waits on the Data API. A reload that fails keeps the old definitions untilstaleTtlpasses;staleTtl: 0restores the earlier behaviour. -
funding_award_usagereads the deliveries of each period once. A scalar subquery in the select list was copied into every use ofs.usedwhen the planner flattened the query, so the deliveries policy ran three times per period. On the example's award the call went from 478 ms and 23,361 buffers to 145 ms and 16,627 buffers. -
better-supabase/configexports theAuthorizationPermissionFiltertype, the shape of oneAuthorizationProvider.permissionFiltersentry, so a provider can name it. -
The read policies of
funding,medications,observations,consents,field-history,pipelines,slaanddeadlinescheck a registry subject's permission as a set and call one generated function per module for the row check, so a signed-in read plans in about 2 ms instead of 15 to 20 ms. Runbetter-supabase upgradeand apply the new migration; each module adds a*_subject_readablefunction (deadline_subject_row_readablefor deadlines) and replaces its read policies. Thefunding_deliveriesread policy now compares the award's tenant with the delivery's tenant. -
The
countersoption ofcreateServer({ sessions })no longer gives a server a private session memo. The counters attach to the one memo of the process, so a token the proxy verified and seeded after a refresh is a hit in the render instead of a second verification. The session cookie is also decoded once per distinct cookie value, not once per request scope. A clock,maxorttlMsstill gives a private memo. -
parseDbStatsreads thex-bsb-db-callsheader whendebug.coldStartappends itscold=field. Before, the extra field made every numberNaNand the parser returnedundefined. -
dev stack pruneand the baseline teardown select stacks with--stack <id>, because Supabase CLI 3.3.0 removed--stack-id. Doctor passes--remote=<url>tosupabase db advisorson CLI 3.0.0 and later, and BS710 now reports a CLI older than 3.3.0. -
The skill's UI recipes are current again. The command search recipe lists the app's areas and their actions, and the signing keys rotation recipe links the published JWK Set. The signing keys docs show
jwksResponsewith the object argument it takes.
0.85.1 (2026-11-24)
doctorruns within a 2 GB heap again on a project with a long migration history. It reads the migrations as code tokens one file at a time instead of keeping them all, reads SQL files one after another, keeps fewer scanned and parsed texts, and only parses the app sources that callkept. A cached result thatdoctorfound at the start no longer fails the run with "The SQL reader has not read this text yet" when a later write drops it from the cache file.upgrade,doctor,genandadd --adoptstart faster and use less memory: the adoption check reads the default SQL of only the blocks it asks about, and only when its cached result is missing, and each SQL text is scanned once.
0.85.0 (2026-11-24)
-
The audit block takes
options.retention: { keep, onExpire, batch }. With it set, the block installshousekeepingand adds anaudit_retentionjob tomaintenance()that deletes entries pastkeepin batches throughpurge_audit_log, creates the coming months of a partitioned log and, withonExpire: "detach", detaches whole expired months of a partitioned log the block owns as their own tables. Unset keeps every entry, as before. Doctor BS389 stops when retention is set, and the new live rule BS639 lists each audit exemption with its reason and its last audit entry (ADR 1215). -
The authorizer's request context gains
enforcement: "rls" | "definer". Repositorycreate,update,deleteandupsertthrough a caller's db sendrls, because RLS checks the write again; an admin db never does. Block verbs senddefiner. Actions, routes, resource actions and MCP tools takeenforcementon their definition and send nothing by default, which a provider treats asdefiner.recordingAuthorizerinbetter-supabase/testingrecords each check's operation, intent and enforcement, andtestAuthorizerchecks thatenforcement: "rls"never turns a denial into a grant. Additive onapiVersion: 1. See ADR 1221. -
postgresCacheSql()now createsbsb_cache_get, which reads an entry and checks its tags and the soft tags in one call, andbsb_cache_mark_tags, which writes each tag column withgreatest()so concurrent expiries never drop one. It grants the tables and functions toservice_roleand adds anexpire_aftercolumn for delayed expiry. Add the SQL to a new migration after you upgrade; until the functions exist, the store uses the two-request path, reports it once throughonErrorand tries again after a minute. The store, the Next.js handler and the Astro provider takefunctionPrefix, and the store and the Next.js handler taketransport: { postgres }instead ofclientto query through a pool.postgresCacheStoregainslookup(key, softTags)anddelete(key), and the Vercel Runtime Cache adapter gainsdelete(key). The store rounds the fractional timestamps Next.js passes down to whole milliseconds; before, every write to thebigintcolumns failed. See ADR 1221. -
Doctor adds BS429 (info), which lists the actions, write routes, resource actions and MCP tools that check a permission and set no
enforcement, so each one's authorizer check runs asdefinerand reads the authorization version live. It adds BS731 (warning) for each SQL file the schema reader rejects, with the file, line, column and the Postgres version whose grammar rejected it; doctor used to skip such a file without a word. BS409 now warns whenblocks.permissions.disabled.useror.tenantoverrides the provider'ssuspensionwith the other form, since a missing row lets the subject through with a column and disables it with a row.SchemaReadErrorgainsmajor, and thegen, config SQL and codemod messages name the grammar. -
Doctor gains three information rules. BS641 reports a table with more than
doctor.policies.maxpolicies (default 4) for one command and names each policy's kind and origin: library, provider or app. BS642 reports an exposed table with RLS whose index leads with an enum column, becauseenum_eqis not leakproof. BS643 counts the functions per schema by caller: policy, trigger, app RPC, service only or unreferenced. The newconfig functionscommand lists the same inventory, andlistFunctionsinbetter-supabase/sqlclassifies it (ADR 1216). -
blocks.drive.options.grants: "roles"keeps nodrive_grantstable:roleFunctions.nodealone names each member's role,drive_grants(node)lists the members it gives a role, anddrive_shareanddrive_unsharerefuse withDRIVE_SHARING_EXTERNAL. Authorization providers can addfunctions.roleOn({user},{resource},{id}), whichroleFunctions.node: { rows }calls when the provider's roles are not permission keys, and the provider conformance kit checks it. The defaultgrants: "table"renders the same SQL as before (ADR 1220). -
bsb.kept()andpostgresCacheHandlerfill a missing entry once. Concurrent misses in one process share one fill. Across instances,postgresCacheSql()adds absb_cache_leasestable and absb_cache_leasefunction that hands one caller the fill; the others wait up towaitms (250 by default) for its entry, then fill themselves. RunpostgresCacheSql()again in a migration to add them. AKeptStoremay implementleaseandrelease;vercelRuntimeCacheAdapterdoes so with a best-effort lock entry. See ADR 1221. -
The
party,product,stock_allocationandstock_countimport entities write the new rows of a batch in one statement per table throughimport_party_batch,import_product_batch,import_stock_allocation_batchandimport_stock_count_batch. With 2,000 new items an import takes 39 to 55 percent less time; results, counts, errors and the record map match the one-row path, which still handles updates and every item with a conflict in its batch.supplier_itemandassetkeep the one-row path, which was already faster than the gain. Runbetter-supabase upgrade(ADR 1217). -
Breaking: a done import chunk drops its items and keeps its result, and
runs.finishrefuses a run with a chunk that is not done (IMPORT_CHUNKS_OPEN).importChunkHandlermarks the chunk and its run failed on the job's last attempt (fail_import_chunkgainsfinal), andmaintenance()clears the items of ended runs afterchunks.keepFailedItems(default 7 days) and, withchunks.staleAfter, cancels a run whose worker died.runs.getreports chunk counts and bytes,runs.conflictspages every conflict of a run, and a stock count without a location goes to the organization's only active one. The chunks of a done 50,000-item run took 839,540 bytes and take none now (ADR 1223). -
Add
bsb.kept(fn, options), which keeps a read in a store across requests and deploys. The function runs as the caller, under RLS, with one entry per user, tenant and authorization version, and a write to one oftablesexpires it. A stale entry is served while one call refreshes it. Pick the store withcreateNext({ kept: { store } }):memoryKeptStore()(the default),vercelRuntimeCacheAdapter(getCache), which gainsexpireTags, or the newpostgresKeptStore()frombetter-supabase/cache-postgres. An entry over 2 MB, 128 tags or 256 bytes per tag is not stored and is reported tokept.onSkip. See ADR 1221. -
postgresKeptLease()frombetter-supabase/cache-postgresreturns the fill lease ofpostgresKeptStoreon its own, andvercelRuntimeCacheAdapter(getCache, { lease })takes it. The entries stay in the Runtime Cache, and one instance fills a missingbsb.kept()key instead of each instance whose read raced the lock entry. TheKeptLeasetype is exported frombetter-supabase/serverandbetter-supabase/cache-postgres. -
bsb.kept(fn, { share: "public" })keeps one entry for every visitor and fills it as theanonrole, under RLS, without reading the request or using the service role. The fill reads onlytablesandfunctions. Doctor rule BS645 reports a public entry on a table thatanoncan't select. -
Breaking:
invoice_open_itemsholds unallocated payments next to open invoices, so itsdocument_idno longer referencesinvoices; filter ondocument_typein your own queries. The store now matches the fold: its triggers andrebuild_open_itemscount thecreditedstatus, refresh on a charge, a kind change and a party change, and keep future-dated invoices, which the reads show from their issue date.open_items_drift(tenant)lists rows that differ from the fold,import_integrityreports them, and doctor rule BS638 names the organizations to rebuild. The invoices block moves to version 4, and the data migration rebuilds every organization. One party's 100 open items read in 1.4 ms instead of 2.6 ms on the local stack (ADR 1214). -
Request stats now count the calls of a fill that runs through a session handle (
bsb.cached({ session }),kept.as(session),getAccesswith a key) on the render that made the handle. Eachbsb.keptandbsb.remotecall adds an entry record ({ id, kind, outcome, fillMs }) to the stats route, andx-bsb-db-callsends intagCalls;hits;misses;fillMs.bsb.statsFetch(fetch)counts the requests of a Supabase client the app builds itself. See ADR 1221. -
Breaking: a record type with
search.frommust listsearch.columns, the columns of its own table the view reads; the config error names the record type. The search index trigger splits intobsb_search_<type>_indexfor inserts and deletes andbsb_search_<type>_index_u, which fires onupdate ofthe watched columns only when one of them changes value. On 1,000 rows of a view-backed type an update of an unlisted column drops from 71 ms and 1,000 trigger calls to 21 ms and none. The search block moves to version 6; runbetter-supabase upgrade. Doctor BS637 reports a column a source view reads thatsearch.columnsleaves out (ADR 1222). -
Four defaults are stricter.
verifySharedSecretreturns false for an empty secret, so an unset environment variable no longer matches a request without a header.createMcpthrows whencookies: truehas noallowedOrigins, as its doc comment already required.verifyHs256rejects a token without a numericexpclaim; Supabase tokens always carry one. The JWKS fetch stops after 10 seconds and refuses a response that declares more than 256 KB. The dev MCP server rejects tool arguments that start with-. -
shareGuard(ctx, db)frombetter-supabase/serverlets an app's own service run inside ashare: "tenant"fill. It gates a db the app builds itself, for example over its own Postgres pool, so it reads only the entry's tables and functions, and a refused read keeps the entry from being stored. The db must run as the caller: its claims carry the caller'ssuband role, so a db for another user, for the service role or for no one is refused. Outside a shared fill it returns the db unchanged.inTenantFill(ctx, tables, body)frombetter-supabase/testingruns a service the way a shared fill does. -
A
share: "tenant"fill can call database functions. An authorization provider lists them in its newsharedFunctionsfield, byschema.name, with the tables each reads and the permissions those reads check, andgenwrites them into the schema metadata.bsb.keptandbsb.remotetakefunctions: ["customer_payload"]: the function's tables join the entry's tables and tags, its permissions join the share key, and inside the fill$rpcpasses only the listed functions. Any other call still answersSHARE_REFUSED. Doctor BS430 fails a shared function that is security definer, isn'tlanguage sql, is volatile, reads the caller or reads a table its entry doesn't list, andtestAuthorizationProviderchecks that every table a shared function reads is shared per tenant. See ADR 1228. -
Read SQL with one reader and compare statements by their canonical text (ADR 1212 and 1213).
Breaking for callers of
better-supabase/sql: the statement splitter is gone from the entry. The CLI reads statements from the parser's scanner, which needs no valid grammar and keeps the same lines.Removed from better-supabase/sqlUse instead splitStatementsSplit in your own code, or read the file with the better-supabaseCLI (doctor,gen,sync)SqlStatement(type){ text: string; line: number }syncand the codemods compare statements by the parser's deparse, so spacing, comments, keyword case and redundant quoting no longer make a statement new. The migration file hash is versioned: new files end in_v2-<8 hex digits>.sql. A migration an earlier release wrote, with the old hash, is still recognized as the same file and is never renamed, so upgrading writes no new migration. A statement set that does not parse keeps the old name form.better-supabase/sqlno longer exports the SQL text readers:addedColumnTypes,adoptedColumnProblems,adoptedTables,adoptedViews,appColumnsOf,auditRegistrations,buildModel,checkValues,columnTagComments,conflicts,declaredCheckValues,declaredColumnTypes,declaredForeignKeys,declaredIndexes,declaredPolicies,declaredTableColumns,declaredTables,declaredUpdatedAtTriggers,declaredViews,duplicateObjects,duplicatePolicies,extensionSchema,mappingTagsOf,moduleWritesText,ownedColumns,ownerOf,parseDeclared,policyGrants,rlsTables,sameTenantLayout,sameTenantTagsOf,setParseStore,splitStatements,widenedCommands,withMappingTags,writtenValuesand the typesAdoptedTable,AdoptedView,CheckValues,ColumnTagComment,Declaration,DuplicateObject,OwnedColumn,ParseStore,SameTenantTags,SchemaModel,SqlStatement,TableCheckValues. The CLI reads SQL with one reader on@supabase/pg-parser, andsynccompares statements by their canonical text. New migration files end in_v2-<hash>.sql; earlier names stay recognized.migrationFileis async.
-
Breaking: order, fulfillment and return line quantities are
numeric, withoptions.quantityScale(0 to 6, default 0) setting how many decimals a quantity may have. Staff orders carrychannel,sourceandexternalId(unique per organization and source, and idempotent likeorigin),invoicingPolicy,deliveryMethod,quoteId,orderDiscount,promotionId,paymentRequiredwith adeposit, and aparty. Lines takeunit,description,lineTypeand the extra columns your schema files add.orderPage,orderFacetsandorderCountpage orders by keyset frompage_orders. The orders block moves to version 5; rename a column of your own that one of the new block columns takes (ADR 1224). -
A write now expires its tags in the
bsb.kept()store as well as in the Next.js cache, and the request stats count every tag call intagCalls. The Runtime Cache store sends oneexpireTagcall per 16 tags. See ADR 1221. -
The tasks block can treat MCP clients and API keys as agents, approve each hold kind under its own policy, and list the tasks that wait on a prerequisite:
options.claims.agentslists the session kinds the claim rules treat as agents:"agent"(always),"oauth-client"(a token withclient_id, or anactclaim without a kind) and"api-key". Such a session claims only tasks assigned to its user and can't take over a reserved task.options.hold.approval.kindsalso takes a record from hold kind totrueor{ policy, onReject }. Each kind files under its own policy and settles a rejection its own way; a field left out comes from the block-wide option.- The
waitinglist filter returns open tasks whosewaiting_oncount is above zero.
The module moves to version 8; re-run
better-supabase addto update the SQL. The upgrade adds no statement to an existing install. -
bsb.keptandbsb.remotetakeshare: "tenant": callers who hold the same permissions in a tenant read one entry, still filled through the first caller's own client under RLS. An authorization provider lists the tables it shares in its newtablesfield (share: "tenant"or"row", with the permissions their reads check), andgenwrites those facts into the schema metadata. The newshareKeyauthorization hook names the caller's grant;permissionsShareKey()frombetter-supabase/blocks/permissionsreads it from the permissions claim. Inside a shared fill a read of another table, a function call or a raw client answers aforbiddenDbErrorwith codeSHARE_REFUSED, and the value is not stored. A refused share falls back to one entry per user and reports the reason"share"tokept.onSkip. Doctor BS428 fails atenanttable whose select policies filter by the caller, andexpectTenantSharefrombetter-supabase/testingchecks a provider's hooks. See ADR 1221. -
better-supabase initnow writescookies: { encode: "tokens-only" }in the browser client andauth: { cookie: { encode: "tokens-only" } }in the server options, so a new app's session cookie holds only the tokens. On the Next.js example this saves about 1,350 bytes per request and one cookie chunk for a user with a permission claim. Existing apps keep the default until they switch; the sessions page lists the steps. The new doctor information rule BS644 reports an app whose cookie still carries the user object, lists the server files that callauth.getSession(), and with--as <user id>measures that user's object in bytes. -
VersionStore.getreturns{ version, at }andset(userId, version, at)takes the time the version was read, socreateVersionCachecountsmaxStaleMsfrom that time. Before, it dated a version taken from the shared store at the lookup, and a store whose keys never expire served a version of any age for anothermaxStaleMs, again and again. A store that still returns a number is read as a miss.VersionStoreEntryis exported frombetter-supabase/server. Breaking for a customstore; the 0.84 to 0.85 guide shows the new shape. See ADR 1227. -
server.warm()andbsb.warm()load the JWKS and open the PostgREST, read replica, pool and flags connections before the first request, in parallel, and report a time per step. They never throw.warm(bsb, { postgres, flags })frombetter-supabase/next/instrumentationruns it fromregister()and logs a failed step. The auth docs say whenprefetchJwks: falseis still needed. See ADR 1221. -
Fixes from the 0.85 adopter gate. The generated audit pgTAP file no longer checks a table that a
drop tableinside adoblock removed, and a droppedbsb_audittrigger counts asunaudit. A block withaudit: falsegets no row audit triggers on its tables. The invoices module grantsrebuild_open_itemsto the service role only and grantsopen_items_driftandopen_items_pageonce, and the API schema writes one wrapper per function when a module grants it twice. A view-backed search subject (search.from) re-indexes when itsexcludecolumn, such asarchived_at, changes, where its own table has that column. Doctor no longer reports extension types (citext,halfvec),serialtypes orpg_temptables under BS721,approvals: falsewithstandaloneApprovalson expenses under BS706, or an optional-column mapping that changes the render under BS427. The 0.84 to 0.85 guide says to runadd --adoptafter the schema diff. -
The browser client from
better-supabase/clientno longer adds its ownvisibilitychangelistener to refresh the session. auth-js already refreshes when a hidden tab becomes visible and the token expires within 90 seconds, so the second listener only added a duplicategetSessionand, near expiry, a second refresh call. -
Make the codemods read TypeScript through the syntax tree and never skip a file in silence:
codemod namingrenames an environment variable where code names it (process.env.NAME, a key, a binding) and a hint code or event name only when the whole string is the name. Comments stay as they are, and a string that holds a renamed environment variable among other words gets a review line..env*files andturbo.jsonkeep a text rename.- Every codemod with a source stage lists a TypeScript file that does not parse, with the line and the parser's message, instead of returning it unchanged.
-
Let
codemod prune,declared-rows,adopt-namesandextra-columnsedit config values that the config imports from other files whentypescript7.1 or newer is installed, and list those files for review. Import merging in the account calls codemod uses one shared helper. -
Read the session cookie and cache source rules (BS412, BS608, BS610, BS611, BS640) from the syntax tree. A comment, a string or a type annotation that mentions
encode: "tokens-only",bsb.remote(,cookies()orbsb.admin(no longer counts, and a function that follows such a string is still found. Findings, codes and lines stay the same for real code. -
Read the TypeScript doctor source rules from the syntax tree. A comment or a string that mentions a call no longer counts, and findings, codes and lines stay the same for real code. BS260 reports only imported function and type names, and BS511 and BS621 count dynamic imports. BS210, BS219, BS227 and BS351 check receiver types when
typescript7.1 or newer is installed. -
doctorparses each TypeScript source once for all rules instead of once per rule. -
Read the SQL and dotenv doctor rules (hooks, dispatch regression, error codes, the import guard, BS221, BS226, BS389 and the env rules) as tokens, so a comment or a quoted string that names a function or a pooler URL no longer produces a finding. Codes and findings stay the same for real code. The table-modules codemod puts a new import after a leading
"use client", and the same-tenant and table-tags codemods remove an entry from the file that declares an imported config value. -
genrecords each rendered SQL module that parsed, by content hash, in the CLI cache and parses only modules it has not seen, and it imports the configured read sets once per run instead of once per consumer.gen --checkon the CRM validation project goes from 5.55 s to 5.3 s. -
Check more SQL at
gentime, with the module or config key in the error:genrenders the installed modules and parses each one with the Postgres reader. A module that renders SQL Postgres rejects stopsgenwith the module name, the file position and the statement.- Config SQL is checked for every key that holds SQL, not only
authorization.functionsand event payload{ sql }columns: the role sources' and platform roles'through.where, persona and fixture rolesetup,vectorSearchboost,predicateandorder, andrealtime.triggerspayload{ sql }values. The error names the config path.
-
Add one guide from 0.82 to 0.85 with the steps in order. It says that an app on the Vercel Runtime Cache store needs
postgresCacheSql()only when it takes its lease from Postgres. -
The Vercel probe (
scripts/probe-vercel-tags.tsand the Next.js example's/api/probe/vercel-tags) now checks the kept store too: a read on another instance (--second), an entry from the previous deployment, set, hit and miss latency, and 250expireTagscalls in one second.--localruns the same steps onmemoryKeptStore(). -
better-supabase/nextloads the block clients thatbsb.record()andbsb.recordAt()call on their first call instead of at import. A fresh Node process evaluates the entry in 93.1 ms instead of 104.5 ms, and loads 89 files (224.2 KB gzip) instead of 109 (256.8 KB). -
outbox_registerstarts a consumer after the events its own transaction emitted, also while an older transaction is open, so the consumer no longer receives them.sole_owned_organizationstakes an optionalorganization(soleOwnedOrganizations({ userId, organizationId })): the list then names at most that organization, and another member's list needs the remove permission only there. The form without it still fails closed. The schema migration drops the one-argument signature (doctor BS235), so move any grant onsole_owned_organizations(uuid)to(uuid, uuid)in the same migration. In the migrations workflow the drop is skipped when a view or policy still calls the one-argument form, which then stays next to the new one and keeps answering one-argument calls, so drop or recreate those objects first.- A baseline built before 0.83 does not move restored transaction ids back on
baseline apply; rebuild it withbaseline build. Restored rows share one transaction id, so the outbox orders them by position. - The quotes block declares an
expiretimer (daily at 03:00) that runsexpire(), soblockSchedulesschedules quote expiry like the other block timers.
-
Request stats count a read that a
"use cache: private"function makes throughbsb.cached()with no session handle, including its time. This was already the case in 0.85; a test now holds it to the shape CentraKit uses for its order payload RPC. -
canonicalJsonskips the key sort for objects whose keys are already in order, andsnapshotOfreturns the snapshot it already built for the same verified auth state. -
The CLI's SQL reader keeps a
begin atomic ... endfunction body and a multi-action rule (do also (...; ...)) in one statement. It used to end a statement at every semicolon outside a string, so doctor rules, the migration and upgrade commands and the codemods that read statements saw the body as several statements, each with its own line number. A file whose parentheses orbegin atomicnever close still splits at every semicolon, as before (ADR 1226). -
Build
sql upgradesteps with the same context as the module files, so a step reads the configured tenant column and only touches columns an adopted table has. The tasks version 7 step no longer clearsdelegate_profileon a table without that column, and the tax version 2 step keys rates onsql.tenantColumninstead oftenant_id.
0.84.0 (2026-11-23)
-
Compare a block's
api: { schema }withdatabase.sql.api, so doctor BS427 andcodemod config --prunereport it as restated, and let the codemod setdatabase.sql.apiwhen most blocks name the same schema (it writesapi: falseon the blocks with no entry and keeps the change only when the render stays the same). BS427 now names a record type permission that repeats the provider'sactionKeysasrecordTypes.<type>.permissions.<action>; a doctor baseline entry for the oldsubjects.target is stale. Doctor BS715 counts, as info, the action keys the config writes that the provider'sactionKeyscould supply. The render and generator caches now include a hash of the config file and the project files it imports, and the generator cache includes the hash of the generator files, so an edit to an imported helper renders again. -
Let a provider's
functions.approverFortemplate use{requester}and{tenant}next to{kind}and{id}. Leave, expenses and time entries fill them from the request, so the provider can answer from the requester's manager chain without looking the request up. A template that names none of the four is still not read, and existing templates keep working. -
A block creates its table under its own names and your schema files extend it with
alter table, and the generatedfieldsnow carry the columns you add for every block, memberships included. Tag an app table that keeps its names withcomment on table ... is '@bsb block-table=<block>.<table>'and each mapped column with@bsb column=<column>instead of writingtablesandcolumnsentries; an entry in the config still wins.better-supabase codemod adopt-names --table <block>.<table>renames one table to the block's names: it writes a rename migration, rewrites the statements in your schema files that name the table, removes thetablesandcolumnsentries and lists the types that change. See ADR 1190 and the 0.82 to 0.83 guide. -
Make doctor BS427 compare resolved values. A provider value written with another key order, another order of
activevalues, other white space or another case in an unquoted SQL template is now reported as restated, andcodemod config --pruneremoves it. Ablocks.permissions.activeTenantof"resolver"(the default) is reported too. The BS409 message now names the provider'stokenHook.activeOrganizationFrom, and the docs say"resolver"means the request. -
Install the packages the CLI reads and plans with.
oxc-parser,@supabase/pg-parser,@supabase/pg-deltaand@supabase/pg-topoare now exact-pinned dependencies ofbetter-supabase, and only the CLI and the Node entries import them, so deployed functions do not grow. Remove@supabase/pg-deltaand@supabase/pg-topofrom your ownpackage.json: doctor reports a second entry as BS709, and BS239 (the two packages are missing) is retired. -
Shrink the config and add the provider features a provider already expects. 0.82.0 on npm has none of this work, so 0.83.0 is the first version with
actionKeys, approval floors (operations[].approval),doctor.command, the grouped baseline, BS427 andcodemod config --prune. Breaking changes, with the old and new forms in the 0.82 to 0.83 guide:blocksis a list of names and{ block, name?, ... }entries. Runbetter-supabase codemod blocks-list.- The numbering tenant column defaults to
database.sql.tenantColumninstead oforganization_id. Rungen sqland read the diff. - Record types are declared once, and
blocks.<name>.onnames a registered type. Runcodemod record-types. - Audit exemptions, data lifecycle, Data API privileges and same-tenant checks can sit in a
comment on tableas@bsbtags. Runcodemod table-tags. - An authorization provider can state
actionKeys,approverFor,managedUsersand approval floors. The config entry still wins. codemod config --pruneremoves entries the render already supplies and bisects by block group.- Doctor accepts a grouped baseline, reports BS427, BS706, BS707 and BS708, and fixes BS112, BS116, BS217, BS352 and BS365.
- Block fixes: tax codes are unique per tenant (run
validate constraintonce),cancel_approvalreaches expenses and time entries, notifications can email non-members, and the import runner, template clones, audit statement trigger and fake client filters are corrected.
-
Add
better-supabase config actionsandbetter-supabase config policies, withlistActions()andlistAccessPolicies()inbetter-supabase/sql.config actionslists every block, record type, bucket and topic action with the permission key it resolves to and whether the config, the provider or the default named it.config policieslists the policies the@bsb accesstags render, one row each, and the generated SQL now comes from the same rows. Both print JSON withversion: 1and ship a JSON Schema. -
db difflists thesupabase/schemas/_customfiles that no migration delivers, in the log and indata.custom: a file with no-- pgdelta-migration:line, or one that names a migration that does not exist. -
db diffstops under pg-delta when the schema files create an object pg-delta cannot manage, lists the objects indata.blockingand writes nothing. Pass--no-strict-coverageto leave them out as before. The Supabase CLI path now passes--strict-coveragetosupabase db schema declarative sync.db diff --proveapplies the plan to a clone of the local stack and refuses a plan that does not converge, loses rows or rewrites a table without saying so. -
Add the declared rows layer.
better_supabase.declared_defaultsholds option set items, pipeline stages, approval floors and numbering formats the app owns, and the block functions read it before the config literal, so a config without declared rows behaves as before. An option set binding can omititems; a field with neither declared nor literal items raisesOPTION_SET_DEFAULTS_MISSING. The newbetter-supabase db rowscommand turns each file insupabase/rows(upserts of literal rows by their natural key) into a data migration stamped with the hash of its statements, writes a new migration only when the hash changes, and with--checkexits 1 when a file has none. A removed row stays in the database and is reported, unless the file carries-- bsb-rows: delete-removed.approval_policyis nowstableinstead ofimmutable. The newcodemod declared-rowsmoves option set items, pipeline stages and approval floors from the config into rows files. -
doctoranalyzes the files undersupabase/schemaswith pg-topo and needs no database: BS720 (a file does not parse), BS721 (an object no file creates), BS722 (two statements create the same object), BS723 (a dependency cycle) and BS724 (an invalid-- pg-topo:annotation). Under pg-delta it also reports BS725 (adoblock with DDL,cron.schedulein a function body,alter publicationthroughexecute, default privileges withoutfor role), BS726 (the reserved names_clusterand_custom), BS727 (schema_paths), BS728 and BS729 (_custom/files without a migration or with modeled objects) and BS730 (a published table without a replication key). -
A state machine with an app history table writes the actor columns the table declares as
actor_name,actor_email,ipanduser_agentwithout naming them inhistory, and a child of a rows template inblocks.templates.options.typesneeds noparentwhen the schema declares one foreign key from the child to the root table. An entry in the config still wins, andbetter-supabase codemod config --pruneremoves the ones the schema now makes redundant. See ADR 1195. -
db diff --in-stackanddb squashname the pg-delta setting they need when the project diffs with migra.doctorreports what a migra diff drops from the schema files (BS713: an error for@bsbtags in a comment, a warning for grants and security-invoker views) and a module file whose@bsb-hashline adb pull --declarativeremoved (BS714).db squash --keepmerges the_1,_2files pg-delta writes in numeric order, and migrations written byupgradeandadd --adoptare created exclusively and retried on a stamp clash. -
Optional features of a block over your own table follow the columns the table declares, not a column entry in the config. Declaring
start_partandend_parton your leave requests table turns the parts of the day on, and aconfidentialcolumn on your leave types turns confidential leave on; the entriescolumns.requests.startPart,endPartandcolumns.types.confidentialare only for other names. Declaring one part column without the other is an error. A block never adds an optional column to a table you own, so BS622 reports required columns only, andcodemod config --prunealso removes anullfor an optional column your table lacks. A column entry on a block's own table no longer raises an error; the entry does nothing. See ADR 1189 and the 0.82 to 0.83 guide. -
blocks.organizations.options.attributesExcludekeeps columns your schema files add to the organizations table out ofcreate_organization,update_organizationandlist_my_organizations. Every other column you add stays an attribute without being listed inattributes. See ADR 1194. -
codemod config --pruneand doctor now remove more entries that equal a default:callbacksentries that keep the hook's name,apientries,tablesandcolumnsentries that keep the block's default name,onentries the schema's foreign keys give and theidType,tableandcascadeof a record type. Each is removed only when a render without it gives the same files. See ADR 1191 and the 0.82 to 0.83 guide. -
Add
authorization.doctor.timeoutMs(60000 by default). A provider doctor command that runs longer is stopped and reported as a BS705 finding that names the setting.doctor --update-baselineno longer gives a new BS705 entry the reason of an entry with another provider code. -
better-supabase codemod table-tagsmovesrecordTypes,realtimetables andvectorSearchentries into@bsb subject,@bsb realtimeand@bsb vector-searchtags when the config read through the tag gives the same value, and lists hand-writtenbetter_supabase.broadcast_topic()triggers. Thesubjecttag gainsheld,templateandread-access. See ADR 1196. -
Same-tenant checks now come from every foreign key between two tenant tables, composite keys included: the first column leads and the others are checked as
matchpairs. A@bsb same-tenanttag follows the nullability of the referenced tenant column instead of always letting a row with no tenant pass, takestenant=,parent-tenant=andshared=true|false, and works on any foreign key that holds the column.better-supabase codemod table-tagsmoves ablocks.memberships.options.sameTenantentry into a tag when the tag renders the same trigger statement, and lists each entry it leaves with the reason. See ADR 1192 and the 0.82 to 0.83 guide. -
Save snapshots as version 3. The file now records every function comment (not only the ones with tags), view column comments, the columns each check constraint covers, and each foreign key's deferrable, initially deferred and match type settings. Version 2 files still load and are read as version 3, and the new fields are optional, so nothing has to be regenerated. The JSON Schema is published as
schemas/snapshot-v3.json;snapshot-v2.jsonstays. -
Supabase CLI 3.2.0 is the tested floor. Commands that need it fail with the new error code
supabase_cli_too_old, anddoctorreports a CLI below 3.2.0 (BS710), whatsupabase config validaterejects with file and line (BS711), and adb.major_versionof 13 (error) or 14 (warning) (BS712).dev stack prunehands stacks with a missing directory tosupabase stack pruneand keeps the deleted-branch and idle rules. -
The CLI reads and writes
supabase/config.toml,config.jsonandconfig.jsoncthrough one module that follows the Supabase CLI 3.2.0 preference order, reports a json and jsonc conflict, and keeps comments whenbetter-supabaseedits a key.jsonc-parseris inlined into the CLI build, so apps install nothing new. -
better-supabase codemod table-tags --explainlists each audit exemption,data-lifecycletable andexposeentry that would move into a comment tag, says whether the render or only doctor reads the tag, and writes nothing. Before it moves adata-lifecycleorexposeentry, the codemod reads the config back through the tag and keeps the entry in the config when the value differs. See ADR 1193. -
Close five gaps in the task coordination, with the old and new forms in the 0.82 to 0.83 guide. Run
better-supabase upgrade: thetasksmodule is at version 7.claimNextpicks only tasks assigned to the caller. Setclaims.next: "any"to keep the old pick. Agent sessions always pick assigned tasks (TASK_NOT_ASSIGNED,TASK_FILTER_FORBIDDEN).hold.stage,claims.startStageandclaims.expiredStagetake a key or{ category }. Doctor reports BS245 for a missing stage.hold.kindslimits the kindsholdaccepts,hold.approval.kindslimits the ones that open an approval, and releasing, leaving the hold stage or closing cancels the pending request.task.hold_releasedcarriesapprovalCancelled.delegate({ toProfile })reserves a task for a profile (delegate_task(..., to_profile),TASK_RESERVED). Tasks read backdelegateProfile,claimNexttakesfilter.delegateProfile, andtask.delegatedcarriestoProfile. The old column value, the delegator label, is cleared.before_task_closeruns once on every closing path from an after-update trigger, and a hook that raises refuses the close. It no longer runs on a reopen.
-
The source codemods and the doctor's source checks now read your TypeScript with a parser to tell code from strings and comments. A quote inside a regular expression, a nested template literal and apostrophes in JSX text no longer hide the code after them from
codemodanddoctor. -
The import and subpath renames in
codemodnow read your TypeScript with a parser. They leave object keys, members, type members, shadowing locals, comments and strings that only mention a name alone, writeold: newfor a shorthand property, and keep CRLF and tab files as they are.codemod account-callsreportsctx.bsb.deleteAccount(id)for review instead of writingctx.deleteAccount(bsb, id), and adds to an existingbetter-supabase/server/accountimport.adoptsays when it could not setdoctor.migrationSafety.since, and a shorthandblocksentry no longer produces a syntax error. -
claim_next_taskpicks another ready task when a racing worker committed its claim on the first one, instead of raisingTASK_CLAIMED. -
The config codemods (
config --prune,blocks-list,record-typesand the key renames innaming) now readbetter-supabase.config.tswith a TypeScript parser.config --prunefinds array paths such assameTenant[1], a comment or string that holdsexport default {no longer hides the config, a key that comes from a shorthand property or a variable is edited where it is declared, and an entry the codemod cannot follow in place is reported instead of skipped. A config that does not parse stops with its path, line and column. -
BS725 also reads the module files better-supabase writes under
supabase/schemas, names the module in the finding, and no longer counts acron.schedulelookup inside a string as a call. -
doctorno longer reports BS721 or BS722 for the module files the library renders undersupabase/schemas/_better_supabase, and BS722 ignores repeatedcreate schema if not existsandcreate extension if not existsstatements, so a project that installs many blocks no longer gets thousands of duplicate-definition warnings. -
Make
genparse the SQL expressions in your config before it reads the schema. An authorization provider'sfunctionstemplate or a block's{ sql }event payload column that is not valid SQL now stopsgenwith the config key and the parser's message, instead of failing later in a migration. Placeholders such as{user}and{row}are accepted. -
The module files
better-supabase genwrites namefor role postgresin everyalter default privilegesstatement, and theautoEmbeddrain and the queuehttpTickjob are plainselect cron.schedule(...)statements, so doctor BS725 no longer reports them under pg-delta. BS725 also accepts acron.schedulecall that first checkspg_cronis installed (to_regnamespace('cron')orto_regprocedure('cron.…')). Doctor BS721 no longer reports a platform schema such asextensions, a built-in type such asxid8, or a call to a function some schema file creates when the call leaves out arguments that have defaults. The declared stages of a pipeline and the declared items of an option set now seed correctly (thewith ordinalitylist in the generated function was invalid SQL), and a new migration addsbetter_supabase.declared_defaults. Runbetter-supabase genand review the module file diff. See the 0.82 to 0.83 guide. -
The schema reader now treats a policy without a
toclause, or withto public, as a policy forpublic, so the grants it derives match the text scanner. A columnreferences ... deferrableis read as deferrable, andcomment on functionkeeps its argument signature. -
Fix the
alter table ... add column if not existsstatements the blocks write over an app's own table. A column default such asarray['a', 'b']is no longer cut at its comma, and anot nullinside acheck (...)is no longer removed, so the generated SQL parses. Themoderationandwaitlistmodules change when an app owns their tables. -
The CLI edits
better-supabase.config.tsandlib/blocks.tsthrough the config document, soadd,removeandadoptfollow a list kept in a variable, read numeric keys and report the line of a config that does not parse. Files with.tsgeneric arrows are read as TypeScript before TSX. -
doctorandcodemoduse TypeScript 7.1 or newer, when your project has it, to follow a name across files. BS609, BS634 and BS635 drop a read whose receiver TypeScript types as a plain collection such as aMap.codemod namingrenames the files that import a renamed export your app re-exports, andcodemod configremoves acolumnsentry from the file that declares an imported config value. Without TypeScript 7.1, doctor adds an info finding that says receivers were matched by name, and each codemod lists the files it did not follow as review lines.The config, naming and column codemods now rewrite your config and source through a parser, and the doctor source checks read functions, loops and
Promise.allcalls from the syntax tree, so a regular expression, a template literal or JSX text no longer changes what they find. -
A 403 from the Management API on a request that needs a permission (
doctoradvisors,genintrospection) now says the access token is valid but a scoped token lacks it, and where to create one that has it. -
The CLI can use TypeScript 7.1 or newer, when your project has it installed, to find where a symbol is used and declared across files.
typescriptis now an optional peer (>=5.0.0); without 7.1 the codemods keep working file by file.
0.83.0 (2026-11-23)
-
Shrink the config in 0.82. Breaking changes, with the old and new forms in the 0.81 to 0.82 guide:
blocksis a list of names and{ block, name?, ... }entries. Runbetter-supabase codemod blocks-list.- The numbering tenant column defaults to
database.sql.tenantColumninstead oforganization_id. Rungen sqland read the diff. - Record types are declared once, and
blocks.<name>.onnames a registered type. Runcodemod record-types. - Audit exemptions, data lifecycle, Data API privileges and same-tenant checks can sit in a
comment on tableas@bsbtags. Runcodemod table-tags. - An authorization provider can state
actionKeys,approverFor,managedUsersand approval floors. The config entry still wins. codemod config --pruneremoves entries the render already supplies and bisects by block group.- Doctor accepts a grouped baseline, reports BS427, BS706, BS707 and BS708, and fixes BS112, BS116, BS217, BS239, BS352 and BS365.
- Block fixes: tax codes are unique per tenant (run
validate constraintonce),cancel_approvalreaches expenses and time entries, notifications can email non-members, and the import runner, template clones, audit statement trigger and fake client filters are corrected.
-
better-supabase/cache-postgreskeeps Next.jscacheHandlersentries and Astro route cache responses in Supabase Postgres, so every instance shares them and a tag you expire takes effect on all. It exportspostgresCacheHandler,astroPostgresCache(andbetter-supabase/cache-postgres/astroas the Astro provider entrypoint),postgresCacheStoreandpostgresCacheSql, which returns the SQL for two tables that only the service role can read. -
Fix five gaps an adopter found on 0.82:
baseline applymoves everyxid8orxidvalue of the restored rows that is ahead of the new database's transaction counter back to the restoring transaction, andoutbox_registernever starts a consumer past the current snapshot, so a consumer registered on a fresh stack no longer skips new events.submit_expenselets the line manager or the update key resubmit a rejected expense whose owner has no account; an owner with an account still resubmits their own.- The relay's receive check reads its probe message back by its typed primary key, so it no longer scans
realtime.messages. baseline applyremoves its temporary folder when unpacking the storage tarball fails.cancel_leave_requestrefuses a rejected request only while it is not approved, matching the status it reports.
0.82.0 (2026-11-22)
-
AI SDK surfaces for media, MCP, harness agents and tools. There are no breaking changes.
Features
createMediaRouteandcreateVideoRoutes(better-supabase/ai-sdk/chat) serve image, speech and video generation with an access check, the quota, metering and Storage output. The video webhook only wakes a status check.mcpResourceTools,mcpPrompts,mcpPromptMessagesandmcpEventRoute(better-supabase/ai-sdk/mcp) cover MCP resources, prompts and the event webhook.harnessRoute,steerRouteandharnessStateCipher(better-supabase/ai-sdk/agents) run aHarnessAgentturn and store its resume state encrypted.@ai-sdk/harnessis a new optional peer.tenantToolsContextandguardTools(better-supabase/ai-sdk) pass the tenant to tools and apply guardrails to tool inputs and outputs.
-
Leave, expenses and timesheets filed for an employee without an account no longer make the member who filed them the approval's requester, so that member can decide them, and a request without a requester now notifies its approvers instead of nobody. A mapped
rejected_atkeeps a leave request rejected in approvals mode without an approval request, soupdateandcancelfail withLEAVE_REQUEST_CLOSED. Time entries takeoptions.writer, an app function(tenant, owner uuid) returns booleanthat lets more callers log, change and archive another owner's entries and submit and withdraw their weeks.sole_owned_organizationsfor another member now fails withORGANIZATION_FORBIDDENwhen the caller lacks the remove permission, instead of returning an empty or partial list. -
createMediaRouteandcreateVideoRoutesinbetter-supabase/ai-sdk/chattake agatewayPolicyoption. Pass the reader thatgatewayPolicyReaderreturns, and the organization's gateway policy is applied to theproviderOptionsyourrunandstartcallbacks receive. A policy that fails to load answers with its error instead of running the call. Without the option nothing changes. -
Close the gaps task coordination left. A hold can open an approval (
blocks.tasks.options.hold.approval): approving releases the task, and a rejection cancels it or, withonReject: "keep", leaves it on hold. Messages carry who acted:sendand commentcreatetakeactor: { kind, name }, andMessagereturnsauthorKindandauthorName, whichmessage.sentalso carries asactorKindandactorName.Upgrade notes:
- The messaging module is at version 2. Run
better-supabase upgrade, thenbetter-supabase db diffand apply the migration. It adds the nullableauthor_kindandauthor_nametext columns to messages. An adopted messages table gets them only when you map them or runcodemod owned-columns; without them the label is not stored andauthorKindisundefined. hold.approvalis off by default and needs the approvals block and theheld_atcolumn. When it is on, the tasks module adds the internal functionsettle_task_hold, which no role can call.- Messages sent before the upgrade have no kind or name.
- The messaging module is at version 2. Run
-
Add task coordination for queues that people and agents share.
tasksgains prerequisites (options.needs,setNeeds, thereadyfilter andtask.unblocked),createPlan, leased claims (claim,claimNext,renew,release,delegate), holds,noteoncompleteandcancel,fail,moveandmoveMany,stageTimesand the realtime topictasks:{organizationId}.db.permissions.explainandexplainPermissionToolsay why a member holds or lacks a key.Upgrade notes:
- The tasks module is at version 6. Run
better-supabase db diffand apply the migration. New columns (waiting_on,held_at,hold_kind,close_noteand the claims table) exist on an adopted table only when you map them; the claims table needsapp: {}when you setownTablePolicies: "app". - Audit rows and timeline entries label an
actof kindagentasagent. They wereimpersonationbefore, so reports that group by actor kind change. setNeedsandcreate({ needs })need the relations manage permission.failneeds a canceled stage; withcanceled: nullit raisesTASK_OUTCOME_UNAVAILABLE.- The client method is
createPlan;createManystays retired. - A new function
better_supabase.explain_permissionis granted toauthenticated.
- The tasks module is at version 6. Run
-
Agents on Supabase with Vercel Sandbox, Connect and the Chat SDK.
supabaseAccessandsupabaseAccessFrominbetter-supabase/vercel-sandboxbuild a sandbox network policy that reaches only your Supabase project, as one user. The firewall adds the token, so code in the sandbox never holds it. They refuse a service role key.connectEventRouteandpostgresConnectEventSubscriptionsinbetter-supabase/vercel-connectverify Connect and MCP event deliveries and write each one to the outbox once, with subscriptions in aconnect_event_subscriptionstable you create.connectAuthinbetter-supabase/evewrapsconnectfrom@vercel/connect/evewith the same Connect subject asvercelConnectCredentials.chatHistoryanderaseChatHistoryinbetter-supabase/chat-sdkkey the Chat SDK's user history by the linked app user and erase it by user.
Upgrade: nothing breaks. To receive Connect events, create the table from the Connect events docs page and mount the route.
-
Blob client uploads, Nitro 3 in the Nuxt module and an agent block from
init. There are no breaking changes.Features
blobUploadRoute(better-supabase/storage) answers Vercel Blob client uploads:authorizeruns your permission check before a token is issued, andonCompletedrecords the finished upload.- The Nuxt module detects Nitro 2 or 3 and writes
toH3V1ortoH3middleware to match. better-supabase initwrites a managed block intoAGENTS.mdfor projects that already have agent files.
-
Expire cached reads when a write comes from outside the process, and cache public reads without the service role.
cacheRoute(better-supabase/server) verifies a bearer token or a Standard Webhooks signature and expires thebsb:tags of a change. It reads the trigger's payload, a Supabase Database Webhook and an outbox CloudEvent.cacheInvalidationSql(better-supabase/sql) generatesbetter_supabase.notify_cache()and statement-level triggers that send the changed table, ids and tenants throughpg_net. Write its output into a migration, then store the route URL and the token in Vault withselect vault.create_secret('https://app.example.com/hooks/cache', 'bsb_cache_url')andselect vault.create_secret('<token>', 'bsb_cache_bearer'). Enable thepg_netandsupabase_vaultextensions first. Without the URL secret the triggers do nothing.vercelRuntimeCacheAdapter(getCache)andvercelCdnCache({ addCacheTag, invalidateByTag })are cache adapters over@vercel/functions(>=3.11.3 <4, an optional peer you pass in).encodeCacheTagescapes the characters Vercel splits tags on.bsb.public()(better-supabase/next) returns an anonymous context for'use cache'reads, so Row Level Security applies and the service role stays out of shared caches.- Doctor rule BS640 reports a plain
"use cache"function that readscookies(),headers(),bsb.cached(),bsb.context()orbsb.user().
Upgrade: nothing changes until you add the route, the SQL and the secrets.
pg_netsends once and doesn't retry, so keep a shortcacheLifeas the backstop. See the Vercel cache invalidation page in the docs. -
Durable execution parity with Vercel Workflow, Queues and Schedules.
startFortakesretention,deploymentIdandhook. A start with ahooktoken is idempotent on that token and resolves to the owning run on a conflict.cancelTenantRuns(tenant)inbetter-supabase/workflow-sdkcancels a tenant's open runs, withruns.cancelManywhere the World has it.ScheduleProvidergains optionalscheduleOnce,enableSchedule,disableSchedule,runScheduleNowandgetSchedule, andcreateQueuegainsscheduleOnce,enableSchedule,disableSchedule,runScheduleandgetSchedule.vercelSchedulerimplements them andtestScheduleProviderchecks them. A listed schedule now reportsonceandenabled, and a one-time schedule has anextRun. The SQL scheduler does not implement them and answersinvalid_request.maintenanceRouteandleaseOverlapinbetter-supabase/blocks/queue.cronRoutetakesmaxLateSecondsandoverlap.
Upgrade: nothing breaks. A custom
ScheduleProviderkeeps working because every new member is optional, soapiVersionstays 1. AVercelSchedulesClientfake needsget,enable,disableandinvokeonly to use the new schedule methods. -
AI Gateway governance per organization in
better-supabase/ai-sdk.GatewayOptionsis now typed after the SDK'sGatewayProviderOptions(a structural copy, so@ai-sdk/gatewaystays an optional peer). Upgrade note: a misspelled key or a non-string entry intags,onlyororderis now a compile error. Fix the call site; nothing changes at runtime.parseGatewayPolicy,gatewayPolicySetting,gatewayPolicyReader,mergeGatewayPolicies,applyGatewayPolicyandgovernedGatewayOptionsgive each organization a policy (zero data retention, allowed providers, region, prompt caching, headquarters) stored in the settings block.createGatewayBudgetchecks an organization's budget before a call and settles the cost after it, on the usage block'sai.costmeter.gatewayCostOf,gatewayCostEntries,gatewayRunReleaseandcostUsagekeep cache read and write tokens, reasoning tokens and the market cost.gatewayCostBackfillretries until the gateway knows the generation, andcheckGatewayCreditsandcreditsMonitorwatch the team's credits.virtualModelCatalogRefreshadds virtual models to the model catalog, andvirtualModelSpendReconciliationattributes their spend by user, because a virtual model replaces the request tags.
-
Vercel integrations gain a Vercel OIDC
AuthResolver, verdict handlers, deadline-aware Postgres statements, Blob options and framework guards. There are no breaking changes.Features
vercelOidcResolver(better-supabase/vercel-passport) verifies a Vercel OIDC token and returns anapiKeycaller from yourmap.verifyPassportcan read the chunked_vercel_passportcookie withheaders: "cookie"or"all".botIdGuardandfirewallRateLimittakeonVerdict.firewallRateLimiter(better-supabase/vercel-security) is aRateLimiterbacked by the Vercel Firewall.createPostgres({ getDeadline, deadlineMargin })cancels a statement that could not finish before the invocation ends.vercelBlobStoretakesttlDays,cacheControlMaxAge,storeIdandoidcToken, and maps Blob's store, suspended and precondition errors toDbErrorcodes.- The Vercel domain provider reports
misconfiguredand the recommendeddnsrecords when the SDK hasdomains.getDomainConfig. bsb.caller()guards SvelteKit remote functions (passgetRequestEventinkit).bsb.guard()is the guard for a TanStack Start function middleware.
-
Observability on Vercel: query metrics, server errors and workflow run outcomes.
better-supabase/otel/vercelexportsvercelMetrics(metric), a plugin that sends the duration and the failures of every repository operation to Vercel custom metrics through themetricfunction of@vercel/functions. It makes at most 16 calls per request (maxCalls) and sends onebudget_exceededcount past the cap. It has its own entry so an app does not need@opentelemetry/api.better-supabase/next/instrumentationexportscreateOnRequestError(betterSupabase), a handler for Next.js'sonRequestErrorthat emits arequest.failedblock event with the error name, a cut message, the digest, the path without its query string and the route context.registerWorkflowLifecycleinbetter-supabase/workflow-sdkregisters the Workflow SDK's lifecycle hooks and writesworkflow_sdk.run_completedandworkflow_sdk.run_failedto the outbox, with the key<runId>:<transition>. The SDK reports only completed and failed runs.- Docs: a Vercel observability page with the
@workflow/webmount behindprotectWebHandlerand recipes for@vercel/oteland eve'sagentRuns().
Upgrade: nothing breaks. All three are new exports, and
@vercel/functions,nextandworkflowkeep their tested ranges. -
A Supabase project on Vercel works without renamed variables.
- The CLI (
gen,db,doctor) and the Workflow World readPOSTGRES_URL_NON_POOLINGandPOSTGRES_URL, the names the Supabase integration syncs. The CLI prefers the direct string, the World the pooled one. loadEnvandparseEnvtakeprefixfor an integration connected with a custom prefix (DB1readsDB1_SUPABASE_URL), and say when only the legacySUPABASE_ANON_KEYorSUPABASE_SERVICE_ROLE_KEYname is set. New exports:withEnvPrefixandprojectRefOf.- New
better-supabase/vercelentry:deploymentUrl,protectionBypassHeaders,protectionBypassUrl,deploymentIssuesandassertDeployment. The bypass secret is only sent to the deployment's own hosts. The Workflow World adds the header to its flow route. better-supabase doctor --vercelreads.vercel/.env.<name>.localand reports BS513 (an environment lacks a Supabase variable), BS514 (a secret under a browser prefix) and BS515 (preview and production on one Supabase project).- New docs page: Deploy on Vercel.
Upgrade: nothing breaks. A CLI run that had
POSTGRES_URLin its shell now connects with it when no other connection string is set; pass--db-url-stdinor setDATABASE_URLto choose another. - The CLI (
-
Fix drift in the AI and agent adapters. A Vercel AI Gateway budget or credit rejection (HTTP 402) now maps to a
quota_exceedederror with status 402 and the codeAI_GATEWAY_PAYMENT_REQUIREDinstead of a 503 outage, gateway errors keep theirgenerationIdandruleIdindetails, the gatewaytimeout_errortype maps to a timeout, and the newer AI SDK error names are recognized.connectToolsandconnectAllreturn atoolApprovalmap foraskUnlessReadOnlyinstead of setting the deprecatedneedsApprovalon each tool; pass the map as the agent'stoolApproval.invalidateTokenon the Vercel Connect provider now names the team and organization scope, so a scoped token leaves the cache, andstartAuthorizationforwardswebhookandexpiresInMs.credentialAuthfor eve sends the device code asuserCodeand evicts through a provider that caches tokens. The CLI detectsOPENCODE=1. The eve, BotID, Firewall and Sandbox structural types follow the installed SDKs, and the peer ranges in seven docs pages match the catalog. -
Fix drift in the framework adapters. The Next.js adapter sends cache tags to
cacheTag()in chunks of 128, so a list longer than 128 no longer loses its tail. The TanStack Start page and the middleware filebetter-supabase initwrites now includecreateCsrfMiddleware, because definingsrc/start.tsturns off Start's default CSRF protection for server functions. -
Fix the Workflow World delivery contract. A continuation (the flow asked to wait) starts
attemptover, so a long run no longer reaches@workflow/core's 48 delivery cap through sleeps and step retries. Invercel-queuemode a continuation and the hops of a long delay are sent without an idempotency key, because Vercel drops a send whose key it saw in the last 24 hours. The World no longer claimsmaxConcurrencyorinBandFenceand creates spec 8 runs even whenWORKFLOW_SPEC_VERSION=9is set, since the pgmq queue does not serialize a run's messages.queueBatchreportsretryableas@vercel/queuereturns it.
0.81.0 (2026-11-21)
-
The npm README leads with a supabase-js comparison, a feature table and a five-step quick start, then covers existing apps, frameworks, the CLI, blocks, integrations, subpaths, agent support, limits and the upgrade policy. The package keywords name the frameworks and features it supports.
-
eve on Supabase moves to eve 1.3, Workflow 5.7.1 and the ai 7.0.179 line, finishes the purge of zero-retention runs through world-postgres 5.4.1's backstop, lets a web tier skip delivery with
skipWorkers, and addssupabaseSkillScopesfor eve's custom skills. The migration guide is From 0.80 to 0.81.Breaking changes
- Peer ranges:
eve >=1.3.0 <2,workflow >=5.7.1 <6,@workflow/world-postgres >=5.4.1 <5.5,ai >=7.0.179 <8,@ai-sdk/react >=4.0.183 <5and@ai-sdk/workflow >=2.0.111 <3.@workflow/worldstays at 5.3.0 and the World still speaks protocol 5.3.0. - The
workflow-sdkSQL module is at version 9. Runbetter-supabase upgradebefore you deploy world-postgres 5.4.1: version 9 addsworkflow.add_job, which takes the purge backstop world-postgres 5.4.1 adds when a zero-retention run ends, andworkflow_purge_backstops(). Without it, the final write of a zero-retention run fails. In thepg_netandvercel-queuedelivery modes it schedulesworkflow_purge_backstops()on pg_cron every minute; in poll mode the World runs it while it polls. WorkflowMaintenancehas a new required member,purgeBackstops({ batch? }). The World implements it; a hand-writtenWorkflowMaintenancemust add it.- The World sets
GRAPHILE_WORKER_SCHEMAtoworkflowwhen it is unset and warns when it names another schema, because no runner of the World reads that schema.
Features
createSupabaseWorld({ skipWorkers: true }), orWORKFLOW_POSTGRES_SKIP_WORKERS=1, starts, resumes, cancels and reads runs without polling or delivering, for a web tier next to separate workers.supabaseSkillScopes()frombetter-supabase/evekeys eve's experimental custom skills by tenant: personal, persona (read-only, chosen per turn from eve 1.3's turn id and parent session), channel and organization (writable by the roles inwritableBy). Store the skills withsupabaseDocumentBackend({ memory, scope: "skills" }).
- Peer ranges:
-
eve on Supabase moves to eve 1.2 and Workflow 5.7, runs on the Supabase World under the transaction pooler and on Vercel Queues, projects sessions into the chat tables from a cursor, and runs the inbox as an eve channel. The migration guide is From 0.79 to 0.80.
Breaking changes
- Peer ranges:
eve >=1.2.0 <2,workflow >=5.7.0 <6,@workflow/world >=5.3.0 <5.4and@workflow/world-postgres >=5.4.0 <5.5. eve 1.0 release candidates and releases before 1.2.0 are not supported, andassertWorldMigrationsthrows on a@workflow/world-postgresolder than 5.4.0. The World speaks protocol 5.3.0, andbetter-supabase/workflow-sdk/world/package.jsonis a stub manifest that carries the@workflow/worldrange for eve's startup check. - The
workflow-sdkSQL module is at version 8 and theai-schedulesmodule at version 3 (theinboxmodule at version 11). Runbetter-supabase upgradebefore you deploy Workflow 5.7. Version 6 addsworkflow_run_delivery_leasesandworkflow_runs.wake_pending, and runs that exist before the upgrade start withwake_pendingset. Version 7 adds the eve projection. Version 8 replacesdispatch_workflow_deliveries()and adds no table. persistSessionsis wake-only. It takes{ store, delaySeconds? }instead of{ chats, agentId, title }: passstore: createSupabaseWorld().eveSessions, runcreateSessionSync(...)where eve'ssessions.attachis available, and moveagentIdandtitleinto itsresolveoption.cancel_approval(request_id, reason)replacescancel_approval(request_id), andworkflow_purge_runstakes a fourth argument,skip_unprojected.better-supabase/ai-sdk/workflowpasses the tool approval policy toWorkflowAgentastoolApprovalinstead of wrapping each tool withneedsApproval. A denied tool call now ends as anexecution-deniedresult, which the model sees, instead of an error.createAssistantstores a stream that failed after it started as anerrormessage, releases the run asfailedwith the error text, and callsonFinishwithstatus: "failed". Before, the answer was stored ascomplete.GatewayAccessPolicyDeniedErrormaps to aforbiddenerror with codeAI_GATEWAY_ACCESS_POLICY_DENIED.- The
ai-schedulesdispatcher only claims tasks whosesourceisai-schedules. - The stream flush interval of the World defaults to 20 ms, and the pool holds 2 connections by default on Vercel, AWS Lambda and Netlify.
- The inbox keeps one
aidraft per conversation andreplyKeyin any status (inbox module version 11 adds the unique indexinbox_drafts_ai_key).
The World
delivery: "vercel-queue"(orWORKFLOW_DELIVERY=vercel-queue) delivers over Vercel Queues.@vercel/queueis an optional peer loaded on first use. It sends each message to its__wkf_*topic, splits delays over 23 hours into hops, and answers Vercel's retry with the World's backoff and the 73 delivery limit. It runs only on Vercel, so a fake client tests it.deliveryHeaders(WORKFLOW_DELIVERY_HEADERSor the Vault secretworkflow_delivery_headers) adds headers such asx-vercel-protection-bypassto poll andpg_netdeliveries, andrecoverAfter(WORKFLOW_RECOVER_AFTER_SECONDS) sets how long an owed wake-up waits before the World queues it again. The World clearswake_pendingwhen an orchestrator delivery completes and sweeps stale flags.delivery: "poll"on Vercel logs a warning.connection: "transaction"(chosen on port 6543, or withWORKFLOW_POSTGRES_CONNECTION) polls stream readers and omits theLISTENbased feeds, so the World no longer warns on the pooler. The warning appears only forconnection: "session"on a pooled URL.encryptionKeys(WORKFLOW_ENCRYPTION_KEYS, Vault secretworkflow_encryption_keys) takes a ring of master keys. With more than one key, the World stamps the key id on each new run as the attribute$bsb.key_id, so a run keeps opening with its key when afromdate changes.world.start()warns when no key is set outside development and test.- New exports from
better-supabase/workflow-sdk/world:isServerless,parseKeyRing,ringKeyFor,runCreatedAt,RingKey,WorldConnection.
eve
createSessionSynccopies sessions into the chat tables from a cursor, read through eve's reader and keyed by event.syncSession,sweepSessions,sessionHistory,openSessions,endStrandedSessionsandcreateEveSessionStoreare new,world.eveSessionsis the store,ai_runs.external_run_idholds the eve run id,purgeRuns({ skipUnprojected: true })keeps runs the sync has not read, andapprovals.cancel(id, { reason })records why an approval was cancelled.inboxConnectionWebhook,inboxHandoff,inboxRunAsandinboxRepliesrun the inbox on eve without Chat SDK.createSessionSynctakes areplyhandler.strictestApproval(...policies)combines approval policies, andsupabaseTool,eveContextandapprovalPolicyacceptpermission, a key or keys that joinscopesin the agent'sscopeclaim.supabaseMemory({ scopes })recalls and writes the user, organization and record scopes.validateExpression,queueScheduleProvider({ scopes, minIntervalMs, validateExpression, mirror }),queueDynamicSchedules({ notify, staleAfterMs })andaiScheduleDispatchmanage schedules, andmirrorwrites eve's schedules and occurrences toai_scheduled_tasksandai_task_runs.
Blocks and adapters
ai-chat: amodesoption adds a check constraint onmodeand narrows its type.memory:importMemoriescopies a table into archival memory, andarchival.upserttakesembeddingandembeddingModel.knowledge:position(offsets, page, heading) on chunks and hits,pdfExtractor,docxExtractorandextractors, andcreateUrlSourcewithresync,resyncAlland fetch guards.unpdfandmammothare new optional peers (>=2.2.1 <3and>=1.13.0 <2).ai-schedules: tasks have asourceand anexternalId, and the service functionsmirror,unmirrorandrecordRunlet another scheduler keep tasks and runs.aiBatchesacceptsoutput, and results carry each item's parsedoutputoroutputError.inboxAdapteraccepts reasoning chunks and keeps them out of the message a contact reads (reasoning: "metadata"stores them inmetadata.reasoning).vercelSandboxestakes typedmountsfor Vercel drives.vercelConnectCredentialstakesteamIdandorgId, andchannelConfigsupports"resend". The Flags SDK page documents running withoutFLAGS_SECRET.
- Peer ranges:
0.80.0 (2026-11-20)
-
Leave in approvals mode stamps the approval's decision on the request (
rejected_at,decided_by,decision_note, andcancelled_atwhen the approval is cancelled) asdecide_leave_requestdoes, andoptions.approvalSubjectnames the subject type its approvals are filed under. The approvals block takesoptions.requestColumns, which fills your own columns of requests a block files and wins over a caller'sfields. Expenses withstandaloneApprovalstakeselfDecideWhenTopOfChain. Time entries takeapprovalRequired, an app function that can skip the approval of a week, andselfApproveWhenTopOfChain, which approves a week at once when its owner is the only one who could decide it. Leave and expenses (withstandaloneApprovals) also takeapprovalRequired, which approves at once without filing an approval request. Time entries addwithdraw(withdraw_timesheet), which takes back a submitted week and cancels its approval request, and week events carry the approval id per employee too. The organizations client getssoleOwnedOrganizations, andoptions.soleOwnedPermissionnames the key that lets a caller ask about another member. Banking takesoptions.primary: "organization"for one primary account per organization andoptions.optionalCurrencyfor accounts without a currency.Behaviour changes to check:
sole_owned_organizations(member)no longer raises when a caller asks about another member. It returns the organizations where the caller may remove members, so an empty list means "no right to ask, or not a sole owner there", never "safe to remove".cancel_approvalon a leave request's approval now cancels the leave request too (cancelled_at,cancelled_by,leave_request.cancelled).- Leave in approvals mode records
leave_request.rejectedon a rejection, and its requests table gets the nullablerejected_at,decided_byanddecision_notecolumns. request_approvalrefuses the subject types leave, expenses and time entries file themselves (leave_requestorapprovalSubject,expense,timesheet) for anyone but the service role, withAPPROVAL_SUBJECT_BLOCK_FILED, and those blocks act only on the approval their own row points at.- A timesheet's status column of an enum type no longer fails when the approvals block decides the week.
- An app-owned timesheets table gets the unique index on organization, owner and week that
submit_timesheetupserts on, unless it already has one.
-
Add
better-supabase baseline build,applyandverify.buildreplays the migrations once and saves the schema, the migration history rows and, with--with-seed, the seeded rows and a storage tarball, keyed by a hash of the migrations and the tool versions.applyloads that snapshot into an empty local stack and runs only the newer migrations, and falls back to a full replay when the snapshot does not fit.verifychecks a restored database against a full replay. The migration history insupabase/migrationsis not touched.
0.79.0 (2026-11-20)
- Approval policy steps take
approvers.decider: true, so thedecideroption of the leave, expenses and time-entries blocks and leave'sselfDecideWhenTopOfChainwork with the approvals block, and time-entries gets adecideroption. Attachments takeon.<type>.upload: "subject"to make the subject row's own update policies decide who attaches and deletes files, and doctor BS345 accepts it. Organizations addsole_owned_organizations(member), which lists the organizations whose last owner a member is. Bank accounts get apositioncolumn thatsaveAccountsets and lists sort by. An app that keepsbank_accountsin its own table adds aposition integer not null default 0column before upgrading.
0.78.0 (2026-11-19)
SupportUnavailableErrornow carries the digestSUPPORT_UNAVAILABLE_DIGEST, so a Next.jserror.tsxcan recognise it. A support cookie that is not a UUID now counts as no session instead of a store outage. Support session ids must be UUIDs:support.startrefuses a store that returns another id, andtestSupportSessionStorechecks it.
0.77.0 (2026-11-19)
- API keys work without direct Postgres.
ServerOptions.apiKeyTokenmints a token for an API key's claims, andapiKeyTokenSigner({ key })frombetter-supabase/serversigns them as a short-lived ES256 JWT with a P-256 key the project trusts (imported as a standby signing key). Withoutpostgres, an API key'sctx.dbandctx.supabasethen run over PostgREST with that token, under RLS and the key's scopes, with the tenant inx-bsb-tenant.ctx.sqlisundefinedfor an API key withoutpostgresinstead of throwing, so the oRPC, Hono and MCP middleware no longer fail on it; readingctx.dbstill throws without either option, and the error names both. prune_deadlineswithpending_only => false(deadlines.forget) deletes satisfied history, so it now also checks the newpruneaction ofblocks.deadlines.permissions. It defaults to the keymanagemaps to (deadlines.manage); setpermissions.pruneto a key fewer roles hold to keep it narrower. Pruning pending deadlines, alone or withcomputeMany({ prune: true }), still needs onlydeadlines.write. A caller without the key getsDEADLINE_FORBIDDEN.- Authorization providers can set
functions.roleIn({role},{tenant}): whether a role belongs to a tenant, declared or a custom role the tenant owns. Withblocks.memberships.options.roles.manyunder the provider model, a trigger onmembership_rolesthen refuses any other role on every write, the service role's included, with SQLSTATE 23514 andMEMBERSHIP_ROLE_SCOPE, so a custom role of another organization can't be stored. Providers without the template keep today's behaviour. blocks.<name>.schedulesswitches a block timer off, such asconsents: { schedules: { expire: false } }. Doctor BS508 and the wiring checklist leave it out, andblockSchedules(blocks, { consents: { expire: false } })takes the same map so the scheduler leaves it out too.- The first jobs sent to a new queue at the same time no longer fail while two of them create the queue.
blocks.audit.options.subjectColumns.<column>.tableswith anidkey, such as{ "public.jobs": "id" }, falls back to the entry'srecord_id. Withrestricted: truethe log keeps no row data, sojob_idstayed null on the jobs table's own entries. Runbetter-supabase upgradeand generate a migration to rewrite the generated column.- Doctor BS213 no longer flags a tenant column that a composite foreign key with not-null columns ties to a parent row, such as
foreign key (job_id, organization_id) references jobs (id, organization_id), when every write policy checks one of the key's other columns, such asj.id = job_parties.job_idinside anexiststhat checks access to the job. - Doctor BS635 no longer suggests an
includeon a view that has the name of a table in another schema, such as apublic.membershipsview overbetter_supabase.memberships. A repository reads the view, which has no relations.
0.76.0 (2026-11-19)
-
A support session lookup now serves the lookups that follow it for one second, for the same admin and token, so a render that builds many contexts loads the session once instead of once per context. A stop, revoke or removed permission applies at once on the instance that ran it and within one second on every other instance. Concurrent lookups of the target's claims share one call, and a failed load is never reused. Each lookup that reaches the store counts as a
support_sessionscall in the request's database stats.supportSessions({ unavailable: 'throw' })makessupport.resolveandsupport.currentthrowSupportUnavailableErrorwhen the session or the target's claims can't be loaded, so an app can fail closed instead of running the request as the admin. The default,'admin', keeps answeringundefined.
0.75.0 (2026-11-19)
-
Calls an adopter looped or wrote by hand:
deadlines.computeMany({ items, prune })(compute_deadlines_many) computes up to 1000 subjects in one request and answers each item with its deadlines or its error; withprune, each subject's pending deadlines of other jurisdictions go first.deadlines.prune({ subjectType, subjectId, keepJurisdiction })anddeadlines.forget(subject)(prune_deadlines) delete a subject's pending deadlines of other jurisdictions, or all of its deadlines. A record type withcascade: truenow deletes its deadlines when its row is deleted.organizations.updateInvitationtakeschanges.onAccept(on_acceptonupdate_invitation) to replace the roles or teams an invitation grants on accept, with the checksinvitemakes.organizations.resendInvitations({ invitationIds })(resend_invitations) andteams.purgeMany(ids)(purge_teams) act on up to 1000 records in one request, all or nothing.blocks.audit.options.subjectColumns.<column>.tablesreads another key for one table's rows, so{ job_id: { type: "uuid", tables: { "public.jobs": "id" } } }fillsjob_idon the jobs table's own entries.
-
Access fixes from an adopter running an authorization provider with own and team level grants:
- A record type permission registered with
rows,ownerorcheckis now checked on the record's row by theattachmentsupload and manage checks, so a member whose key covers only their own or their team's records can attach files to those records (ADR 1094). Thedeadlinesread checks let such a member read the deadlines of the records the grant reaches whenblocks.deadlines.permissions.readis the record type's read key. Plain keys are checked in the tenant as before. import_note_issue,import_note_warningsandimport_clear_issuesare revoked frompublic,anonandauthenticated; only the import functions call them.- The
contacts,imports,teamsandnotificationsfunctions check the service role with the sharedSERVICE_CALLERcheck instead of the deprecatedauth.role(), so a direct admin connection passes as it does in the other blocks. team_membershas a composite foreign key(tenant_id, team_id)toteams, so a member row can't point at another tenant's team.teams,companies,people, the contactlocations,bank_accountsandchannelstables,attachmentsandledger_transactionsget a unique(tenant_id, id)index, so app tables can reference them with a composite foreign key (doctor BS217). An upgrade fails on an existingteam_membersrow whose team is in another tenant; move or delete it first.blocks.organizations.permissions.readPlatformnames a platform key whose holders read every organization through the table's read policy.
- A record type permission registered with
-
BS386 and BS206 say that a select policy on a table's own rows keeps the per-row call as the
orfallback after a set helper, since the set misses a row the statement inserts andinsert ... returningfails. -
Doctor false positives from an adopter:
- BS112 counts a call to the access contract (
better_supabase.can,can_user,is_platform,tenant_ids_with) or to a function in a schema of the authorization provider's functions as a caller check. - BS633 skips row triggers whose function lives in a schema of the authorization provider's functions; they guard the provider's own rows and must run during an import.
- BS634 and BS635 no longer suggest an
includethrough a view, whose generated table has norelations. - BS627 reads a raise's whole
usinglist, so a hint on the fourth or later line counts.
- BS112 counts a call to the access contract (
-
ctx.supabase.auth.oauth.listGrants()andrevokeGrant({ clientId })work on a request context (bsb.context()in Next.js, Hono and the other adapters). The context client holds the caller's access token but no Auth session, so supabase-js answered both withAuthSessionMissingError; they now send the token to Supabase Auth's/user/oauth/grantsand return the same{ data, error }shape.
0.74.0 (2026-11-19)
-
Expense, invoice and leave follow-ups:
- An expense without a creator, such as a company expense the service role recorded, no longer counts every decider as its creator (ADR 1093). Before, two or more approvers each saw the other as someone else who could decide, so nobody could decide it. A service caller acting for a user must now pass
createdBy; without it the user who recorded the expense may decide it unless they are its owner. An expense with a creator keeps the rule that its owner or creator decides only when nobody else can. recomputeStatus(invoiceId)(recompute_invoice_status(invoice uuid)) derives an issued invoice's status, paid total and credited total from its ledger payments, imported allocations and issued credit notes, includingcreditedwithoptions.creditedStatus, so an app never writes the status itself. The paid total never drops below the stored one, so an import's row settlement keeps its total. A draft, void or uncollectible invoice keeps its status but gets its totals rewritten, andinvoice.paidis recorded only for an invoice that was never paid. It also restores invoices whose credit notes were voided before 0.73. Needsinvoices.manage, orinvoices.purchasefor a purchase invoice.requestSelfDecides(requestId)(leave_request_self_decides(request_id uuid)) tells whether the caller decides a leave request as its requester underoptions.selfDecideWhenTopOfChain, anddecide_leave_requestuses the same function.
- An expense without a creator, such as a company expense the service role recorded, no longer counts every decider as its creator (ADR 1093). Before, two or more approvers each saw the other as someone else who could decide, so nobody could decide it. A service caller acting for a user must now pass
0.73.0 (2026-11-18)
-
Breaking: 51 state refusals in 26 block modules move from SQLSTATE
55000toPT409, so PostgREST answers HTTP 409 instead of 500 andmapDbErrorreturns aconflicterror. The hints are unchanged:EXPENSE_LOCKED,EXPENSE_TRANSITION_INVALID,EXPENSE_REPORT_LOCKED,EXPENSE_IN_APPROVAL,LEAVE_REQUEST_CLOSED,IMPORT_RUN_NOT_RUNNING,TIME_TIMER_RUNNING,TIME_ENTRIES_TIMESHEET_APPROVED,TIME_ENTRIES_TIMESHEET_SUBMITTED,WEBHOOK_DELIVERY_IN_PROGRESS,LEDGER_ALREADY_REVERSED,ACCOUNTING_ENTRY_REVERSED,PERIOD_CLOSED(fiscal year already closed),INVOICE_ALREADY_APPROVED,INVOICE_NOT_DRAFT,INVOICE_PAYMENT_REVERSED,INVOICE_ALREADY_HANDED_OVER,ACTIVITY_ALREADY_MARKED_ERROR,AGENT_MANDATE_USED,ASSETS_DISPOSED,ATTACHMENT_NOT_CLAIMABLE,DECISION_SUPPORT_ALERT_STATUS,DSAR_CLOSED,DSAR_EXTENDED,DOCUMENT_SUGGESTION_CLOSEDandSHIPMENT_PROOF_RECORDED. Code that catches55000for them must catchPT409.Expense and approval follow-ups to ADR 1090 (ADR 1091):
- The expenses guard stamps
createdBywith the caller on a client's insert and refuses a client's change to it. The service role names a creator withcreateExpense({ createdBy })orfields.created_by; other trusted writers keep theirs, else the caller or the owner is recorded. The upgrade migration (expenses module version 2) backfillscreated_bywith the owner's user on older rows; a row whose owner has no user keeps a null creator. An expense without a creator counts the decider as its creator, so it is decided or reopened only when nobody else can. reopenExpenselets the owner or creator reopen when nobody else can decide, likedecideExpense.expenseSelfDecidesMany(ids)(expense_self_decides_many,uuid[]) answersexpenseSelfDecidesfor a whole list in one call.options.deciderlets an app function decide standalone expenses, as in the leave block, and makes the "nobody else can decide" rule count the active managers up the owner's chain.options.invoicedChecknames an app function(expense_id uuid) returns boolean, so an expense on a cancelled invoice can be reopened.- An approval policy snapshot takes
excludedUserIds: those users leave the approvals queue, the notifications and the required-all holders, and their decision is refused. Standalone expenses exclude the creator while someone else can decide. - Expense reports and lines get the guard triggers of standalone expenses: no client writes to the stamp columns or the owner, only the allowed transitions, the decider stamped, and owner, currency and lines frozen once approved (for a client, once submitted). These guards also apply to the service role and
postgres: a seed or import that adds lines to an approved report must insert the lines before approving it, or disable the trigger for its transaction as the expenses docs describe under Decision rules.
- The expenses guard stamps
-
The invoices block takes
options.creditedStatus: true, which moves an invoice whose credit notes cover its total and charges to a closedcreditedstatus instead ofpaid, unpaid or paid, without aninvoice.paidevent. Behaviour changes for every adopter:invoice.paidis recorded only when an invoice moves topaid; a credit note on an invoice that was already paid no longer records it again.- Voiding an issued credit note gives its credit back and moves the original invoice to the status its balance gives (for example
paidback toissued), with or withoutcreditedStatus, and a state machine over the invoices table records thatstatus.changed. Credit notes voided before this release are not restored retroactively. - The status update after a payment or credit no longer clears the row it reports on when the invoice isn't in a settling status, so
invoice.creditedalways carries the organization and invoice id.
0.72.0 (2026-11-18)
-
Expenses without reports keep their decision rules in the database (ADR 1090). Behaviour changes:
- A trigger on the expenses table stamps
decidedBy,decidedAt,reimbursedByandreimbursedAt, clears the decision when an expense goes back to submitted or draft, and refuses a client's own write to the status or those columns. A client's new row starts as a draft. - The status moves only along the allowed transitions; an approved or reimbursed expense never goes straight to draft (
EXPENSE_TRANSITION_INVALID). - The owner and the creator (
createdBy) can't approve or reject an expense unless nobody else can decide it (another approve key holder, or withapprover: "manager"the owner's direct manager), as the leave block'sselfDecideWhenTopOfChainrule. The audit entry carriesselfDecided. WithstandaloneApprovals, the creator's decision of the approval request is refused too. - Only the owner resubmits a rejected expense.
- The amount, currency, category and owner are frozen once approved, and against a client's own write once submitted; the owner changes only in draft, and a client needs the create or update key for it.
reopenExpense({ expenseId, reason })takes an approved expense back to submitted, andreverseExpenseReimbursement({ expenseId, reason })takes a reimbursed one back to approved; both keep the reason in the audit and recordexpense.reopenedandexpense.reimbursement_reversed.options.invoicedColumnmakesreopenExpenserefuse an invoiced expense.options.withdrawApprovedis removed:withdrawExpenserefuses a decided expense withEXPENSE_ALREADY_DECIDED. Reopen it instead.permissions.withdraw(default theupdatekey) now governs withdrawing someone else's submitted expense, not only an approved one.reopenExpenserefuses the owner and the creator.- State conflicts (
EXPENSE_ALREADY_SUBMITTED,EXPENSE_ALREADY_DECIDED,EXPENSE_ALREADY_OPEN,EXPENSE_ALREADY_REIMBURSED,EXPENSE_NOT_REIMBURSED,EXPENSE_INVOICED) raise SQLSTATEPT409, which PostgREST answers with 409 andmapDbErrormaps to aconflicterror. expenseSelfDecides(id)(expense_self_decides) and the leave block'sselfDecides(organizationId)(leave_self_decides) tell an app whether the caller decides their own record.
- A trigger on the expenses table stamps
0.71.0 (2026-11-18)
-
Managers whose employee record has an
end_datebefore today lose their decision rights, as offboarded managers already do. This applies to the manager step of the approvals block and to the direct decide functions of leave, time entries and expenses. Requests such a manager would have decided now go to the fallback approvers: in the direct decide functions, the members who hold the block's approve permission; in the approvals block, the step's other approvers or, once it escalates, itsescalateToapprovers. Runbetter-supabase upgradeand generate a migration to pick up the change.The leave block's
options.selfDecideWhenTopOfChainnow lets a requester with the approve permission decide their own request only when nobody else can decide it. Before, any approver without a manager could approve their own leave, even with other approvers in the organization, and an owner whose manager was offboarded or had no login was refused. Now another active member who holds the approve permission, or an active manager with a login whom the block lets decide (the direct manager underapprover: "manager", or anyone up the chain with adecider), blocks the self-decision. The option needs an access model that answers for other users: a custom model needsfunctions.canUser, and a provider needsidsWithForandisPlatformFor. Otherwise rendering the block fails.
0.70.0 (2026-11-17)
-
Doctor BS213 no longer reports a column that a row-level
beforetrigger protects, once the trigger's comment names it withbetter-supabase:guards(column, ...). Snapshots now record the marker and whether each trigger is disabled. -
The leave block takes
options.selfDecideWhenTopOfChain. Withapprovals: false, a requester who holds the approve permission and has no manager above them in the employees block may decide their own request throughdecide_leave_request. It is off by default. -
Audit entries, ledger transactions and accounting entries that blocks write now keep a translation key and its raw values next to the English text (
summaryKeyandsummaryParams,memoKeyandmemoParams), so an app can word them in its own locale.BLOCK_MEMO_MESSAGESlists every memo key with its English text. The Englishsummaryandmemoare unchanged. The audit module moves to version 15 and the ledger module to version 3; runbetter-supabase upgrade.audit_event,audit_event_trustedandledger_posttake two new trailing arguments, and the upgrade drops their old signatures. Calls by name or by position keep working. Only custom grants or comments on the old signatures, or views and functions that depend on them by signature, need attention: grant or comment again on the new signature. -
Doctor BS206 now sees
col in (select f())as a wrapped call when Postgres prints the helper without its schema, as it does for a function inpublic. -
Doctor BS345 now says what its finding means since it checks uploads only: readers of a record can attach files to one they can't change. It names both places to set the upload key.
-
Entity list pages, such as the inventory block's
movementPage, takeoffsetandtotal: trueand return the decodedtotalandtotalCapped. -
PowerSync uploads now replay for tables that load on first use. Before,
createUploadConnectoranduploadRouterefused every queuedPUTandPATCHon such a table asunsupportedand dropped the change, because the lazy repository answeredfalseto"upsert" in repository. A lazy repository now answers theinoperator like its getter: before the table loads every method name is present, and after it loads the built repository answers. -
The ledger read policy now correctly exposes a whole transaction to a member who can read one of its entries. It compared each entry with itself instead of with the transaction, so members without
ledger.readread no transactions at all. They now read every transaction that moved an account they can read; the transaction's entries on other accounts stay hidden unless they can read those accounts too. -
Blocks no longer create an index that already exists. Two block statements that build the same index, such as the
invited_byindex of tenant and platform invitations sharing one table, now render once. Over an adopted table, a partial orginindex is left out when the app's index has the same method, columns andwhere, and an app index that only shares its name with a block index (such asteam_members_user_idx) now counts as the app's, soteam_members_membership_idxandwebhook_endpoints_types_idxno longer duplicate the app's indexes and doctor BS200 stops reporting them.
0.69.0 (2026-11-17)
- The inventory movement list takes a
productIdfilter, and each movement carries itsproductId,unit,reason,noteandactorId. - A refused invoice action now answers
INVOICE_FORBIDDENto a caller who sees the invoice through the invoices table's own select policies, not only through thereadkey, so readers whose permission has row conditions no longer getINVOICE_NOT_FOUND. The prelude addsbetter_supabase.row_visible(rel, column, value)for the same decision in your own functions. blocks.leave.options.decidernames an app function(request_id uuid) returns booleanthat lets more callers decide a request throughdecide_leave_request, such as every manager up the requester's reporting chain. The database enforces it, and the requester still never decides their own request.- Doctor BS219 ignores a negated
?and one insidecase, BS345 checks only the upload key because the attachments read policy already checks the subject row, and BS346 accepts anonentry that carries its owntable. - Doctor reports fewer false positives: BS107 skips commands the API roles hold no privilege for, BS117 is info when
anonholds no privilege on the table, BS204 accepts an expression index led by the tenant column, BS205 is info on an insert-only policy, and BS206 countsunion allbranches andfrom helper('k') t(id)with constant arguments as once per statement. - Doctor BS112 now counts a call to
better_supabase.is_service_role()as a caller check, so a security definer function that only the service role may run is no longer reported.
0.68.0 (2026-11-16)
audit()takesarchive_columnandarchive_value, so an update that sets or clears a soft-delete or status column is recorded as<entity>.archivedor<entity>.restoredinstead of<entity>.updated. Block tables with anarchivedAtcolumn pass it on their row audit trigger. The audit module moves to version 14; runbetter-supabase upgrade.- Add
blocks.invoices.permissions.settle, a second key that may record a positive payment for an invoice's whole open balance (or replay one already recorded) but not a part, so a "mark paid" permission works next to a finer "record payment" one. Without it, payments checkpaymentas before. - Add
better_supabase.is_service_role()to the prelude: true for theservice_rolekey and a direct admin connection, so your own service-only SQL functions call one helper instead of copying theauth.jwt() ->> 'role'check. - Doctor BS628 now reads only the ORDER BY clause of a list function, so a column selected after an inner
order byand anorder by ... limit 1that picks one row no longer report a missing cursor index. - Invoice actions (
record_invoice_payment,issue_invoice,update_invoice,set_invoice_lines,delete_invoice,archive_invoice,restore_invoice,add_invoice_charge,credit_invoice,void_invoiceandwrite_off_invoice) now answer a caller who can read the invoice but lacks the action's key withINVOICE_FORBIDDEN(42501, aforbiddenerror) instead ofINVOICE_NOT_FOUND. A caller who can't read the invoice still getsINVOICE_NOT_FOUND, now with the message "no such invoice you can read" (it was "no such invoice you can edit", "delete" or "manage"); match on the hint, not the message. The permission check runs before the row lock, so a caller without access locks nothing.
0.67.2 (2026-11-16)
- Doctor BS504 no longer asks for
CRON_SECRETwhen no app source names it. The billing, outbox and queue routes take the secret from the app, so an app that authenticates its cron routes another way, such ascaller: "vercel-schedule", doesn't need the key. - Doctor BS601 now only warns about a peer outside its range when the project's
package.jsonor a package of its workspace lists it, so packages that another dependency installs for itself, such asundiciorvue, no longer raise it. - Doctor BS512 now finds the
schedule/v1betatrigger of a schedule that names aservicein that service'sfunctions, and matches a function by its route file (app/api/drain/route.tsforapi/drain), so it no longer warns about a schedule that is wired. - The ledger upgrade from version 1 no longer fails with
LEDGER_APPEND_ONLYon a database that has ledger entries: the step that copieseffective_atfrom each transaction turns the append-only trigger off for that one statement and back on in the same block. - A text list filter, such as
statusonlist_teams,page_employeesorpage_invoices, now compares the column as text, so it works when the app keeps that column as an enum or a domain instead of failing with "operator does not exist". A text column keeps using its index; an index on an enum column does not serve the filter. Runbetter-supabase upgradeto rewrite the block functions. - The generated permission list now has every optional key a block checks when you set it:
purgefor teams, employees, time entries, activities, agents, announcements, care rules, courses, field definitions, enrollment programs, forms, funding claims, maintenance plans, meetings, posts and score models, the finer quote keys (send,accept,reject,requestChanges,withdraw) andimpersonation.approve. Teams no longer listdelete, which becamepurgein 0.67. - The template guard triggers of tasks, quotes and invoices now fix their
search_path, so doctor no longer reports BS100 for them.
0.67.1 (2026-11-16)
add --adoptwrites a block's data statements again when an upgrade step since the version an earlier data migration recorded asks for it. The search 2 to 3 upgrade does, so the adopted migration carriessearch_reindex()again and existing documents get theirfacetsandsort_key.codemod namingkeeps the check constraints the app's own schema files and seeds name on block tables (alter table better_supabase.profiles add constraint profiles_locale_check ...). Itsbsb_loop renamed them, and the next schema diff renamed them back.better-supabase codemodskips a folder that holds its own.git, such as a linked git worktree inside the project, so it no longer rewrites another checkout's files.- Leave request notes are private:
list,requestPageandgetreturnnoteonly to the requester, their manager and members withleave.approveorleave.manage, andnullto other readers, andqno longer matches notes the caller can't read.get_leave_requestchecks the caller itself instead of relying on the table's read policy. A block table listed inexposekeeps the privileges the grants module writes: the block no longer adds its own table-wide select grant, soselect(*, -note, -decision_note)closes direct reads of the note columns. - Ledger version 2:
upgradeaddsledger_entries.effective_atand copies it from the entry's transaction, so entries posted before the column keep their transaction's time instead of the upgrade time. Runbetter-supabase upgradeand apply the migration. upgrade --preserve <file>writes the new render to<file>.new, keeps the hand-edited file, and writes the other blocks. The path never matched the planned one, so it skipped the file, wrote no.newand stopped the rest.
0.67.0 (2026-11-16)
-
Breaking:
agentsgetsarchiveandrestore, and the hard delete of an agent ispurge, behind its ownpermissions.purgekey (it falls back toagents.moderate, and the owner needs it too). An archived agent leaves the store andlist, andupdate,publish,installandraterefuse it withAGENT_ARCHIVED; its installs, ratings and skills stay.listtakesincludeArchived, andAgentcarriesarchivedAt.Before After agents.remove(id)agents.purge(id)delete_agent(id)purge_agent(id)event agent.deletedevent agent.purgedlist_agentswith 4 argsa fifth argument, include_archivedNew events are
agent.archivedandagent.restored. Runbetter-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
prompts,ai-evalsandai-guardrailsgain a page read each:prompts.list,datasets.listandpolicies.list. They takeorganizationId,limitandafter, return aListPageand go throughaccesslike the other methods.prompts.listreturns each name with its latest version, version count and labels;datasets.listadds item and run counts;policies.listreturns the policies an organization saved, ordered by agent and stage. They are backed by the newlist_prompts,list_eval_datasetsandlist_guardrail_policiesSQL functions, whichbetter-supabase upgradewrites into the modules: run it and apply the migration it generates. A hand-written implementation of thePrompts,AiEvalsorAiGuardrailsinterface needs the new method. -
ai-chatgainsruns.usageByUser({ organizationId, since?, until?, limit? }), which returns runs, failed runs, tokens and cost per user across an organization, most expensive first.ai_runsstays readable by its owner only; the read needsai_chat.managein the organization (or the service role) and fails withAI_CHAT_FORBIDDENotherwise. It is backed by the newai_usage_by_userSQL function, whichbetter-supabase upgradewrites into the module: run it and apply the migration it generates. -
invoices,risks,shipmentsandbookingsget an archive and a restore, so a record that cannot be deleted can leave the lists and come back.Block New methods New events Rule invoicesarchive(invoiceId),restore(invoiceId)invoice.archived,invoice.restoredany status; needs the opt-in archivedAtcolumnrisksarchive(riskId),restore(riskId)risk.archived,risk.restoredany status; needs risks.manageshipmentsarchive(id),restore(id)shipment.archived,shipment.restoreddelivered, returned or cancelled; the archivedlist filter shows thembookingsarchive(bookingId),restore(bookingId)booking.archived,booking.restoredcancelled or ended; listtakesincludeArchivedshipmentsandbookingsget anarchived_atcolumn,ShipmentandBookingcarryarchivedAt, andlist_bookingstakes a fifth argument,include_archived. An app table made before the column mapsarchivedAt: nullincolumns.shipmentsorcolumns.bookingsto leave the pair out. Runbetter-supabase upgradeand apply the migration. -
Breaking: announcements can be archived and restored, and their hard delete is
purge, behindpermissions.purge(ADR 1042). Archived announcements leavelistActiveandlist;list({ includeArchived: true })adds them.Before After announcements.remove(id)announcements.purge(id)delete_announcement(id)(SQL)purge_announcement(id)event announcement.deletedevent announcement.purgedlist_announcements()(SQL)list_announcements(include_archived)Run
better-supabase upgradeand apply the migration, which addsarchived_at. See the 0.66 to 0.67 guide. -
Breaking: maintenance plans and funding claims can be archived and restored, and their hard delete is
purge, behindpermissions.purge(ADRs 1043 and 1044). An archived maintenance plan is never due and opens no work order. Only a claim the funder answered is archived; a draft claim is purged.Before After maintenance.deletePlan(id)maintenance.purgePlan(id)delete_maintenance_plan(id)(SQL)purge_maintenance_plan(id)event maintenance_plan.deletedevent maintenance_plan.purgedfunding.deleteClaim(id)funding.purgeClaim(id)delete_funding_claim(id)(SQL)purge_funding_claim(id)event funding_claim.deletedevent funding_claim.purgedlist_funding_claims(tenant, ...)list_funding_claims(tenant, ..., include_archived)Run
better-supabase upgradeand apply the migrations, which addarchived_at. See the 0.66 to 0.67 guide. -
Breaking: meetings and courses can be archived and restored, and their hard delete is
purge, behindpermissions.purge(ADR 1045). A held or cancelled meeting is archived and an archived meeting takes no changes. A course archives through itsarchivedstatus and restores as a draft, so no column is added for it.Before After meetings.delete(id)meetings.purge(id)delete_meeting(id)(SQL)purge_meeting(id)event meeting.deletedevent meeting.purgedcourses.delete(id)courses.purge(id)delete_course(id)(SQL)purge_course(id)event course.deletedevent course.purgedRun
better-supabase upgradeand apply the migration, which addsarchived_atto meetings. See the 0.66 to 0.67 guide. -
Breaking: posts can be archived and restored, and their hard delete is
purge, behindpermissions.purgewhen you set it (ADR 1078). An archived post leaveslistunlessarchivedis set and takes no votes, replies or edits.Before After posts.delete(id)posts.purge(id)delete_post(id)(SQL)purge_post(id)event post.deletedevent post.purgedRun
better-supabase upgradeand apply the migration, which addsarchived_atto posts. See the 0.66 to 0.67 guide. -
Breaking: products and variants can be archived and restored, and their hard delete is
purge, behindpermissions.purge(ADRs 1048 and 1049). Archive and restore use the existing status, with no new column.channelProductshides archived products unlessarchivedis set, and an archived variant can't be added to a cart.Before After catalog.deleteProduct(id)catalog.purgeProduct(id)delete_product(id)(SQL)purge_product(id)catalog.deleteVariant(id)catalog.purgeVariant(id)delete_variant(id)(SQL)purge_variant(id)event product.deletedevent product.purgedevent product_variant.deletedevent product_variant.purgedblocks.catalog.permissions.deleteblocks.catalog.permissions.purgeRun
better-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
Breaking: time entries and activities can be archived and restored, and their hard delete is
purge, behindpermissions.purge(ADRs 1046 and 1047). An archived time entry leaves lists, timesheet totals, billing, costing, payroll and metrics and never blocks an overlap. An archive, restore or purge in a submitted or approved week fails withTIME_PERIOD_LOCKED, so an entry is never restored into a locked period. An archived activity leaves the timeline, next step, open list, search and recordings and takes no changes.Before After timeEntries.remove(id)timeEntries.purge(id)delete_time_entry(id)(SQL)purge_time_entry(id)event time_entry.deletedevent time_entry.purgedactivities.remove(id)activities.purge(id)delete_activity(id)(SQL)purge_activity(id)event activity.deletedevent activity.purgedRun
better-supabase upgradeand apply the migration, which addsarchived_atto time entries and activities. See the 0.66 to 0.67 guide. -
Bulk, export, import targets and long calls now share one shape.
bulk(ids, action, options)returns{ succeeded, failed: [{ id, error }] }with a declared limit (500 by default,BULK_TOO_MANYbeyond it): thebulk-actionsblock has it, andbulk,checkBulkLimitandBulkReportare exported frombetter-supabase/blocksfor blocks that migrate their*Manymethods. A list built withentityListgainsexport(options), a CSV stream over the same filters aspage, andexportCsvandexportResponseturn anypageinto a download route. A manifest declaresimportTarget(fourteen blocks do), andimportTargetsOffrombetter-supabase/blocks/importslists every block that can take rows. Long calls return{ jobId }:bulk-actionshasstartJob,bulk-actionsandimportsexpose ajobssource, andcreateJobsreads any of them through onejobs.get(jobId)result. The organizations module addsupdate_member_rolesandorganizations.updateMemberRoles, which change many roles in one call with the checks of the single call.Run
better-supabase upgradeand apply the migration it generates to getupdate_member_rolesin an installedorganizationsblock. Nothing is removed, so no code changes are needed. -
An app entity page in
gen.entityPagescan list the blocks whose screen it is withapp: { blocks: ["deals", "pipelines"] }.pageCoveragelists the page's route under each block, so the app's coverage map no longer repeats it; a page withoutblockswrites no entry, as before.defineEntityPagerefuses a blank block name. Runbetter-supabase gento rewritepageCoverage. -
PageOptions.sortnow accepts a list of up to three sorts as well as one. The list query of an entity page (defineEntityListQuery) readssort=a:asc,b:descor repeatedsortparameters, checks each term against the entity's declared sorts, and writes the list back intoSearchParams. Blocks still order by one declared sort, so theirpageorders by the first term and returnssorted: { applied, ignored }with the terms it left out; the keyset cursor is the cursor of the applied term.PageSort,SortReport,sortsOfandMAX_PAGE_SORTSare exported frombetter-supabase/blocks. A page declared ingen.entityPagescan list the multi-column sorts it offers insortLists;genwrites a composite index for each, and doctor rule BS636 reports a list without it. A custompagethat readsoptions.sort.bymust readsortsOf(options.sort)instead. NoapiVersionchanges. -
Record the admin behind an impersonated call on block events. While a support session runs, every block event and row mutation event carries
impersonatedBy(the admin) next toactorId(the impersonated user),blockCloudEventputs it indata.impersonatedBy, andauditSinkwrites it as the audit entry'simpersonatedBy. Nothing changes for calls outside a session. -
Enforce an entity's flag key and page the open invitations. An entity that sets
flaginEntitySurfacenow lists themethodsthe flag hides, andcreateBlocks({ flags })returns anot_founderror from those methods while the flag is off (entityFlagHooksbuilds the hooks). The organizations client getsinvitationsPage,invitationsFacetsandinvitationsCountwith therolefilter, theexpiresAtandemailsorts and a search over the email. -
Page the open invitations in SQL. The organizations module adds
page_organization_invitations(tenant, filters)next tolist_organization_invitations, which stays unchanged, soupgradeadds one function and no table change.invitationsPage,invitationsFacetsandinvitationsCountread it, andOrganizationsOptionsacceptstenant, so a call withoutorganizationIdreads the request's tenant. An entity page fororganizations.invitationnow generates its list route and columns. -
Declare the offline rules in the manifest.
EntitySurface.offlinenow accepts{ scope, where, systemRows }next totrue, andbetter-supabase powersync streamsreads them for the teams, profiles, observations, medications and activities streams. The generated sync streams are unchanged. The notification, membership and attachment streams keep their joins in the generator. -
Mark which block events are public.
event<T>({ public: true })records the event inEvents.public, andwebhookEventCatalog(blocks)frombetter-supabase/blockslists them by block, so an app offers webhook subscribers only those.organizations,shipments,invoicesandordersmark their events. The manifests of the blocks thatpowersync streamssupports now declareoffline: trueon their entity. Nothing changes for an app that ignores both. -
Breaking: the Next.js sign-in flows (
signInWithPassword,verifyOtp,signInWithOAuth,exchangeCodeForSession, the email flows,verifyMfaandsignOut) now call auth-js on acreateServerClientfrom@supabase/ssrinstead of the Auth endpoints directly, so the session and PKCE cookies are the ones@supabase/ssrwrites. Flows the browser client starts can finish inexchangeCodeForSession.Before After passwordGrantfrombetter-supabase/serversignInWithPasswordon acreateServerClienterror code code_verifier_missingpkce_code_verifier_not_found(auth-js)verifier cookie httpOnly, 10 minutesthe auth-js verifier cookie @supabase/ssrwritesSignInWithOAuthParams.provider: stringProviderfrom@supabase/supabase-jsA link from a flow started before the upgrade fails the exchange once; ask the user to request a new one.
-
Adds
testBlockListtobetter-supabase/testing: one conformance helper for the block list contract (ADR 1077). It runs a block entity'spage,count,facetsandgetover seeded rows and checks the keyset walk, the limit, each sort and a list of sorts, an array filter,q, the counts andgetfor an unknown id. No call is renamed or removed. Each block family adopts the contract in its own change. -
drive.bulkShare(items),filespace.bulkShare(input)andcustomFields.bulkSet(input)give each row its own value and return the common{ succeeded, failed }report, named by node id,type:idprincipal and field key. They take at most 500 rows and do not stop at the first failure; a repeated id fails withBULK_DUPLICATE_ID.drive.shareMany,filespace.shareManyandcustomFields.setManyare deprecated and removed in 0.70. They keep working and keep stopping at the first failure.Old New drive.shareMany({ ids, grants })drive.bulkShare(ids.map((id) => ({ id, grants })))filespace.shareMany({ id, ... })filespace.bulkShare({ id, ... })customFields.setMany({ subject, inputs })customFields.bulkSet({ subject, inputs }) -
Rename two types of the bulk call to names that follow the naming vocabulary.
BulkOptionswas the retired name ofBulkActionsOptions, andFailureis a banned type suffix. Both types shipped in the same unreleased version asbulk, so no released code changes.BULK_TOO_MANYis now a shared hint code, becausebulk-actions,organizationsandtasksraise it.Old New BulkOptionsBulkCallOptionsBulkFailureBulkItemError -
The calendar block gains
calendar.bootstrapand the SQL functioncalendar_bootstrap, which read a calendar page in one database call: the organization's calendars, the occurrences of a range, the occurrences of a second range and the caller's reminders on events. Runbetter-supabase upgradeand apply the migration it generates to get the function in an installed block.searchalso stops computing a full-text rank for rows that only the trigram index matched, which halves its time on a corpus where most documents match by trigram; its results and scores do not change. -
carePlans.restore(planId)brings an archived care plan back as a draft and recordscare_plan.restored. The plan's actions stay ended, so add the actions the client needs before you publish it again. A plan that is not archived is returned unchanged. It needscare_plans.publish. Runbetter-supabase upgradeand apply the migration. -
Breaking:
clinicalDecisionSupportgetsarchiveRuleandrestoreRule, and the hard delete of a rule ispurge, behind its ownpermissions.purgekey (it falls back toclinical_decision_support.manage). An archived rule leavesrulesand the evaluation, andsaveRulerefuses it withDECISION_SUPPORT_RULE_ARCHIVED; alerts it raised stay until the next evaluation resolves them.rulestakesincludeArchived, andCareRulecarriesarchivedAt.Before After clinicalDecisionSupport.deleteRuleclinicalDecisionSupport.purgeRuledelete_care_rule(rule_id)purge_care_rule(rule_id)event care_rule.deletedevent care_rule.purgedlist_care_ruleswith one argumenta second argument, include_archivedNew events are
care_rule.archivedandcare_rule.restored. Runbetter-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
The lims module adds
list_qualified_instruments(tenant, on_date), which returns the asset ids that holdoptions.instrumentQualificationon a day, and the lims block's client calls it throughlims.listQualifiedInstruments({ on }). A result form no longer asksinstrumentStatusonce per asset. Without the option the list is empty. Withoptions.recognition: true, the accounting module addslist_revenue_recognition_schedules(tenant, limit_count), which returns every revenue recognition schedule of the organization with its row count and the amount already recognized, so a list of schedules needs no hand-written read policy. Both functions need the block's read permission.Run
better-supabase upgrade. -
Breaking:
custom-fieldsgetsarchiveDefinitionandrestoreDefinition, and the hard delete of a field definition ispurgeDefinition, behind its ownpermissions.purgekey (it falls back tocustom_fields.manage). An archived field leaveslistDefinitions, andsaveDefinitionandsetValuerefuse it withCUSTOM_FIELD_ARCHIVED; its values stay and stay readable.listDefinitionstakes{ entity, includeArchived }, and a definition carriesarchivedAt. The normalized layout has the column and functions; the inline and keyed layouts have no definition rows.Before After deleteDefinition(id)purgeDefinition(id)delete_field_definition(id)purge_field_definition(id)event field_definition.deletedevent field_definition.purgedlist_field_definitionswith 2 argsa third argument, include_archivedNew events are
field_definition.archivedandfield_definition.restored. Runbetter-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
Blocks can declare plan limits and meters. A manifest's new
limitsandmetersname the methods that check ausagequota before they run (they returnquota_exceededwith themeterandlimit) and the meter a successful call records. Turn it on withcreateBlocks({ metering: true })with theusageblock in the set; it is off by default.usagenow provides ameterport,organizations.invitedeclares a limit onseats, andapi-keys.createa limit and meter onapi_keys_created.BlockQuotais the one shape of aquotaoption (blocks.drive.options.quota). No option or error code is renamed. -
dispatchandshipmentsgetgetOrNotFound(id), which returns the row or anot_founderror (DISPATCH_NOT_FOUND,SHIPMENT_NOT_FOUND) as the block list contract asks (ADR 1077).get(id)keeps returningnullfor a missing row, so apiVersion 1 does not change, and is marked@deprecated.Before After dispatch.get(id)(null)dispatch.getOrNotFound(id)shipments.get(id)(null)shipments.getOrNotFound(id) -
doctorchecksSUPABASE_JWKS. BS509 reports an env file whoseSUPABASE_JWKSis not JSON or holds no key with akty, whichloadEnvwould reject. BS503 now also runs when the shell exports onlySUPABASE_JWKS, and warns that those inline keys override the running stack'sSUPABASE_JWKS_URL. The auth env page shows how to fill the variable withcurl <url>/auth/v1/.well-known/jwks.json. -
The domains block takes a hosting platform.
createDomainsAdmin({ provider })accepts a versionedDomainProvider(add,verify,remove,status) and gainsadd({ hostnameId }),remove({ hostname })andstatus({ hostnameId }). With a provider,verifyasks the platform after the TXT check passes and fails withDOMAIN_PROVIDER_UNVERIFIEDuntil it agrees; without one, it behaves as before.vercelDomainProvider(new Vercel({ bearerToken }), { projectId, teamId })implements it over@vercel/sdk, an optional peer, andtestDomainProviderinbetter-supabase/testingchecks your own. -
Breaking:
drivegetsarchiveDriveandrestoreDrive, and the hard delete of a drive ispurgeDrive, behind its ownpermissions.purgekey (it falls back todrive.manage) and only for an archived drive. An archived drive leavesdrives(), and it refuses new items, a rename and a share withDRIVE_ARCHIVED; its content stays and stays readable.drives()takesincludeArchived, and a drive carriesarchivedAt. A legal hold still blocks the purge.Before After deleteDrive(id)archiveDrive(id), thenpurgeDrive(id)drive_delete_drive(id)drive_purge_drive(id)event drive.deletedevent drive.purgeddrive_list_driveswith 3 argsa fourth argument, include_archivedNew events are
drive.archivedanddrive.restored. Runbetter-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
Breaking:
enrollmentsgetsarchiveProgramandrestoreProgram, and the hard delete of a program ispurgeProgram, behind its ownpermissions.purgekey (it falls back toenrollments.manage) and only for an archived program. An archived program leavesprograms(), andenrollandsaveProgramrefuse it withENROLLMENTS_PROGRAM_ARCHIVED; its enrollments stay.programs()takes{ includeArchived }, and a program carriesarchivedAt.Before After deleteProgram(id)archiveProgram(id), thenpurgeProgram(id)delete_enrollment_program(id)purge_enrollment_program(id)event enrollment_program.deletedevent enrollment_program.purgedenrollment_programswith 1 argumenta second argument, include_archivedNew events are
enrollment_program.archivedandenrollment_program.restored. Runbetter-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
defineEntityPagetakes two new optional fields andgenwrites one more file.tenantOption: "organizationId"makes the generated list and export routes pass the request's tenant to a block whosepageandfacetstake the organization per call.appdeclares an entity no block owns (app.<entity>) with its surface, table and a reads module, so an app table gets the generated routes, indexes and scale test.pages/coverage.tslists the routes of each block's pages for the app's coverage map. Pages that set none of these generate what they did before. -
gennow also writes the columns, the detail frame and the forms of an entity page. SetcolumnsandsectionsondefineEntityPageandgenwritespages/<name>.columns.ts(each column with its label, kind and the declared sort and filter of the same name) andpages/<name>.detail.ts(the/:idroute, the sections andhref(id)). A page whose block exports an input schema also getspages/<name>.form.tswith<name>CreateFormand<name>EditForm, built with the newdefineEntityFormfrombetter-supabase/list, so a form cannot drift from the action it submits to.better-supabase/listalso exports the typesEntityColumn,EntityDetail,EntityDetailSection,EntityFieldKind,EntityForm,EntityFormFieldandEntityFormParse. The descriptor keepsapiVersion: 1.The entity list helper type
ListArgsis nowListCallParamsand the eve typeEveDynamicRunArgsisEveDynamicRunParams, so neither uses the bannedArgssuffix (ADR 0246). -
defineEntityPagetakesexport: { filename, columns, maxRows }.genthen writesGET /api/<name>/export, which streamsexportResponseover the entity'spageunder the list query'sq,sortand filters, and lists the route asexportinpages/routes.manifest.ts(EntityRouteEntry.exportis optional). A page withoutexportwrites nothing new. The eight format-specific exports (payroll, OSCAL, SEPA, iCalendar, promptfoo, audit log, governance subject and data export) keep their own methods. -
gennow writes the list of an entity page from one descriptor. Declare a page withdefineEntityPage(frombetter-supabase/list) ingen.entityPages.pages, andgenwritespages/<name>.list.ts(adefineEntityListQueryover the entity's declared sorts, facets, filters and search), the/api/<name>/listroute, a migration with the indexes of its sorts, facets and searched columns, andscale_list_<name>.test.sql, a pgTAP plan check. A new doctor check, BS636, reports a declared sort, facet or search column that has no index.gen.entityPagesis new and optional, so nothing changes without it. -
Generate seed rows, a nav item and a route manifest from an entity page.
gen.entityPagesnow writespages/<name>.seed.tsfor a page that setsseed,pages/<name>.navigation.tsfor a page that setsarea, andpages/routes.manifest.tswith the routes and message keys of every page.better-supabase/listexports the typesEntitySeed,EntitySeedValue,EntityNavItemandEntityRouteEntry. A page withoutareaorseedwrites no new file besides the manifest. -
An entity's manifest can now declare how it handles personal data, retention and history.
EntitySurfacegainssubjectColumn,erase(delete,anonymizeorkeep),legalHold,historyandpartition.subjectAccessPlan(blocks)andsubjectAccessRequest(lifecycle, input)frombetter-supabase/blocks/data-lifecycleread the declarations and return the entities an access request collects and an erasure removes, blanks or keeps, so an erasure never deletes append-only audit rows.historyTabs(blocks)frombetter-supabase/blocks/field-historylists the entities that keep history.consent,data_subject_requestandfield_historydeclare their personal data, retention class and, for field history, a monthly partition. No schema change. -
better-supabase/evefollows eve 1.0.0-rc.13, which bundles Workflow 5.5: theevepeer range is now>=1.0.0-rc.13 <2and@vercel/connectstarts at 2.7.0.persistSessionsstores acontent.completedpart without arunId, which eve now sends for a part its turn wrote without a model run.queueDynamicScheduleskeyscollectionsby the collection name, which is the definition's newidwhen it sets one. -
better-supabase/evefollows eve 1.0, and theevepeer range is now>=1.0.0-rc.0 <2(@vercel/connectstarts at 2.5.2).persistSessionshandles eve's version 27 session events:delivery.consumedstores the user's text,content.completedstores each text part (a part outside the reply is interim), andturn.settledsets the run's status from its outcome, in place ofmessage.received,message.completedand the threeturn.*endings.credentialAuthandopenApiAuthreturnprincipalType, which eve 1.0 reads, instead ofcredentialOwner, so a user-owned connection keeps per-user tokens.EveApprovalResponseContextnamesrequest.interactionIdand thedenydecision,EveApprovalStatustakes the{ type: "not-applicable" }and{ type: "user-approval" }forms, andEveMemoryTool.inputSchemais a JSON Schema object. See the 0.66 to 0.67 guide for the renames. -
queueScheduleProvider({ scheduler })frombetter-supabase/eveis a provider for eve'sdefineDynamicSchedulesthat stores each schedule as a queue block schedule on theeve_schedulesqueue, so members and the model manage them with eve's tools while the drain scheduler keeps their time zone, tenant and payload.queueDynamicSchedules({ queue, provider, collections })is therunof a minutedefineSchedule: it enqueues the due runs, then calls each definition'sauthandrunas the schedule's creator, with eve's retry andoccurrence.dispatchedandoccurrence.failedrules.eveScheduleRunis the queue's schema. The provider needs a scheduler that lists schedules with their payloads, such assqlScheduler(sql, { mode: "drain" }). -
supabaseJwtAuthfrombetter-supabase/eveis an eve routeAuthFnfor MCP clients and other agents that send a Supabase access token asAuthorization: Bearer. It verifies the token locally against the project's keys, so a valid token costs no Auth server call, and it never reads the session cookie. A request without a bearer token falls through to the next entry; an invalid token gets a 401 withWWW-Authenticate: Bearer error="invalid_token"and never reaches a laternone(). It declares theBearerchallenge, sooauthResourceand eve's own 401 advertise it.EveAuthRejectiontakes response headers as a third argument. -
Adds the list calls the example findings EX-800, EX-802, EX-1102 and EX-1103 asked for, all additive (ADR 1077).
donationsacceptsqongiftPage,giftFacets,giftCountand the pledge reads (donor id, payment reference and note), andwarehouse.pickListPageacceptsqover the document id and type.reviews.queuetakes a list of statuses instatusand matches a review in any of them.inventorygainslocationPage,binPageandvariantPagewith their facets and counts, so a page that names or selects locations, bins and catalog variants no longer reads them withqueryRaw.The SQL extends
list_gifts,list_pledgesandlist_pick_listswith a search filter, replacesreview_queuewith a version that has astatusesargument (the old arguments still work), and addspage_stock_locations,page_stock_binsandpage_stock_variants, so the generated schema files needbetter-supabase upgrade. -
The
workflow-editorandinboxblocks gain list pages, andworkflowsgains a definition filter.workflow-editoraddsdefinitions.page,facets,countandgetDefinition, withqover the name and the slug, astatefilter (published,draft,new) and the sortsname,updatedAtandcreatedAt.inboxaddsinboxes.page,facets,countandgetInbox, andtemplates.page,facets,countandgetTemplate.conversations.pagegains the filterspriority,sla,slaMinutesandtagId(the last needs thetagsblock) and the facetspriorityandsla.workflows.runs.listtakesdefinitionId, one builder definition id or a list, which the database applies to the runs'bsb.definitionattribute.All of it is additive.
definitions.listanddefinitions.getstay as deprecated aliases. The new SQL functions arepage_workflow_definitions,page_inboxes,get_inbox,page_message_templates,get_message_templateandinbox_conversation_tagged, andworkflow_runs_listgains adefinition_idsargument (its old signature is replaced). Runbetter-supabase upgradeand apply the migration it generates. A hand-written implementation of theWorkflowEditororInboxinterface needs the new methods. -
A data subject request can now run its erasure.
data-lifecyclegains the SQL functionerase_data_subject(request_id)and the client methodexecuteErasure({ requestId }). It reads each installed module table's newlifecycle.erase(delete,anonymizeorkeep), deletes, blanks or counts the rows of the one person the request names in the request's organization, and returns what was removed, blanked, kept and held. A table whose retention kind has an active legal hold is left alone and reported underheld. Theconsentsandfield_historytables anonymize,data_subject_requestsis kept andconsent_signalsis deleted; append-only rows are never deleted.consentno longer declaresgivenByContactas personal data and gains aconsent_signalentity. Runbetter-supabase upgradeand apply the migration it generates. -
createDataLifecyclehasstartExportJob(options), which returns{ jobId: "export:<id>" }, andjobs, theexportsource ofcreateJobs.createWorkflowshasjobs, theworkflowsource, which reads a run as the common job result. Both read through the caller's own permissions and fail withDATA_EXPORT_FAILED,WORKFLOW_RUN_FAILEDorWORKFLOW_RUN_CANCELLED. Nothing existing changes. -
exportandexportResponsetake aformat.csvFormatis the default andndjsonFormatwrites one JSON object per line with the content typeapplication/x-ndjson. Pass your ownExportFormat(contentType, an optionalheaderandrows) for another line-oriented format, such as TSV. Both helpers and the type come frombetter-supabase/blocks. -
The attachments and drive blocks keep their bytes in a versioned
FileStore(put,get,delete,signedUrl, with optionalheadandsignedUploadUrl) frombetter-supabase/storage.supabaseFileStore(storage)is the default, so nothing changes without the newfilesoption;vercelBlobStore(blob)stores the files in Vercel Blob, with@vercel/blobas an optional peer. Postgres still decides who may upload:confirm_attachmenttakes an optionalobject({ size, mimetype }) that only the service role may pass, checked against the bucket's limits, so passservicetocreateAttachmentsandcreateDrivewith an external store. Image transforms, public URLs and the upload claim stay Supabase-only (ATTACHMENT_STORE_UNSUPPORTED). Runbetter-supabase upgrade(attachments module 9 to 10) and apply the new migration.testFileStoreinbetter-supabase/testingchecks your own store.Before After confirm_attachment(id uuid)confirm_attachment(id uuid, object jsonb default null)storagerequired oncreateAttachmentsstorageorfiles;filesdefaults tosupabaseFileStore(storage) -
runandcountFacetsofdefineListQuerytakefacetCountMode: "exact" | "capped", which overrides the list's config for one call, so a list that caps its chips can still give a dashboard an exact count. Thenumberingblock declaresnumbering.readon itsnumberentity, and the default admin role holdsnumbering.*. A page that lists the counters can checknumbering.readinstead ofnumbering.assign. Runbetter-supabase gento write the permission catalog migration, which grants the new key to the owner and admin roles, andbetter-supabase upgradeto refresh theoperation_permissionfunction. A member also holdsnumbering.read, because every declaredreadkey goes to thememberrole.Old New A numbering page gated by numbering.assignnumbering.read(the owner, admin and member roles)Facet count mode fixed per list run(db, query, { facetCountMode })per call -
Breaking:
formsgetsarchiveSubmissionandrestoreSubmission, and the hard delete of a submission ispurge, behind its ownpermissions.purgekey (it falls back to the review permission). An archived submission leaveslistSubmissionsandnps;listSubmissionstakesincludeArchived, andFormSubmissioncarriesarchivedAt.Before After forms.deleteSubmission(id)forms.purgeSubmission(id)delete_form_submission(submission_id)purge_form_submission(submission_id)event form_submission.deletedevent form_submission.purgedhooks.deleteSubmissionhooks.purgeSubmissionlist_form_submissionswith 4 argumentsa fifth argument, include_archivedNew events are
form_submission.archivedandform_submission.restored. A draft is refused byarchiveSubmission; a respondent still purges their own draft. Runbetter-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
Inbox messages, outbox events and queue jobs can start as soon as they are written instead of on the next cron call.
createQueue,createWebhookInboxandcreateOutboxtakekick: { waitUntil, run }, which runs a pass after each successful write (bsb.waitUntilin Next.js wrapsafter()). The queue, webhook-inbox and outbox modules (versions 13, 11 and 7) add a statement trigger that notifiesbetter_supabase_workon each insert, andlistenForWork(pool, { inbox, outbox, queues })inbetter-supabase/postgresruns the matching pass on a long-lived Node process, including for rows written from SQL. Runbetter-supabase upgrade.usesTransactionPooleris now also exported frombetter-supabase/postgres. -
The signing-keys block signs through a versioned
KeyProvider(sign,signJwt).vaultKeyProvideris the default and keeps today's behaviour, with the private keys in Supabase Vault.createSigningKeys({ keys: vercelKmsKeyProvider(kms, { issuer }) })signs in Vercel KMS instead, so the private key never reaches the app;create,rotate,jwksand the other key methods keep managing the Vault keys.@vercel/kmsis an optional peer that you pass in, andtestKeyProviderinbetter-supabase/testingchecks your own provider. -
Generated seeds can link to each other.
seed.rowsondefineEntityPagetakes nested lists and objects,seedRef(entity, name)for the id of a row another page seeds, andseedDate(days)for a day counted from the day the seed runs.genwritesdependsOninto the seed file and stops when a ref names a page without a seed.better-supabase/listexportsseedRef,seedDate,seedRefs,orderSeedsandresolveSeedValuefor a seed runner. The descriptor stays atapiVersion: 1. -
Eleven list entities of the commerce blocks page, facet and count through the shared list function (ADR 0769): commission, commission statement and commission plan, donation gifts and pledges, leases, production orders, periods, referrals and referral codes, and shipments. Each client gets
<x>Page,<x>Facetsand<x>Count(commissionPage,statementPage,planPage,giftPage,pledgePage,leasePage,orderPage,periodPage,referralPage,codePageandshipmentPage), and each entity declaressorts,facetsandfiltersin its manifest. The SQL functionslist_leases,list_shipments,list_giftsandlist_pledgesnow take(tenant, filters jsonb)instead of one argument per filter, andlist_production_ordersnames its argumentfilters. The clients'list,gifts,pledgesandlistOrdersmethods are unchanged. Apply the generated migration, and change a direct SQL call to pass the filters as a jsonb object.Before After list_leases(tenant, 'active', unit, null, null, 50)list_leases(tenant, '{"status":"active","unitId":"...","limit":50}')list_shipments(tenant, 'draft', null, null, 'dhl', null, 50)list_shipments(tenant, '{"status":"draft","carrier":"dhl","limit":50}')list_giftsandlist_pledgeswithdonor_type,donor_idandpage_sizefilterswithdonorType,donorIdandlimitlist_production_orders(tenant, filter => '{"status":"done"}')list_production_orders(tenant, filters => '{"status":"done"}')One status per list call <x>Page({ filters: { status: ["open", "done"] } }), a list per filterNo facet counts or exact counts for these lists <x>Facets()and<x>Count()return{ value, exact } -
The
legal-entities,coursesandcontentblocks page, facet and count through the shared list implementation (ADR 0749, 0789).legal_entity,courseandcontent_entrydeclaresorts,facetsandfiltersin their manifests, and each client gainspage,facetsandcount. The SQL functionslist_legal_entities,list_coursesandlist_content_entriesnow take(tenant, filters jsonb).content.listreads its text search fromqueryas before and sends it asfilters.search;legalEntities.listandcourses.listare capped at 500 rows (200 by default). An unknownstatuson a course list now matches no rows instead of raisingCOURSE_INVALID. Thessoblock keeps its SCIMstartIndexandcountpaging and its boundeddomains()andproviders()lists. Apply the generated migration to adopt the new list functions.Before After list_legal_entities(tenant, include_archived)list_legal_entities(tenant, filters)withfilters.includeArchivedlist_courses(tenant, status)list_courses(tenant, filters)withfilters.statuslist_content_entries(tenant, filter)list_content_entries(tenant, filters)content.list({ query })was the only text searchcontent.page({ q })matches the title and slugcourses.list()andlegalEntities.list()returned every rowA capped list; use pagepast 500 rowsNo facet counts or sort choice for these three lists facets(),count()andsort: { by }from the entity's declaredsorts -
Five more blocks page, facet and count through the shared list implementation (ADR 0749, 0779):
sequences(sequencePage,sequenceFacets,sequenceCount),payroll-export(runPage,runFacets,runCount),passes(passPage,passFacets,passCount),enrollments(enrollmentPage,enrollmentFacets,enrollmentCount) ande-prescribing(prescriptionPage,prescriptionFacets,prescriptionCount). Each takesq,sort, list filters,afterandlimit, declares itssorts,facetsandfiltersin the manifest, and returns aninvalid_inputerror for a name it does not declare. The existinglistmethods and SQL list functions keep their signatures;sequences,payroll-export,passesandenrollmentsgain the SQL functionspage_sequences,page_payroll_runs,page_passesandpage_enrollments, andlist_prescriptionsnow accepts list filters,sort,facet,count,afterandpaged.enrollmentsalso gainsget(enrollmentId)over the new SQL functionget_enrollment. Apply the generated migration to adopt the new functions.Before After list({ status })was the only read of sequences, runs, passes and enrollmentssequencePage,runPage,passPageandenrollmentPagewithsortand list filtersNo facet counts or exact counts on these blocks <x>Facets(options)and<x>Count(options)returning{ value, exact }An enrollment was read from the list or by program and subject enrollments.get(enrollmentId) -
The
guests,dispatch,incidents,approvals,assets,casesanddeadlinesblocks gainpage,facetsandcountthrough the shared list surface (audit lane G7). Each takes the same filters, sorts andqthat its manifest declares, and rejects an undeclared one withinvalid_input.listand the old SQL functions are unchanged, and the migration only adds functions, so apply it in any order with the client upgrade.Block New client calls New SQL function guestspage,facets,count,get(id)page_guests,get_guestdispatchpage,facets,countpage_work_ordersincidentspage,facets,countpage_incidentsapprovalspage,facets,countpage_approvalsassetspage,facets,countpage_assetscasespage,facets,countpage_casesdeadlinespage,facets,count,get(id)page_deadlines,get_deadlineapprovals.pagehas notenantlessoption; requests without an organization stay onlist.incidentstakes the organization on every call. -
The shared list surface takes the organization per call (ADR 0939).
entityListacceptsorganizationIdin the options ofpage,facetsandcount, withtenantOrOptionas the resolver andRequiredTenantOptionfor a block that has notenantoption. Thedomains,forms,importsandaccess-requestsblocks use it:hostname,form,import(the runs) andaccess_requestdeclaresorts,facetsandfiltersin their manifests, anddomains.page,forms.page,imports.runs.pageandaccessRequests.pagecome withfacetsandcount, each takingorganizationId. The SQL functionslist_hostnames,list_forms,list_import_runsandlist_access_requestsnow take(tenant, filters jsonb). The cappedlistof each client sends the same filters as before;domains.listandforms.listnow return at most 200 rows by default and 500 at most, where they were unbounded. Apply the generated migration before you upgrade the client, because the old client calls the old argument lists.Before After list_hostnames(tenant)list_hostnames(tenant, filters)list_forms(tenant, status)list_forms(tenant, filters)withfilters.statuslist_import_runs(tenant, source, status, row_limit)list_import_runs(tenant, filters)withfilters.source,.status,.limitlist_access_requests(tenant, status, mine, page_size, before)list_access_requests(tenant, filters)with the same names as filterslist_import_runsreturnedsetof jsonbIt returns one jsonbarray, or a page object withpageddomains.listandforms.listwere unboundedCapped at 200 by default, 500 at most; use pagepast thatNo sort, facets or count for these four lists page,facets(),count()andsort: { by }from the declaredsortsentityListread only the block'stenantoptionorganizationIdper call wins, thentenant, elseTENANT_REQUIRED -
The
inspections,meetingsandwarrantyblocks page, facet and count through the shared list implementation (ADR 0749, 0759).inspections.page,meetings.pageandwarranty.pagetakePageOptions(q,sort, listfilters,after,limit),facets()returns the values of each declared facet with counts, andcount()returns{ value, exact }. Their manifests declaresorts,facets,filtersandsearch, and the SQL list functions serve all three reads.warrantyalso gainsget(id)with the SQL functionget_warranty_claim. The existinglistmethods keep their scalar options. Runbetter-supabase upgradeand apply the new migration to adopt the new list functions.Before After inspections.list({ status })withoffsetfor the next pageinspections.page({ filters: { status: ["planned", "in_progress"] }, sort, after })meetings.list({ search, from, to })withoffsetmeetings.page({ q, filters: { from: [start], to: [end] }, sort, after })warranty.list({ status })withoffsetwarranty.page({ filters: { status: ["submitted"] }, sort: { by: "amount" }, after })No facet counts or exact counts on these three blocks facets()andcount()on each, with{ value, exact }countsA claim detail page read the claim from the list warranty.get(id) -
The members controller has
setRoles({ userIds, role }). It changes many roles in oneupdate_member_rolescall, shows the new role at once, puts back the roles of the members the database refused and returns{ succeeded, failed }.useMembersreturns it, and the members table recipe applies its bulk role change with it instead of onesetRolecall per member.createMembersControllernow needsupdateMemberRoleson itsclient, whichcreateOrganizationsalready has. -
notifications.bulk(ids, action)marks many notificationsreadorunread, or dismisses them, andmoderation.bulk(ids, decision)applies one decision to many items. Both return the common{ succeeded, failed: [{ id, error }] }, and fail withBULK_TOO_MANYbeyond 500 ids.markRead,markUnread,dismissanddecidekeep working.NotificationBulkActionis exported frombetter-supabase/blocks/notifications. -
EntitySurface.offlinetakes ajoinlist (EntityOfflineJoin) that declares the tables and rules the PowerSync streams join to the entity's rows: the notification events and preferences, the membership role sets and organizations, and the attachment reader and subject rules.better-supabase powersync streamsreads them from the manifests, and the generated YAML does not change. The manifest contract stays atapiVersion1, andEntityOfflineJoinandEntityOfflineJoinTableare exported frombetter-supabase/blocks. -
Every peer range now starts at the release the conformance tests run on, and each range covers one major release. The previous majors are no longer supported: SvelteKit 2, Nuxt 3, React Router 7, NestJS 11, Stripe 17 to 22,
expo-server55 to 57, undici 7, redis 5 and PowerSync 1.h3keeps H3 1 (>=1.15.11 <3) because Nuxt 4 runs on it, andoxfmtkeeps its 0.66.0 floor. Expo SDK 58 needs nounstable_options, and thebsb.loader()error namesweb.output.VercelSandboxCreateOptionstypes Sandbox 4'scredentials: { npm: true }, which lets a sandbox install the team's private npm packages. Eight Vercel SDKs join the optional peers:@vercel/schedules,botid,@vercel/firewall,@vercel/passport,@vercel/sdk,@vercel/functions,@vercel/kmsand@vercel/blob. From 0.66 to 0.67 lists every new floor; the Supabase packages are in their own changeset.Package Before After @sveltejs/kit>=2 <4>=3.2.0 <4nuxt>=3 <5>=4.6.4 <5react-router>=7.9 <9>=8.5.1 <9@nestjs/common>=11 <13>=12.5.0 <13stripe>=17 <24>=23.1.0 <24expo-server>=55 <59>=58.1.0 <59undici>=7.30.1 <9>=8.12.4 <9redis>=5 <7>=6.3.1 <7@powersync/common>=1 <3>=2.5.0 <3@vercel/queue>=0.8 <0.9>=0.11.0 <0.12@vercel/sandbox>=3 <4>=4.0.0 <5eve>=0.71 <1>=0.83.3 <1workflow>=5.1 <6>=5.4.0 <6 -
Breaking: the hard delete of a team is
purge, behind its ownpermissions.purgekey. Archive and restore stay.Before After teams.delete(id)teams.purge(id)delete_team(team)(SQL)purge_team(team)event team.deletedevent team.purgedblocks.teams.permissions.deleteblocks.teams.permissions.purgeTeamWrites.delete(PowerSync)TeamWrites.purgeRun
better-supabase upgradeand apply the migration. Purging falls back to themanagekey until you setpermissions.purge. See the 0.66 to 0.67 guide. -
Breaking: a calendar event's hard delete is
purge, behindpermissions.purge, which falls back to the formerdeletekey (ADR 1081). A cancelled event keeps itsstatusas the archive, so events get noarchive,restoreor new column. Removing one occurrence of a series still usespermissions.delete.Before After calendar.delete(eventId)calendar.purge(eventId)delete_calendar_event(id)purge_calendar_event(event_id)(SQL)event calendar_event.deletedevent calendar_event.purgedpermissions.deletepermissions.purge(deletestill read)Run
better-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
Breaking: an employee's hard delete is
purge, behindpermissions.purge, which falls back to the write key (ADR 1079). Offboarding stays the archive, so employees get noarchive,restoreor new column.Before After employees.delete(id)employees.purge(id)delete_employee(id)(SQL)purge_employee(id)event employee.deletedevent employee.purgedhooks before_employee_delete,after_employee_deletebefore_employee_purge,after_employee_purgeRun
better-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
Breaking: an expense's hard delete is
purge, behindpermissions.purge, which falls back to the formerdeletekey and thenexpenses.manage(ADR 1082). A rejected or reimbursed expense keeps its status as the archive, so expenses get noarchive,restoreor new column.Before After expenses.deleteExpense(id)expenses.purgeExpense(id)delete_expense(id)(SQL)purge_expense(id)event expense.deletedevent expense.purgedpermissions.deletepermissions.purge(deletestill read)Run
better-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
The queue block can read one message back:
queue.enqueueJob(input)returns{ jobId: "queue:<queue>:<id>" },queue.get({ queue, id })returns its run record (state, attempts, last error, never the payload), andqueue.runsis thequeuekind ofcreateJobs. The newget_job(queue, job_id)SQL function (queue module version 16) backs it; runbetter-supabase upgradeand apply the migration.enqueuekeeps returning the numeric id. -
better-supabase addandinitprint the wiring of each queue and scheduler pair when the queue block is installed, and theschedulesfragment ofvercel.jsonfor the workers that run on a cron. Doctor BS512 (warning) reports queue schedule wiring that misses or doubles runs: a pathvercel.jsonstill calls fromcrons, a path in bothcronsandschedules, a schedule on a private function without aschedule/v1betatrigger, andblocks.queue.options.httpTickwithoutpg_netor thejobs_tick_urlandjobs_tick_tokenVault secrets. -
createQueuetakes aschedulerapart from the queue, so Supabase Queues or Vercel Queues pair with Supabase Cron or Vercel Schedules. The newScheduleProviderinterface (apiVersion: 1) is what decides when a schedule fires; everyQueueProvideris one, and withoutschedulerthe queue's own schedule methods run as before.sqlScheduler(sql, { mode })andtransportScheduler(transport, { mode })are Supabase Cron (mode: "pg_cron", the default) or the drain scheduler (mode: "drain") apart from the queue. A pair that can't deliver, such as pg_cron with Vercel Queues, throws aTypeError.vercelScheduler(Schedules, { bridge, jitter, namespace })writes each schedule to Vercel Schedules (passSchedulesfrom@vercel/schedules). A tenant becomes a namespace. On Vercel Queues a run publishes to the job's topic andvercelQueueRouteunwraps it; on a Supabase queue it publishes to thebridgetopic, wherevercelScheduleBridgeRoute(jobs, { client })checks the probe and enqueues the run once perexecutionId.jobs.schedulesRoute({ secret })runsrunSchedulesfor a clock on a queue without a drain, andjobs.enqueueScheduledRun(input)enqueues one run another scheduler fired.runSchedulessends due runs withsendBatchwhen the queue has it, whichvercelQueueProvidernow does.blocks.queue.options.httpTickinstallsbetter_supabase.http_tick()and a pg_cron job that calls the drain or schedules route every minute with the URL and token in the Vault secretsjobs_tick_urlandjobs_tick_token, so Supabase Cron can be the clock.drainRouteandschedulesRouteacceptcaller: "vercel-schedule", which lets a Vercel schedule run in without the secret. Use it only on a private function with aschedule/v1betatrigger.vercelScheduleConfig(options)returns thefunctionsandschedulesfragments ofvercel.json, andvercelCronOf,vercelScheduleNameOf,vercelNamespaceOf,parseVercelScheduleRunandisVercelScheduleMessageconvert to and from Vercel's formats.- A job delivered from a schedule run exposes
job.schedulewith itsname,executionIdandscheduledAt.jobs.unschedule(name, { tenant })takes the tenant a scheduler keeps apart. testScheduleProviderfrombetter-supabase/testingchecks a scheduler.
The
jobsSQL module moves to version 14 (schedule_has_workbecomes a client function, plushttp_tickwithhttpTick). Runbetter-supabase upgradeand apply the new migration. -
Breaking:
readSessionis replaced byssrSession, which decodes the session cookies with the@supabase/ssrhelpers (combineChunksand its base64url decoder) and returns a promise.applyCookieWritesis no longer exported.Before After readSession(cookies, name)await ssrSession(cookies, name)applyCookieWrites(cookies, writes)let a createServerClientwrite the cookiesChunks that don't parse together now read as no session, as they do in
@supabase/ssr;readSessionused the longest prefix that parsed. -
The
bookings,expenses,leaveandrisksblocks have record bindings.bookingsBindingloads a customer's bookings,expensesBindinga member's expense reports,leaveBindingthe leave requests of an employee or a member, andrisksBindingthe open risks linked to a record. Each takes the organization from the block'stenantoption. Bookings getsforCustomer, leave getsforOwnerand risks getslinkedTo, with the SQL functionslist_bookings_for_customerandlist_risks_for_subject; runbetter-supabase upgradeand apply the new migration.LeaveOptionsacceptstenant.Before After bookingsBlock.record,expensesBlock.record,leaveBlock.recordandrisksBlock.recordareundefinedThey are bookingsBinding,expensesBinding,leaveBindingandrisksBindingA customer's bookings read by hand from the range list bookings.forCustomer({ subject })Leave of an employee read with list({ employeeId })onlyleave.forOwner({ subject }), or the bindingRisks of a record found by hand through relations risks.linkedTo({ subject }) -
Breaking:
better-supabase/client/liteis removed, along with the optional peers@supabase/auth-jsand@supabase/realtime-js. Browser clients come only from@supabase/ssr'screateBrowserClient, so sessions follow its cookies everywhere (ADR 0846).Before After import { createLiteBrowserClient } from "better-supabase/client/lite"import { createClient } from "better-supabase/client"A route that used the lite client loads about 12 KB more. You can uninstall
@supabase/auth-jsand@supabase/realtime-jsif nothing else in the app imports them. -
deals,tasks,messaging,channels,collectionsandaccountingget arestorenext to theirarchive, and a restore records an event.archivewitharchived: falsestill works and records the same event. Each method needs the permission itsarchiveneeds.Block New method New event dealsrestore(dealId)deal.restoredtasksrestore(taskId),restore(ids)task.restoredmessagingrestore(conversationId)conversation.restoredchannelsrestore(channelId)conversation.restoredcollectionsrestore(id)collection.restoredaccountingrestoreAccount(accountId)none Run
better-supabase upgradeand apply the migration, which replacesarchive_deal,archive_task,archive_tasks,archive_conversationandarchive_collection. -
leave,qualifications,donationsandexpensescan restore what they archive, and record the change. Each new method needs the permission itsarchive*twin needs.Block Archive New restore Events leavearchiveTyperestoreTypeleave_type.archived,leave_type.restoredqualificationsarchiveTyperestoreTypequalification_type.restored(archived existed)donationsarchiveFundrestoreFunddonation_fund.archived,donation_fund.restoredexpensesarchiveCategoryrestoreCategoryexpense_category.archived,expense_category.restoredRun
better-supabase upgradeand apply the migration. The SQL functions arerestore_leave_type,restore_qualification_type,restore_donation_fundandrestore_expense_category. -
cases,lims,contacts,consents,shiftsandobservationsget a restore next to their archive. Each needs the permission its archive needs, and restoring an entity that is not archived changes nothing.Block New method New event casesrestoreKind(kindId)case_kind.restoredlimsrestoreMethod(methodId)lims_method.restoredcontactsrestoreCompany(id),restorePerson(id)company.restored,person.restoredconsentsrestorePurpose(purposeId)consent_purpose.updatedshiftsrestoreTemplate(templateId)none observationsrestoreDefinition(definitionId)observation_definition.updatedarchiveCompanyandarchivePersonwitharchived: falsenow record the restored event too. Runbetter-supabase upgradeand apply the migration. -
assets,medications,compliance,content,option-setsandpipelinesget a restore next to their archive. Each needs the permission its archive needs, and restoring an entity that is not archived changes nothing.Block New method New event assetsrestoreLocation(locationId)asset_location.restoredmedicationsrestoreMedication(medicationId)none compliancerestorePolicy(policyId)none contentrestore(entryId)(back as draft)content_entry.restoredoption-setsrestoreItem(itemId)option_set_item.restoredpipelinesrestore(id),restoreStage(id)pipeline.restored,pipeline_stage.restoredRun
better-supabase upgradeand apply the migration. -
Breaking:
scoresgetsarchiveModelandrestoreModel, and the hard delete of a model ispurge, behind its ownpermissions.purgekey (it falls back toscores.manage). An archived model leavesmodels,listandtop, andcomputeandsaveModelrefuse it withSCORES_MODEL_ARCHIVED; its versions and every score stay, andhistorystill reads them.modelstakesincludeArchived, andScoreModelcarriesarchivedAt.Before After scores.deleteModel(id)scores.purgeModel(id)delete_score_model(model_id)purge_score_model(model_id)event score_model.deletedevent score_model.purgedhooks.deleteModelhooks.purgeModellist_score_modelswith two argumentsa third argument, include_archivedNew events are
score_model.archivedandscore_model.restored. Runbetter-supabase upgradeand apply the migration. See the 0.66 to 0.67 guide. -
An import run now indexes search once per record when it closes. While a run writes through
import_upsert_batch, the search triggers note each record inbetter_supabase.import_search_dirty, andfinish_import_runorcancel_import_runindexes the noted records through the newsearch_refresh_run. A record that several batches of one run change is indexed once; it becomes searchable when the run closes.recordTypes.<type>.search.statement: trueindexes a record type through statement triggers (bsb_search_<type>_insert,_update,_delete) instead of the row trigger, so a set-based write fires one search call per statement. Switching a type renames its triggers: runbetter-supabase upgradeand generate a migration.A batch import target now receives
subjectIdon each item, as documented. Before, an update batch inserted duplicates and fell back to onewriteper item.Run
better-supabase upgrade(search 4, imports 3). -
Request stats now count the raw
ctx.supabaseclient and remote cache fills. Whiledebugcollects, each PostgREST, RPC, Storage and Edge Function request the context'ssupabaseclient sends is a call on the request's stats, named after its table,name(),storage/<bucket>orfunctions/<name>; Auth calls don't count. A'use cache: remote'fill called throughbsb.remote()records on the request that called it, where before it recorded nothing. With a request recorder,ctx.dbkeeps its own PostgREST client instead of reusingctx.supabase, so no call is counted twice. -
Comment counters and search lists now check record access once per list instead of once per row. The subjects module adds
can_subjects(subject_type, subject_ids, action), which returns the ids the caller can act on in one read of the record's table.comment_countsuses it and then finds the records' conversations by key, through the newcomment_count_keys;comment_count_rowsis removed.search_page,search_recentsandsearch_favoritescheck each batch or record type with one call. The results don't change.Run
better-supabase upgrade(subjects 2, comments 10, search 5). -
sessionStatus,asSignedInUserand the flags-sdk Data API transport now call Supabase through supabase-js (auth.getUser,auth.signInWithPasswordandrpc) instead of building the requests.Breaking: the notifications block's
avatarsoption takes only a function of the object path. PassgetPublicUrlfrom a supabase-js client for a public bucket:Before After avatars: { url, bucket: "users" }avatars: (path) => users.getPublicUrl(path).data.publicUrlsessionStatusreads a 403 whose body is not Auth's JSON asunknowninstead ofended, so a proxy or firewall response no longer ends a session. -
The Supabase peers now start at their newest releases.
@supabase/supabase-js,@supabase/auth-jsand@supabase/realtime-jsneed^2.119.0(was^2.118.0),@supabase/serverneeds^1.9.2, and@supabase/configneeds^1.6.1(was>=0.9.0 <2).@supabase/postgrest-typegenand@supabase/mcp-server-supabasehave a floor and no upper bound:>=0.8.1(was>=0.6.0 <0.7) and>=0.16.1(was>=0.13.0 <0.15). The CLI is tested against postgrest-typegen 0.8.1, so install that release (pnpm add -D @supabase/postgrest-typegen@0.8.1) to keepdatabase.types.tsequal tosupabase gen types. -
tasks.bulk(ids, action, options)archives, restores or removes many tasks with the common bulk shape:{ succeeded, failed: [{ id, error }] }, with ids the set statement skipped asfailedwithnot_found, andBULK_TOO_MANYbeyond 500 ids. The array overloads ofarchive,restoreandremovekeep working.TaskBulkActionis exported frombetter-supabase/blocks/tasks. -
The usage module adds
usage_quotas_for(tenants, meters), which returns the quota of every tenant and meter pair and resolves each tenant's entitlements and plans once. The usage block's admin client calls it throughusage.quotas({ organizationIds, meters }), which returns oneUsageQuotaper pair that has a quota.usage_quota(tenant, meter)now reads from it and returns the same row as before.Run
better-supabase upgrade(usage 9). -
createPostgres({ attachDatabasePool })takesattachDatabasePoolfrom@vercel/functionsand calls it with the pool it opens, so a function instance stays alive until its idle connections close.createServer({ auth: { jwksStore } })andverifyPassport({ store })share the fetched JWKS between instances through aJwksStore;vercelRuntimeCache(getCache)builds one on the Vercel Runtime Cache. A stored key set keeps the time of its original fetch, so a Supabase key set is still never served more than 600 seconds after it was fetched, and a store that fails or takes over 500 ms is skipped.accessTokenResolvertakes it ascache: { store }. -
Two new entries for apps on Vercel.
better-supabase/vercel-securityguards the sign-up, OTP and magic-link routes:botIdGuard({ checkBotId })refuses bots with aproblem+json403 (BOT_DETECTED), andfirewallRateLimit({ checkRateLimit, id })answers a limited request with a 429 andRetry-After(a Firewall block is a 403 withFIREWALL_BLOCKED).combineGuardsandwithGuardscompose them, andbotIdCheckcovers Server Actions.better-supabase/vercel-passportaddsverifyPassport(request, options), which verifies the Vercel Passport token against Vercel's keys through the shared JWKS cache and passes{ iss, sub, claims }to yourresolveUser.botid,@vercel/firewalland@vercel/passportare optional peers that you pass in; the entries import none of them. -
The webhooks block is a job source:
dispatchJob(input)andredeliverJob(deliveryId)return{ jobId: "webhook:<delivery id>" }, andwebhooks.jobs(thewebhookkind ofcreateJobs) reads the delivery back as the commonJobResult. The newget_webhook_delivery(delivery)SQL function (webhooks module version 8) returns one delivery to a caller who may read its endpoint's organization; runbetter-supabase upgradeand apply the migration.dispatchandredeliverkeep returning the delivery id. -
Workflow editor: three additions and a migration. An
eventtrigger kind starts a run for each block event whose type isconfig.event(or aprefix.*pattern):builder.triggers.fire(event)does it, andsubscribeEventTriggers(betterSupabase, builder)calls it frombetterSupabase.events.on("block", ...)without ever changing the result of the work that emitted the event. A node kind withwaits: truepauses the run after its step:GraphRuntime.waitForregisters the hooknodeWaitToken(runKey, node), and the node is called a second time withcall.resumedonce the hook resumes (compileGraphemits the same calls);nodeRunReportertakes{ waits: true }to recordwaiting. Node run records keep the step's input (WorkflowNodeRun.input,NodeRunRecord.input), recorded withrunning.Run
better-supabase upgradeand apply the migration it generates: it addsworkflow_node_runs.input, replacesrecord_workflow_node_runwith a version that takesinputlast, addsworkflow_event_targets, and addseventto the trigger kind check. An app whose own enum types the trigger kind adds the valueeventto it. -
useWorkflowRunsandcreateWorkflowRunsControllertake amodeoption (live,testorall, defaultlive), so an editor can list the test runs it starts instead of tracking their ids itself.WorkflowRunModeis exported frombetter-supabase/blocks/workflows. -
better-supabase/workflow-sdk/worldspeaks the@workflow/world5.2 protocol (WORKFLOW_WORLD_PROTOCOLis5.2.0), so the peer ranges are nowworkflow>=5.5.0 <6and@workflow/worldand@workflow/world-postgres>=5.2.0 <5.3;@vercel/functionsstarts at 3.11.1, the release@workflow/core5.5 depends on. Theworkflow-sdkSQL module is version 5: it adds theworkflow.workflow_job_lock_holderstable of world-postgres migration 0030, closed to the API roles. Runbetter-supabase upgradeand apply its migration before you deploy. The World declaresqueueAuthMode: "skip", because its flow route already checks the HMAC signature of every delivery, and keeps the world-postgres capabilities, soWORKFLOW_SPEC_VERSION=9can create spec 9 runs. See the 0.66 to 0.67 guide. -
Pages the people blocks by the block list contract (ADR 1077).
leavegainsrequestPage,requestFacets,requestCountandgetRequest, with sorts onstartsOn,endsOnandcreatedAt, filters on status, type, member, employee and dates, andqover the note and type.employeesgainspage,facets,countandget.document-templatesgainstemplatePage,templateFacetsandtemplateCount, anddeadlinesandenrollmentsacceptqon their pages. The SQL addspage_leave_requests,get_leave_request,page_employees,get_employeeandpage_document_templates, and the generated schema files needbetter-supabase upgrade. The array methodsleave.list,deadlines.list,enrollments.listanddocumentTemplates.listTemplateskeep working and are deprecated.Old New leave.listleave.requestPagedeadlines.listdeadlines.pageenrollments.listenrollments.enrollmentPagedocumentTemplates.listTemplatesdocumentTemplates.templatePage -
teamsandorganizationsfollow the block list contract (ADR 1077).teamsgainsteamPage,teamFacets,teamCountandgetTeam, withqover the name, slug and description and astatusfilter list.organizationsgainsmembersPage,membersFacetsandmembersCount, sorted byroleoruserIdand filtered byrole.teams.liststays as a deprecated alias until 0.70. -
Pages the AI and messaging blocks by the block list contract (ADR 1077).
agents,ai-chat(chats and projects),ai-files,ai-keys(keys and batches),ai-schedules,knowledge(documents and collections),ai-evals(datasets and runs),ai-guardrails(policies and decisions),inbox,channels,messaging,posts(posts and boards) andmemory(archival facts) gainpage,facetsandcountwithq, sorts, array filters and a keyset cursor, and a read of one row that returns anot_founderror for an unknown id (getConversation,getChannel,getPost,getDataset,getRun,getPolicy,getBatch,get). The SQL adds thepage_*andget_*functions for them, and the generated schema files needbetter-supabase upgrade. Blocks with a tenantless scope (ai-evals, ai-guardrails, memory) take noorganizationIdfor their system rows.comments,timelineandshare-linksstay as they are: they read one subject, and their docs pages say so. The array methods keep working and are deprecated.Old New agents.listagents.pageai-chatchats.list,projects.listchats.page,projects.pageaiFiles.files.listfiles.pageaiKeys.keys.list,batches.listkeys.page,batches.pageaiSchedules.listaiSchedules.pageknowledge.documents.list,collections.listdocuments.page,collections.pageevals.datasets.list,runs.listdatasets.page,runs.pageguardrails.policies.list,decisions.listpolicies.page,decisions.pageinbox.conversations.list,getconversations.page,getConversationchannels.list,getchannels.page,getChannelmessaging.conversationsconversationPageposts.list,boards,getposts.page,boardPage,getPostmemory.archival.listmemory.archival.page -
Pages the content, scheduling, work and platform blocks by the block list contract (ADR 1077).
announcements,reminders,tags,saved-views,custom-fields,incidents,advisories,time-entries,care-plans,observations,calendar,bookings,tasks(with projects) andtrashgainpage,facets,countand agetthat returns anot_founderror, with sorts, list filters andq.promptsgainspage,countandgetPrompt(labels are a map, so it has no facet).bookingsusespageBookings,bookingFacets,countBookingsandgetBookingbecausepagereads slots.incidentsgainsgetIncident, andtasksgainsgetTask, because theirgetreturnsundefined. Advisories also page vulnerabilities, observations page definitions and calendar pages calendars. The SQL addspage_*andget_*functions for each, so the generated schema files needbetter-supabase upgrade. The array methods keep working and are deprecated.Old New announcements.listannouncements.pageprompts.listprompts.pagereminders.listreminders.pagetags.listtags.pagesavedViews.listsavedViews.pagetasks.listtasks.pagecustomFields.listDefinitionscustomFields.pageincidents.listincidents.pageadvisories.advisoriesadvisories.pageadvisories.vulnerabilitiesadvisories.pageVulnerabilitiestimeEntries.listtimeEntries.pagecarePlans.listcarePlans.pageobservations.listobservations.pageobservations.definitionsobservations.pageDefinitionscalendar.listCalendarscalendar.pageCalendarsbookings.listbookings.pageBookingstrash.listtrash.pageimports.runs.listimports.runs.page -
Pages the inventory, drive, qualifications, versions, attachments, signatures, templates and forms blocks by the block list contract (ADR 1077). Each gains
page,facetsandcountmethods withq, sorts and list filters:inventory.levelPage,movementPageandlotPage(withgetLevel,getMovementandgetLot),drive.documentPageandgetDocument,qualifications.typePageandgetType,versions.versionPage,attachments.attachmentPage,signatures.requestPage,templates.templatePageandgetTemplate, andforms.submissionPage. The SQL addspage_inventory_levels,page_inventory_movements,page_inventory_lots, the threeget_inventory_*reads,page_drive_documents,page_qualification_types,get_qualification_type,page_versions,page_attachments,page_signature_requests,page_templatesandpage_form_submissions, andlist_formsgains search. The generated schema files needbetter-supabase upgrade. The array methods keep working and are deprecated.Old New inventory.levelsinventory.levelPageinventory.movementsinventory.movementPagedrive.documentsdrive.documentPagequalifications.typesqualifications.typePageversions.listversions.versionPageattachments.listattachments.attachmentPagesignatures.listsignatures.requestPagetemplates.listtemplates.templatePageforms.listSubmissionsforms.submissionPage -
Pages the CRM pipeline blocks by the block list contract (ADR 1077).
segments,forecasts,pipelines,deals,quotesandcontractsgainpage,facets,countandget, andcontractsaddsobligationPage,obligationFacetsandobligationCount.contactsgainscompanyPageandpersonPagewith their facets and counts, pluscompanyByIdandpersonById.mail-syncgainsthreadPageandaccountPagewith their facets and counts, plusgetThreadandgetAccount. Each list takesq, sorts, array filters and a keyset cursor, and agetfor an unknown id returns anot_founderror. The SQL addspage_segments,page_forecast_snapshots,page_pipelines,get_pipeline,page_deals,get_deal,page_quotes,get_quote,page_contracts,page_contract_obligations,page_companies,page_people,page_mail_threadsandpage_mail_accounts, and the generated schema files needbetter-supabase upgrade. The array methods keep working and are deprecated.Old New segments.listsegments.pagesegments.getsegments.getSegmentforecasts.listforecasts.pagepipelines.listpipelines.pagecontracts.listcontracts.pagecontracts.obligationscontracts.obligationPagecontacts.listCompaniescontacts.companyPagecontacts.listPeoplecontacts.personPagecontacts.getCompany,getPersoncompanyById,personByIdmailSync.accountsmailSync.accountPagemailSync.threadsmailSync.threadPagemailSync.threadmailSync.getThread -
Pages the finance blocks by the block list contract (ADR 1077).
accountinggainsaccountPageandentryPage,bankinggainsaccountPageandbatchPage,billable-timegainsratePageandgetRate,expensesgainscategoryPage,reportPageandexpensePage,invoicesgainspageandget, andscoresgainsmodelPage, each with facets and a count. Every list takesq, sorts, array filters and a keyset cursor, and agetfor an unknown id returns anot_founderror. The SQL addspage_accounting_accounts,page_accounting_entries,page_bank_accounts,page_payment_batches,page_time_rates,get_time_rate,page_expense_categories,page_expense_reports,page_expenses,page_invoices,get_invoiceandpage_score_models, and the generated schema files needbetter-supabase upgrade. The array methods keep working and are deprecated.billingandcataloghave no list function to page, so they are unchanged.Old New accounting.accountsaccounting.accountPageaccounting.entriesaccounting.entryPagebanking.accountsbanking.accountPagebanking.paymentBatchesbanking.batchPagebillableTime.listRatesbillableTime.ratePageexpenses.categoriesexpenses.categoryPageexpenses.listexpenses.reportPageexpenses.listExpensesexpenses.expensePageinvoices.listinvoices.pagescores.modelsscores.modelPage -
Pages the status-list blocks by the block list contract (ADR 1077).
collectionsgainscollectionPage,collectionFacets,collectionCountandget, andreviewsgainsreviewPage,reviewFacets,reviewCountandget, with sorts, list filters andqover names, descriptions, titles and bodies.leases,passes,warranty,guestsandagent-checkout(sessions and mandates) acceptqon their pages. The SQL addspage_collections,get_collection,page_reviewsandget_review, and extends the leases, passes, warranty, guests and agent-checkout list functions with a search filter, so the generated schema files needbetter-supabase upgrade. The array methodscollections.list,reviews.list,assets.assets,leases.list,passes.list,warranty.list,guests.list,agentCheckout.listSessionsandagentCheckout.listMandateskeep working and are deprecated.Old New collections.listcollections.collectionPagereviews.listreviews.reviewPageassets.assetsassets.pageleases.listleases.leasePagepasses.listpasses.passPagewarranty.listwarranty.pageguests.listguests.pageagentCheckout.listSessionsagentCheckout.sessionPageagentCheckout.listMandatesagentCheckout.mandatePage -
The operations blocks follow the block list contract (ADR 1077).
tills,lims,maintenance,warehouseandmanufacturinggainpage,facets,countandgetmethods for tills, lims methods, maintenance meters, pick waves, count plans, putaway rules, bills of materials and work centers, andrfqs,shipments,lims,maintenanceandmanufacturingacceptqon their existing lists. The array methods stay as deprecated aliases until 0.70.Deprecated Use listTillstillPage,tillFacets,tillCount,getTilllims.listMethodsmethodPage,methodFacets,methodCount,getMethodmaintenance.listMetersmeterPage,meterFacets,meterCount,getMeterlistPickWavespickWavePageandgetPickWavelistCountPlanscountPlanPageandgetCountPlanlistPutawayRulesputawayRulePageandgetPutawayRulelistBoms,workCentersbomPage,workCenterPageandgetWorkCenterNew SQL functions are
page_lims_methods,get_lims_method,page_maintenance_meters,get_maintenance_meter,page_pick_waves,get_pick_wave,page_count_plans,get_count_plan,get_putaway_rule,page_boms,page_work_centers,get_work_centerandget_till.list_tillsandlist_putaway_rulesreturn a page whenpagedis true and the array otherwise. Runbetter-supabase upgradeand apply the migration. -
Pages the admin blocks by the block list contract (ADR 1077).
option-setsgainssetPageandgetSet,impersonationgainssessionPageandgetSession,consentsgainspurposePageandgetPurpose,compliancegainsframeworkPage,evidenceTaskPageandpolicyPagewith agetfor each,data-lifecyclegainssubjectRequestPageandgetSubjectRequest, andsequencesgainsenrollmentPageandgetEnrollment, each with facets and a count. Every list takes sorts, array filters and a keyset cursor,qwhere the entity searches text, and agetfor an unknown id returns anot_founderror. The SQL addspage_option_sets,get_option_set,page_support_sessions,get_support_session,page_consent_purposes,get_consent_purpose,page_control_frameworks,get_control_framework,page_evidence_tasks,get_evidence_task,page_compliance_policies,get_compliance_policy,page_data_subject_requests,get_data_subject_request,page_sequence_enrollmentsandget_sequence_enrollment, and the generated schema files needbetter-supabase upgrade. The array methods keep working and are deprecated. Entity lists can now omit the tenant, which the platform-wideimpersonationlist uses.Old New optionSets.listoptionSets.setPageimpersonation.listimpersonation.sessionPageconsents.purposesconsents.purposePagecompliance.frameworkscompliance.frameworkPagecompliance.evidenceTaskscompliance.evidenceTaskPagecompliance.policiescompliance.policyPagedataLifecycle.dataSubjectRequestsdataLifecycle.subjectRequestPagesequences.enrollmentssequences.enrollmentPage -
Pages the SSO, service account and API key blocks by the block list contract (ADR 1077).
ssogainsdomainPage,getDomainandproviderPage,service-accountsgainsprincipalPage, andapi-keysgainskeyPage, each with facets and a count. Every list takes sorts, array filters,qand a keyset cursor, and agetfor an unknown id returns anot_founderror.keyPagewithout anorganizationIdlists the caller's personal keys, and the app's own fields are parsed on every row ofkeyPageandprincipalPage. The SQL addspage_organization_domains,page_sso_providers,page_service_principalsandpage_api_keys, and the generated schema files needbetter-supabase upgrade. The array methods keep working and are deprecated.Old New sso.domainssso.domainPagesso.providerssso.providerPageserviceAccounts.listserviceAccounts.principalPageapiKeys.listapiKeys.keyPage -
An entity page's
seedtakes four more keys, sogencan write demo rows for pages it could not seed before.fieldssets the value of an input field by its name (a scalar for every row, or a list that rowireads atimodulo its length), which seeds a risk'scategorywith the block's configured categories.rowsdeclares the rows by hand for a block with no input schema that fits, andtableandtenantname the table when the block declares none. The descriptor stays atapiVersion: 1.gennow stops withconfig_invalidwhen aseedhas no table instead of writing nothing. Theperiodsblock exportsperiodInputSchema, the input ofcreatePeriod, so a periods page seeds through it andgenwrites aperiods.form.tsfor the page. -
Security: the service-role AI blocks
prompts,ai-evalsandai-guardrailsdid not check which organization or permission a call acted for, so an app that skipped its own check could read or write another organization's prompts, datasets, runs and decision log. Each block now takes an optionalaccess({ organizationId, allowed, permission }). With it, every method fails withforbiddenunless the caller has an organization and the permission, a call must name that organization, a dataset or run of another organization reads asnot_found, anddecisions.purgeis refused. Without it the blocks behave as before.ai-evalsalso gainsdatasets.getand theget_eval_datasetSQL function, whichupgradewrites into the module; runbetter-supabase upgradeand apply the migration it generates. Apps that call these blocks for a signed-in caller should passaccess. -
The pgTAP file that
gen.entityPageswrites per page (scale_list_<name>.test.sql) now turnsenable_sort,enable_incremental_sortandenable_bitmapscanoff next toenable_seqscan. A sort that no index serves and a facet count that is not an index-only scan fail on any table size, including the few rows of a local seed. Runbetter-supabase gento rewrite the files. -
The
attachments-uploader,related-items-panel,subject-timeline,sequence-builder,quote-builder,contact-detail,deal-boardandcommand-searchrecipes show the new example sources. The record sections now take a subject (customer,company,personordeal) instead of a customer id, the sequence builder renders one sequence on its own page, and the command search can open a create dialog with?new=1. -
doctorno longer reports BS503 for an exportedSUPABASE_JWKSwhose keys the running stack's JWKS URL serves, such as the local public keysenv:localwrites. Keys the stack does not serve are still reported. -
The generated list and export routes of an entity page with
tenantOptionanswer 403 when the caller has no organization, and pass the option inside thepageandfacetsoptions. -
genno longer writes a facet index that the table already has. A page whose facet matches a block's own index ((tenant_id, status)) got a second, identical index and doctor reported it as a duplicate index. The check compares the btree column lists in the snapshot and ignores the*_page_idxindexesgenwrote earlier, so a second run changes nothing. Sort indexes are always written, because the snapshot has no sort direction. -
The
better-supabaseskill now carries one block reference per category (references/catalog-<category>.md), generated from the block manifests. Each lists the blocks of the installed version with their client, entities, permission keys, events, ports, actions and env keys.references/catalog-index.mdadds the category, preset and glossary tables, so none of them drifts from the package. -
Fix:
better-supabase genacceptssearch({ title, body }orfalse) on an entity underblocks.<name>.names, as the config type and ADR 0831 already allowed. It failed with "blocks.contacts.names: Invalid type". -
The org-switcher UI recipe in the docs and the skill reference now names the trigger from its visible text plus a screen-reader suffix, instead of an
aria-labelthat differed from the visible text, and hides the decorative mark from assistive technology. -
The risk register UI recipe now sorts by residual score, number and next review date, and reads its list state from the generated
risksList.
0.66.0 (2026-11-13)
-
Event verbs, hint prefixes and block keys follow one rule, and
pnpm check:namingenforces it (ADR 0699). The SQL moduleswebhooks-outandwebhooks-inare the blockswebhooksandincoming-webhooks, ten hint prefixes carry the block they come from, and two events use the lifecycle verbupdated. Runbetter-supabase codemod namingto rename the config keys, thenbetter-supabase upgradeanddb diff; the data migration renames the block's row inbetter_supabase.blocks, so installed modules keep their version and mode. Outbox rows and logged errors keep the names they were written with.Old New blocks["webhooks-out"],blocks["webhooks-in"]blocks.webhooks,blocks["incoming-webhooks"]message.editedmessage.updateddrive_node.document_saveddrive_node.document_updatedEVAL_*(ai-evals)AI_EVAL_*HOSTNAME_*(domains)DOMAIN_*SUPPORT_*(impersonation)IMPERSONATION_*CARE_*(clinical-decision-support)DECISION_SUPPORT_*BOM_*(manufacturing)MANUFACTURING_BOM_*SSF_*(security-events)SECURITY_EVENT_*TIMESHEET_*(time-entries)TIME_ENTRIES_TIMESHEET_*FIELD_*(custom-fields)CUSTOM_FIELD_*PRESCRIPTION_*(e-prescribing)E_PRESCRIBING_*WEBHOOK_IN_*(incoming-webhooks)INCOMING_WEBHOOK_*The type
DateBucketArgs(exported frombetter-supabase/list) is nowDateBucketOptions, becauseArgsis a banned suffix.codemod namingrewrites it. -
Bookings series expand through the shared recurrence core, and
better-supabase/recurrenceexportsparseRruleandformatRrule.booking_series_startsnow callsrrule_occurrences(thebookingsmodule requiresrecurrence), so a series keeps its local time across a daylight saving change exactly like a calendar event. Runbetter-supabase upgradeanddb diffto pick up the new function.parseRecurrenceandformatRecurrencekeep their signatures;formatRecurrencenow leaves outINTERVAL=1, and a malformed part such asCOUNTwithout a value throwsInvalid RRULE part. The digest loop moves into a shared helper that notifications call, and ADR 0719 replaces ADR 0197.Old New booking_series_startsloops over days in SQLbooking_series_startscallsbetter_supabase.rrule_occurrencesBookings parse RRULE text with their own parser parseRruleandformatRrulefrombetter-supabase/recurrencebookingsmodule requiresmemberships,permissionsalso requires recurrenceformatRecurrence({ freq: "daily", interval: 1 })returnsFREQ=DAILY;INTERVAL=1returns FREQ=DAILY -
Three blocks get the reads and clients the example app was missing. Run
better-supabase genanddb diffto pick up the new functions.Before After field-encryptionhad no member readfield_key_status()andcreateFieldEncryption().keyStatus()frombetter-supabase/blocks/field-encryptionvercel-marketplacereads needed the service roleinstallationFor(tenant)andresourcesFor(tenant)for tenant members, andVERCEL_MARKETPLACE_CLIENT_IDandVERCEL_MARKETPLACE_CLIENT_SECRETin the manifest envimpersonationhad no client, apps calleddb.$client.schema("api").rpc(...)createImpersonation()frombetter-supabase/blocks/impersonationwithrequest,approve,start,endandlistSessionProviderreadcaller_authz_version()fromapionlyschemaprop onSessionProviderandrealtimeVersionSource, defaultapidoctorBS502 read only the app's.gitignoreit reads the files up to the repository root and ignores !linesgen --checklisted stale filesit adds a subject, search and other count ( data.drift) -
Updates can refuse a stale write, creates can be retried safely, and block controllers can write optimistically. A change in
tasks.updateanddeals.updatetakesexpectedVersion(the row'supdatedAtas you read it) and is refused with aconflicterror, hintSTALE_WRITE, when the row changed since.tasks.create,deals.createandquotes.createtakeidempotencyKeywhen their creator getsidempotency: createIdempotency(...).createBlockMutationand theuseBlockMutationhooks takeoptimistic, built withoptimisticUpdate,optimisticArchiveoroptimisticReorder.better-supabaseexportsisStaleWrite,STALE_WRITEandstaleWriteError, andEntitySurfacegainsexpectedVersionandidempotent. Re-runbetter-supabase upgradeto install the changedupdate_tasksandupdate_dealsfunctions; their signatures do not change.Before After update({ changes: [{ taskId, field, value }] })update({ changes: [{ taskId, field, value, expectedVersion: task.updatedAt }] })create({ organizationId, input })ran again on retrycreate({ organizationId, input, idempotencyKey })returns the first resultuseBlockMutation(tasks, "update", { engine, instance })useBlockMutation(tasks, "update", { engine, instance, optimistic: optimisticUpdate({ ... }) }) -
Subjects get labels, parties and declared composition.
subjects.label(refs)returns a label for every subject (its title, or its id withfound: false), batched bybatchSubjects.createPartyResolverinbetter-supabase/blocks/subjectsresolves a name, initials, an avatar URL and a page for any subject fromsubjects.labeland one reader per subject type.defineBlocktakeslinks(written withblockLink) andconcerns, and every block that has SQL links or concerns declares them. A subject whose SQL module names no search registration now registers its title column, with the body columns of its manifest entity'ssearch, andblocks.<name>.names.<entity>.searchreplaces the columns or turns it off withfalse. Apps that install thesearchblock runupgradeand generate a migration for the new search triggers.Subjectsgainslabel, so a hand-writtenSubjectsdouble adds it.Before After A subject reference has no text subjects.label([{ type, id }])Pages join contacts, employees and profiles by hand createPartyResolver({ label: subjects.label, readers })Links and concerns live in SQL NAMESonlydefineBlock({ links: [blockLink(...)], concerns: ["search"] })17 subjects have no search registration Title column by default; names.<entity>.search: { title, body }orfalseA custom Subjectsobject withoutlabeltype-checksAdd label, for examplelabel: (refs) => labelsOf(resolve, refs) -
Block errors name their fields and carry default messages.
invalid_inputerrors have an optionalfields: [{ path, code, message }](build one withinvalidInput(message, fields), or raise{"fields": [...]}in theDETAILof an22xxxerror in SQL), andtoProblemsends them as afieldsmember. The newbetter-supabase/blocks/messagesentry exportsBLOCK_HINT_MESSAGES(one English message per hint code, keyed by the code, which is also the next-intl key) withhintMessage,blockErrorMessageandfieldMessages.createBlockstakeslocaleandhintMessagesand rewords errors raised in SQL through them.better-supabase/reactexportsErrorMessagesProvideranduseErrorMessage. The tags block returns aTAG_NAME_REQUIREDfield error for an empty name, and a few clients raise hint codes thatBlockHintsnow lists.Before After A hand-written useErrorMessagehook per appuseErrorMessagefrombetter-supabase/react, with anErrorMessagesProviderA sentence per error kind and no text for a hint code blockErrorMessage(error) ?? yourKindMessage(error)dbError("invalid_input", message, { hint })with no fieldinvalidInput(message, [{ path, code, message }]){ kind: "invalid_input" }carries no input nameserror.fieldslists the inputs, when the block names them -
Block reads have one list status and a realtime refetch.
blockListStatus(state)maps auseBlockQuerystate toBlockListStatus(loading,empty,errororready), andblockRealtimeRefetch(block, entity, source)returns therefetchOnof an entity that declaresrealtime: true. Both are exported frombetter-supabase/react,/vue,/svelteand/solid.Before After if (list.status === "loading") ...per listblockListStatus(list).kindrefetchOn: { source, types: ["task.created"] }refetchOn: blockRealtimeRefetch(tasksBlock, "task", source) -
The
employeesblock has a record binding.employeeContractsBindingloads an employee's contracts on the employee's page, reads again onemployee.updatedandemployee.deleted, and has aremovewrite that needsoptions.contracts: "editable".better-supabase/blocks/employeesexports it, andemployeesBlock.recordis set.Before After employeesBlock.recordisundefinedemployeesBlock.recordisemployeeContractsBindingContracts loaded by hand on the detail page bsb.record("employee", id)includes the contracts -
Block manifests declare their entities.
defineBlocktakesentities, one entry per entity withmutability(editable,append-only,state-machineorread-only), optionalsorts,facets,search,realtimeand more, and anemitsflag per method. Every built-in block declares its entities, andBlock.entitiesandAnyBlock.entitiesexpose them.better-supabase/blocksexports the list contract typesPageOptions,ListPage,FacetResult,FacetValueandCount({ value, exact }), theEntitySurface,BlockEntities,EntityMutabilityandEntityMethodtypes, and theENTITY_METHODSandENTITY_MUTABILITIESlists.renameBlockrenames the keys ofentities. No behavior of an existing method changes.Before After No declared entity surface defineBlock({ entities: { task: { mutability: "editable" } } })ListPagenot exportedListPage,PageOptions,FacetResultandCountfrombetter-supabase/blocks -
field-encryptionrotates keys and says what they protect. EachkeyStatus()entry now carrieskeyCreatedAt,keyRotatedAt,lookupKeyCreatedAt, the app tablecolumnsthat owner's kind of key encrypts and the number of encrypted customfields, still without key material.rotateKey(owner)(SQLrotate_field_key) replaces the data key in Vault and encrypts every value sealed under it again in one transaction, with the newfield_encryption.managekey (owner and admin by default), and recordsfield_key.rotated. Columns your own trigger seals withfield_sealgo in the newblocks["field-encryption"].options.sealedlist so a rotation covers them. Runbetter-supabase genanddb diff;gen.permissionCatalogadds the key. -
gencan write the permission catalog from the block manifests.entities.<key>.permissionsis now validated: a key is<block>.<entity>.<verb>(verbsread,create,update,archive,delete,export,import,manageplus named domain verbs), and a two-part key a module already checks stays valid.gen.permissionCatalog: true(catalog model) writes a_better_supabase_permission_catalog.sqlmigration with a row for every key the installed blocks check or declare and the default grants of theowner,adminandmemberroles, so a new block's pages no longer answer 403 until a hand-written migration runs. It also writespermission-scopes.tswithapiKeyScopesandoauthScopes.entities.<key>.recordAccess: "team"declares record-team access. The advisories, commissions, deadlines, leave, periods and referrals manifests declare their keys.Before After A catalog migration written by hand for each new block (EX-807) gen: { permissionCatalog: true }, thengenwrites the migrationentities.<key>.permissionsis free-form and nothing reads itValidated as <block>.<entity>.<verb>;genreads itAPI key and OAuth scope lists edited by hand apiKeyScopesandoauthScopesfrompermission-scopes.tsNo manifest field for record-team access entities.<key>.recordAccess: "team" -
blocks.hiring.options.ratingMaxsets the highest scorecard rating (default 4), so an app can score from 1 to 5. The scorecards table check and thesubmit_scorecardrange check follow it. -
Nine blocks (agent-checkout, appraisals, dam, lims, maintenance, rfqs, risks, tills and warehouse) page, facet and count through one shared implementation. Each list entity declares
sorts,facets,filtersandsearchin its manifest, and the SQL list function serves the page, the facet values and the count, so the three always describe the same rows (ADR 0749).better-supabase/blocksexportsEntityListSurface,EntityList,FacetOptionsandCountOptions, andEntitySurfacegainsfilters. Thessoblock keeps its SCIMstartIndexandcountpaging, because it is not an entity list. Each block page method now takesPageOptions, the page options interfaces and thetotalandtotalCapoptions are removed, anddamandmaintenancegaingetRight,getPlanandgetCalibrationwith the SQL functionsget_usage_right,get_maintenance_planandget_calibration. Apply the generated migration to adopt the new list functions.Before After RiskPageOptions,CheckoutSessionPageOptions,AgentMandatePageOptions,AppraisalPageOptions,DamUsageRightPageOptions,LimsSamplePageOptionsPageOptionsfrombetter-supabase/blocksMaintenancePlanPageOptions,MaintenanceCalibrationPageOptions,RfqPageOptions,TillSessionPageOptions,PickListPageOptionsPageOptionsfrombetter-supabase/blocksrisks.page({ status: "open" }), one value per filterrisks.page({ filters: { status: ["open", "assessed"] } }), a list per filterrisks.page({ search: "supplier" })risks.page({ q: "supplier" })Newest-first order only sort: { by: "nextReviewOn", direction: "asc" }, one of the entity's declaredsortspage({ total: true, totalCap })returnedtotalandtotalCapped<x>Count(options)returns{ value, exact }No facet counts risks.facets()and<x>Facets()return the values of each declared facet with{ value, exact }countssessionPage,mandatePage,appraisalPage,rightPage,samplePage,planPage,calibrationPage,rfqPage,pickListPagewith scalar filtersThe same names, with list filters, plus sessionFacets,sessionCountand the matching pair per listA detail page reads a usage right, a maintenance plan or a calibration from the list getRight,getPlanandgetCalibrationUnknown sort, filter or facet reached the database An invalid_inputDbErrorwithfield: "kind"before any call -
The
invoices,quotesanddealsblocks have record bindings.invoicesBinding,quotesBindinganddealsBindingload the invoices, quotes or deals that name a record as their company or contact (a deal also by its contacts), read again on the block's events, and take the organization from the block'stenantoption. Each block client getslist({ subject, limit })and a SQL function (list_invoices_for_subject,list_quotes_for_subject,list_deals_for_subject); runbetter-supabase upgradeand apply the new migration. The three options types accepttenant.Before After invoicesBlock.record,quotesBlock.recordanddealsBlock.recordareundefinedThey are invoicesBinding,quotesBindinganddealsBindingInvoices, quotes and deals of a record read by hand invoices.list,quotes.listanddeals.listwith asubject -
reminders.listForCaller()returns every reminder the caller set in the tenant, with the subject each one is on. Thelist_my_remindersfunction takes its subject arguments as optional and addssubjectTypeandsubjectIdto each entry, so a "my reminders" page no longer needs one call per subject. Runbetter-supabase genanddb diffto pick up the new function. -
Search can browse and page. A record type's
search.facetslists columns that the index keeps in a newfacetsjsonb column (GINjsonb_path_ops), andsearch_documentsgets asort_keycolumn with a btree index for browsing. The newsearch_page(q, types, tenant, filter, after, page_size)function, andSearch.page, return{ items, nextCursor }: withoutqit browses by title, withqit ranks likesearchover at most 500 candidates, andfilterkeeps documents whose facets contain it.searchis unchanged. Runbetter-supabase upgradeanddb diff; the module's data file reindexes existing documents. -
The last block columns that broke the naming rules are renamed: timestamp columns end in
_at, and a user reference names the user's role.better-supabase upgradewrites a migration that renames them in place, so no row moves (vercel-marketplace 3, billing 5, impersonation 3); then rundb diff. The SQL functions keep their parameter names (period_start,period_end), the support session rows keep theirtarget_user_idkey and TypeScript keepstargetUserId,periodStartandperiodEnd. Code that selects the columns directly needs the new names.Table Old New marketplace_invoices,marketplace_meter_reports,billing_native_subscriptionsperiod_startperiod_starts_atmarketplace_invoices,marketplace_meter_reports,billing_native_subscriptions,billing_subscriptionsperiod_endperiod_ends_atsupport_sessions,support_requeststarget_user_idtarget_idThe
jsonbthatcreate_native_subscriptionreturns names the periodperiod_starts_atandperiod_ends_attoo. -
createVercelMarketplacetakesclientIdandclientSecretas optional and reads them fromVERCEL_MARKETPLACE_CLIENT_IDandVERCEL_MARKETPLACE_CLIENT_SECRETin the newenvoption (env: process.env), so a settings page can build the client forinstallationForwithout holding the secret. Without them,verifyWebhookanswersfalse, andhandleWebhook,exchangeSsoand the Partner API's token check return aforbiddenerror with the hintMARKETPLACE_CREDENTIALS_MISSING, so a missing client id never matches a token without an audience.VERCEL_MARKETPLACE_ENVnames the two keys. -
Offline attachments no longer break signed uploads. Storage checks upload permission by inserting a trial
storage.objectsrow and rolling it back, and that row carries the request's own content type and no size. Theattachment_object_uploadedtrigger now fires only on objects with a size, socreateSignedUploadUrlfor a pending attachment stops failing with check violation 23514 on the mime type. Runbetter-supabase upgradeanddb diffto pick up the new trigger. -
The audit test generator follows a renamed table. A migration that runs
alter table ... rename tonow moves the table'saudit()orbsb_audittrigger registration to the new name, sogenandupgradestop writing pgTAP checks for the old name, which no longer exists, and stop reporting the generated audit test as edited by hand once it is fixed. -
Doctor BS502 asks
git check-ignorewhether an env file with secrets is ignored, so.git/info/exclude, the global excludes and!negations count, and a committed env file is reported even when a pattern matches it. Outside a git work tree it reads each.gitignorefrom the app up to the repository root against paths relative to its own folder, with negations, instead of matching every pattern against the app's paths. -
genandupgradeno longer serve block SQL from a cache an older generator wrote. The cache key hashed only the CLI's own chunks, while the built CLI loads the SQL generator frombetter-supabase/sql, so after an upgrade that changed a block's subjects a localgencould drop search triggers that CI kept. The key now covers all ofdist(orsrcin a checkout).gen --checkalso reports a file with gen's header that the run no longer writes even when the local manifest is missing, so CI and a local run agree on leftovers.powersync streamswrites its own header, sogennever takes its files for leftovers. -
better-supabase codemod namingno longer pins a block'stenantcolumn to the name thatsql.tenantColumnalready gives it. That pin wrote acolumns.<table>.tenantentry whichupgradethen refused. -
The service worker that
initwrites for Next.js keeps hashed/_next/staticfiles in their own cache, capped at 512 entries and kept across deploys. It skips/_next/static/service-worker/and stores only responses markedimmutable, so the cache no longer grows with every deploy. -
db.$rpcreturns table rows in app casing in a schema withlazyTables, also when the function's result table has not loaded yet. The call now loads that table before it builds the select and decodes the rows. Before, the row came back with database keys such ascreated_at, and the function kept that result for the rest of the process, so a later call stayed undecoded even after the table loaded.
0.65.0 (2026-11-12)
- The hiring block passes its application row to its events, so
blocks.hiring.events.payloadcan add row columns toapplication.created,application.hired,application.rejected,application.retracted,scorecard.submittedandinterview.scheduled, and job columns tojob_opening.openedandjob_opening.closed. A payload value can also be{ sql }, an expression that reads the row as{row}, for a value from a joined table such as the job title.
0.64.0 (2026-11-12)
- The search block indexes more record types. The quotes, invoices, orders, requests for quotation, tills, bookings, assets, leases, expenses, shipments, contracts, forms, documents, incidents, care plans, laboratory, maintenance, dispatch and ledger modules now declare a
searchtitle on their main subject, sosearch(q)finds their records once you runbetter-supabase upgradeand apply the migration. The migration backfills the index withsearch_reindex. - Doctor BS213 counts the authorization provider's
idsWithandmemberIdshelpers as tenant pins, next totenant_ids_withandmember_organization_ids. A write policy with anorstill pins the tenant column when each branch pins it or writes a null tenant under a platform check, such as(org_id in (select ids_organization('notes.create'))) or (org_id is null and (select is_platform('platform.notes.manage'))). A column every insert policy pins to the caller,created_by = (select auth.uid()), no longer counts on insert. - The
inbox-threadsrecipe shows the conversation queue of the example app: search and status, assignee and channel filters in the URL, rows that link to/inbox/<id>, and a queue that reloads over Realtime. doctorno longer reports BS610 when a"use cache: private"function calls a method that has the name of another private function, such asdb.tills.getSession(id)next to agetSessionhelper.- Fix
db.$search(and$many,$stats) going missing on the server when a module that only defines a list query loads the lean client runtime after the full one. A lean install no longer replaces an installed full runtime, sodb.$search is not a functionno longer fails pages that mixbetter-supabase/listover the client app with a serverdb. - Fix
useRecordListStatedropping the facets of a list. nuqs keeps each facet under its own URL key (status=active), but the hook passed that flat state totoSearchParams, which reads facets fromfacets, sosearchParamsandquerynever carried a facet and a list route called with them returned every row. The hook now moves the facet keys underfacetsusing the list'sfacets, solist.set({ status: ["active"] })reaches both the URL and the query.
0.63.2 (2026-11-12)
- Doctor BS386 accepts a per-row check after an
in (select ...)set check only when the check passes the whole row, as inid in (select note_ids('read')) or can_note(notes, 'read'). A check that reads a column after an unrelated set check, such asemployee_id in (select own_employee_ids()) or is_decider(id), is flagged again.
0.63.1 (2026-11-12)
- Doctor BS386 now flags a select policy that calls a
security definerfunction, or one with asetclause, once per row, even when it is a stable SQL function such ascan_note(notes, 'read'). Postgres never inlines such a function, so a list pays one call per row. The call is still accepted as theorfallback after a set check, as inid in (select note_ids('read')) or can_note(notes, 'read'). It also no longer flags a set helper in thefromof a subquery that is joinedlateralor wrapped in parentheses, or one whose arguments read a column of anotherfromitem such asmember.id.
0.63.0 (2026-11-12)
notifications.pagesorts byorder(newest,oldest,type,subjectorstatus, with_descforms) and filters onexcludeTypes,subjectIdsandanyOfgroups, so a view such as "everything that is not an open request" pages in SQL.searchinlistandpagealso matches the actor's name when theprofilesmodule is installed. Both return up to 500 items (was 200), andpagereturns thelimitit applied, so a caller sees when a request was clamped.notification_pagetakesexclude_types,subject_ids,any_ofandorder_by; the notifications module goes to version 11.- A queue schedule can name a
probe, a SQL function without arguments that returns whether there is work. A due schedule whose probe returnsfalsestays due and enqueues nothing, so every-minute schedules stop enqueueing a job on each idle drain tick. The outbox, webhooks-out and webhook-inbox modules addoutbox_has_work(),webhook_deliveries_has_work()andwebhook_inbox_has_work()to use as probes.listSchedulesreturns each schedule's probe, andensureSchedulesrewrites a schedule whose probe changed. The queue module goes to version 12. - Doctor BS219 attributes a containment filter in a function to the tables that function names. Before, it joined every function definition together, so a function that only named a table flagged that table's jsonb column whenever any other function used
?or@>on a column of the same name. unreported_usagereads each tenant's plans and entitlements once and each quota once per tenant and meter, instead of once per counter row, and computes each window start once per tenant, period and day. On 1,000 counters of 20 tenants it callstenant_entitlements20 times instead of 1,008 andusage_window_start102 times instead of 1,000.
0.62.0 (2026-11-12)
blocks.<name>.eventstakes{ payload: { "<event type>": { <payload key>: "<column>" } } }, which adds columns of the event's row to the payload the module writes to the outbox. An app that keeps its own columns on a block's table, such as acustomer_idontasks, no longer has to write a secondtask.createdwith them. Rendering fails for an event type the module doesn't record and for an event the module writes without a row. The tasks block passes its row to every event.events: trueandevents: falsekeep working.- Breaking:
db.$decode(table).row()and.rows()return anAsyncResult, so$decodeworks with lazy tables (gen.serverTables: "lazy"). It loads the table and every table an embedded relation in the value reaches before it decodes; before, it threwunknown tablefor a table the process had not loaded yet. Addawaitwhere you read the result:const customers = await db.$decode("customers").rows(rows). A failure that is not a database error is now an error result instead of a thrown exception. list_incoming_webhooksandhooks.list()page:pageSize(up to 500) andskipreturn one page of a tenant's endpoints, andnewestFirstlists the newest first. WithoutpageSizethe call still returns every endpoint, oldest first. Runbetter-supabase upgradeto regenerate thewebhooks-inmodule.
0.61.1 (2026-11-12)
doctorBS386 no longer flags a volatile set helper in thefromof a policy subquery when its arguments read no column of the row, such asid in (select t.id from thread_ids('key') as t(id)). Postgres calls that function once and rescans its result. A helper whose arguments read the row is still flagged.
0.61.0 (2026-11-11)
-
Security, behaviour change: an API key now holds only the permissions its scopes map to.
cap_allows, and somember_can,canand every policy and module that asks them, checks a request with anapi_keyclaim against the key's scopes, mapped throughblocks.permissions.scopes. A key with*holds every permission except the interactive-only ones, and a key with no scopes holds none. Before, a personal key held every non-interactive permission of its user whatever its scopes, and only policies that calledhas_scopenarrowed it.To migrate, find the keys whose access shrinks (
select id, name, scopes from better_supabase.api_keys where scopes = '{}') and give each the scopes it needs, or rotate it with new scopes, before you deploy. Runbetter-supabase upgradeto regenerate thepermissionsmodule. The API keys docs page has a section on scopes and permissions. -
database.realtime.triggersand a topic'sbroadcastentries takededupe: "transaction", which sends each topic, event and payload once per transaction, so a bulk write or an audit log filled row by row sends one message per key instead of one per row.dedupeKeynames the payload fields that tell messages apart.upgradewrites the trigger withbetter_supabase.broadcast_once(), and the function itself, into therealtime.policiesoutput. It keeps the hashes in a transaction-local setting, so a commit or rollback clears them and a rolled-back transaction sends nothing. -
fromBase64removes ASCII whitespace before it computes the padding, so Postgresencode(..., 'base64')output wrapped every 76 characters decodes. -
Fix the drive set readers (
drive_readable_idsanddrive_drive_readable_ids) with provider row grants. They now ask the provider'srowsWithfunction once per mapped role, with the candidate ids as onetext[], instead of once per node. Runbsb sql upgradeto apply the new function bodies. -
Security: ownership transfer, organization deletion, impersonation start, platform invitations and SSO management are now interactive-only.
cap_allowsrefuses their permission keys to an API key, an OAuth client and an agent or otheractchain, whatever the token's scopes, andcan_assignrefuses the organization owner role to the same callers.create_api_keyrefuses an interactive-only key as a scope withAPI_KEY_FORBIDDEN, and existing keys that carry one get nothing from it. Add keys withblocks.permissions.interactiveOnlyorauthorization.delegation.interactiveOnly. An API key, OAuth client or agent that creates or rotates a key may only give it scopes the token holds itself. Runbetter-supabase upgradeto regenerate thepermissionsandapi-keysmodules. -
--jsonkeeps a command's warnings in thewarningsfield of the result document on stdout. The line on stderr stays. -
The package ships
api/naming.jsonand exports it asbetter-supabase/api/naming.json, the file the 0.58 migration guide,codemodand doctor rule BS260 point to. -
The pgTAP helper
tests.age_import_runis a plpgsql function, so the pgtap module loads without the imports block installed. -
Say
config.recordTypesin error messages, generated comments, JSDoc and docs where they saidconfig.subjects, the keyrecordTypesreplaced in 0.54.scripts/check-naming.tsnow fails on a former config key in a comment, a string or a docs page. Runbetter-supabase gento refresh the comment ingenerated.ts. -
AuthzSubjectSeedhas atenantfield: the tenant a bootstrap subject is restricted to by the provider'ssubjectForTenant, ornullfor the whole subject.accessForsets it from the newBootstrap.subjectTenant, which the bootstrap wrapper reports assubject_tenant(runbsb upgradeto regenerate it). An authorizer that caches the seed by user and version must key it by the tenant, andtestAuthorizerchecks that a seed for another tenant is ignored. -
Describe CLI result v2 and the exit codes 0, 1, 2, 65, 130 and 143 in the
better-supabaseskill, in place of the v1 envelope and the unused exit code 3. A docs test now compares the skill's exit codes with the CLI errors page. -
Stop writing
drop event trigger if existsinto the declarative900_better_supabase_999_unscoped.sqlfile, whichsupabase db schema declarative syncrejects.better-supabase sql upgrade --checknow fails when a declarative module file contains adrop event triggerline. Runbetter-supabase upgradeto rewrite the file.
0.60.0 (2026-11-11)
-
Two batch reads for approval sweeps and bill lists.
invoices.approvalStatuses(invoiceIds)(purchase_invoice_approval_statuses(invoice_ids uuid[])) returns where each purchase invoice stands in approval as a map keyed by invoice id, andapprovals.getMany(ids)(get_approvals(request_ids uuid[])) returns requests with their decisions and items in the order asked. Both skip an id the caller cannot read instead of failing the batch. -
s.$fn.<name>(args, { tables })declares the tables a SQL function reads, sobsb.tagsandbsb.cached({ readSet })tag a cached function payload with them and a mutation of one of those tables revalidates it.bsb.tagsalso takes a function call alone or in a list. TheFunctionSpecandFunctionSpecOptionstypes are exported. -
list_comments,comment_countsandmessaging_messages_jsoncheck each conversation once and read its messages by key, so a read no longer weighs every conversation the caller can see across tenants. What each caller sees stays the same.list_comments_uncheckedandmessaging_messages_json_uncheckedreturn the same rows without a check, for an app's ownsecurity definerfunction after its own check; they are granted toservice_roleonly. -
Doctor's N+1 checks report fewer false positives and catch more real ones. BS634 skips a loop that calls a write such as
decideRequestorservices.agenda.assignTask, or a side effect such asnotifyAgendaUpdated(...),publish...,send...orenqueue.... For a search term or a JSON value it suggests one read with anORof the conditions or an RPC that takes an array, and says when no batched form applies, instead of aninfilter. It now also reads the callback of a per-item helper such asmapInChunks(ids, 20, async (id) => ...), achunk.map(...)inside a chunk callback, and services passed as typed parameters (customers: CustomersService). BS635 names a nested include for two tables that both reference a third (include: { task: { include: { invoiceTasks: true } } }), and reports a dependent read that shares aPromise.allwave with other reads of the same rows as info, since an include saves a request there, not a wait.BS609, BS634 and BS635 targets name the file, the enclosing function and the callee (
src/lib/tasks.ts#loadTask:db.quoteTasks.list,#2for a second call), so baseline entries survive edits elsewhere in the file. Entries with the oldfile:linetarget still match, anddoctor --update-baselinerewrites them with their reasons.doctor --snapshotreads the CLI's cached snapshot file ({ key, snapshot }), anddoctor --only BS609,BS634,BS635runs without a database or snapshot, with an info finding that no include could be named.
0.59.0 (2026-11-11)
- Doctor reports database reads made once per item of a loop or a
mapcallback (BS634) and reads that wait for an earlier read of a related table (BS635), and names the fix: anincludeon the outer read when the snapshot has a foreign key between the tables, otherwise one read with aninfilter. Both are warnings; accept a deliberate case in the baseline or add the code totooling.doctor.ignore. The newtooling.doctor.parallelReadsoption (default 3) sets how many reads onePromise.allmay await before BS609 suggests a read set. db.$manyasks a read set's permission gates in one wave instead of one after another, and starts the set's function entries beside its table batch when the connection can't send the whole set as one call. The results are the same.
0.58.3 (2026-11-11)
-
Lazy server tables (
gen.serverTables: "lazy") now load the tables a call reaches through relations before the query is built, so includes, nested includes, relation filters, counts andorderByacross a relation no longer fail withunknown tablein a fresh process.specTablesno longer caches the fallback for a table that has not loaded yet.blocks.<name>.indexes.skipand tables mapped tonullkeep the comments above a dropped statement, so a module file whose first statement is skipped keeps its-- better-supabase moduleand@bsb-blockheader, and the nextupgradereads the right version.
0.58.2 (2026-11-11)
- With an authorization provider that defines
isApprover,approval_eligible_idsasks it per pending request inside the set query instead of callingapproval_eligiblefor every request no set rule matched, so a policy branch such asid in (select better_supabase.approval_eligible_ids())no longer re-runs every approver rule per request in every tenant. 2,000 pending requests in ten tenants: 349 ms before, 5.5 ms after. Runbetter-supabase upgradeand generate a migration. list_comments,get_commentand the other comment reads look up the record's conversation and work items by key, andmessage_authorschecks only the conversations of the messages it was given, so a comment read no longer checks every conversation the caller can read. Reading one comment as a member of 50 tenants with 150 record conversations askscan_subject5 times instead of 154. Runbetter-supabase upgradeand generate a migration.usage_overviewreads the tenant's plans and entitlements once per call instead of once per quota row. Runbetter-supabase upgradeand generate a migration.
0.58.1 (2026-11-11)
- A table loaded lazily (
gen.serverTables: "lazy") keeps its property ondbwhen a block instance has the same name, as an eager table already did; the block stays underdb.$blocks.codemod owned-columnsreads the live database when it can connect and keeps an optional column that the database or the snapshot has, instead of reading the snapshot alone. A derivedsameTenantentry setssharedwhen the referenced table's tenant column may be null, so global rows such as shared roles pass again; a not-null tenant column keeps the strict check. Theentax seeds no longer create theSTD,REDandZEROcodes without rates, and a seed table with no rows renders no emptyif. Doctor BS260 reports an old argument name only wherecodemod namingrenames it, so a local variable namedworkItemIdpasses, and the codemod no longer treats a value such as{ taskId: workItemId }as shorthand. The 0.57 to 0.58 guide covers search watches withoutcolumnsand the column renames in your own SQL functions.
0.58.0 (2026-11-11)
-
The servers no longer have
deleteAccount,suspendAccount,endSessionsorlastSignInsmethods, so a route or proxy that never calls them doesn't bundle their code. Import the functions from the newbetter-supabase/server/accountand pass the server first. Runbetter-supabase codemod account-calls.Old New bsb.deleteAccount(id, options)deleteAccount(bsb, id, options)frombetter-supabase/server/accountbsb.suspendAccount(id, options)suspendAccount(bsb, id, options)bsb.endSessions(id)endSessions(bsb, id)bsb.lastSignIns(ids)lastSignIns(bsb, ids)createNextstill drops the user's cached reads and session memo after each of them. -
bsb.action(options, fn, map)takes a third argument that maps the data of a successful call to another type, soActionResult<Row>can becomeActionResult<ViewModel>. The mapper may be async, runs after theinvalidatestags drop and turns a thrownDbExceptioninto the action's error.ActionMapperis exported frombetter-supabase/next. -
bsb.actiontakesinvalidates, a list of tables whose cache tags drop after a successful call (until now onlybsb.blockActiondid), and itsresultmapper may be async. -
Engagements are activities everywhere: the
engagement_subjects,engagement_recordings,engagement_notesandengagement_transcript_segmentstables areactivity_*, theEngagement*types areActivity*, hint codes start withACTIVITY_, and the mail-sync optionengagementTypeisactivityType. Three events use the lifecycle verbs. Runbetter-supabase codemod naming, thenupgrade; no data moves.Old New engagement_subjectsand the other three tablesactivity_subjects,activity_recordings,activity_notes,activity_transcript_segmentsEngagementInput,EngagementEventDataActivityInput,ActivityEventDataENGAGEMENT_NO_TRANSCRIBERACTIVITY_NO_TRANSCRIBERblocks.mail-sync.options.engagementTypeblocks.mail-sync.options.activityTypevex_statement.savedvex_statement.updatedteam_member.removedteam_member.deletedreaction.removedreaction.deleted -
A column your own schema file adds to a block's table (
alter table ... add column) is a field of that block: its functions read and write it, and the block adds none of it.better-supabase codemod extra-columnsmovesblocks.<name>.options.extraColumns(and the*ExtraColumnsoptions) into the file that already alters the table, or into<table>.ext.sql, and removes the options from the config. -
upgradewrites module and data files only. Under pg-delta, the forward steps a schema diff can't express (renames, backfills, expression changes) go into<stamp>_better_supabase_reviewed_upgrade_<hash>.sql, marked-- destructive: reviewed; the migra workflow keeps<stamp>_better_supabase_block_upgrade_<hash>.sql.blocks.memberships.options.sameTenant.autoemits no trigger for a column that an app trigger already reads or writes throughnew.<column>, andcodemodnever rewrites a block file, even when a path names it. If you reference the old migration name in scripts, use the new one. -
A block that adds columns to your own table now adds a column before the columns whose checks read it, so applying the generated file no longer fails with
column "user_id" does not existon the contacts block over an existing table. -
Approval items take the columns your schema files add to
approval_itemsas fields. Pass them asfieldson an item inapprovals.request({ items })and read them fromfieldson each itemgetreturns. Upgrade: nothing to change for an app without such columns; runbetter-supabase upgradeto render the new reads and writes after you add one. -
Approval requests gain a
consumedstatus.consume_approval(consume()in TypeScript) now sets the status toconsumedas well asconsumed_at,ApprovalStatusincludesconsumed, and a check keepsconsumed_atset exactly when the status isconsumed.is_approvedstill answers true for a consumed request.The approvals module moves to version 6.
better-supabase upgradewrites a reviewed migration that allows the new status, moves requests consumed before (withconsumed_atset and statusapproved) toconsumed, and adds the check. Over a requests table of your own,consumekeeps setting onlyconsumed_atand leaves the status alone, so the app's status check or enum keeps working.Code with an exhaustive map over
ApprovalStatus, such as aRecord<ApprovalStatus, string>of labels, needs an entry forconsumed. -
Exported
*Argsand*Settingstypes are*Options, with no alias.better-supabase codemod namingrenames them in your code.RateLimitSettingsandIdempotencySettingsare part ofRateLimitOptionsandIdempotencyOptions,AccountingSettingsisAccountingSetupandBucketSettingsisStorageBucketOptions.Old New AgentPassthroughSettingsAgentPassthroughOptionsAddArgsAddOptionsAggregateArgsAggregateOptionsAssistantRunArgsAssistantRunOptionsBoundArgsBoundOptionsBulkActionArgsBulkActionOptionsCodemodArgsCodemodOptionsCountArgsCountOptionsDataListArgsDataListOptionsDeleteArgsDeleteOptionsDurableTurnAgentArgsDurableTurnAgentOptionsEveDispatchArgsEveDispatchOptionsEveScheduleArgsEveScheduleOptionsGenerationRunArgsGenerationRunOptionsGetArgsGetOptionsGuardsFindArgsGuardsFindOptionsIncludeArgsIncludeOptionsInitArgsInitOptionsKeysArgsKeysOptionsManyWriteArgsManyWriteOptionsMembershipsFindArgsMembershipsFindOptionsMigrateSchemaFirstArgsMigrateSchemaFirstOptionsOffsetPageArgsOffsetPageOptionsOffsetRangeArgsOffsetRangeOptionsOverloadArgsOverloadOptionsPresetSubjectSettingsPresetSubjectOptionsQueuePurgeArgsQueuePurgeOptionsReadArgsReadOptionsRemoveArgsRemoveOptionsTanStackStartHandlerArgsTanStackStartHandlerOptionsTanStackStartServerArgsTanStackStartServerOptionsTrashDeleteArgsTrashDeleteOptionsTrashFindArgsTrashFindOptionsUpdateArgsUpdateOptionsUpsertArgsUpsertOptionsUpsertManyArgsUpsertManyOptionsWriteArgsWriteOptionsWriteManyArgsWriteManyOptionsAccountingSettingsAccountingSetupBucketSettingsStorageBucketOptionsRateLimitSettingsRateLimitOptionsIdempotencySettingsIdempotencyOptions -
An asset due check stores the check type, the last completion, the result and a service-plan interval in days. The next due date is the last completion plus that interval. A repeat import updates the same check.
-
An asset import stores the make, model, model year, ownership and product. Identifiers import by type and value, and a repeat updates the asset that holds that value.
-
The attachments insert policy checks the upload permission with the tenant sets instead of one
can()call per row, so no block policy of any module callscan()per row any more (a registry test holds it forusingandwith check).better-supabase upgraderewrites the attachments module and the next schema migration replaces one policy. No data migration is needed. -
The attachments read and insert policies check the subject inline instead of calling
attachment_subject_readableonce per row. A member counting 40,000 attachments over 200,000 customers waits 8.7 to 15.6 seconds instead of 32 seconds, and counting 12,000 over 60,000 customers takes 73 ms once the tenant permission is also checked as a set. The function stays for callers that pass values.better-supabase upgraderewrites theattachmentsmodule and the next schema migration replaces two policies. No data migration is needed. -
blocks.audit.options.exempttakes{ class: "no-tenant-column", reason }, which leaves out every table that has no tenant column, in place of one entry per table. Doctor BS315 asks for the reason, as it does for a table glob. -
The audit log and the notification inbox read in index order on logs of millions of rows. After
better-supabase upgradeand a migration:list_audit_eventstakesentry_fields(summaryleaves out the old and new record,changedandmetadata), andaudit.listtakesfields.count_audit_eventstakescap, andaudit.listtakescountCap. New:get_audit_event(audit.get) andaudit_event_types(audit.eventTypes). The organization index gains theidtiebreaker, and the log gets(tenant, actor, occurred_at, id)and(tenant, event_type, occurred_at, id)indexes.list_notificationsandnotification_pageadd only the filters you pass, so the default inbox query reads the partial inbox index.notification_pagetakesbefore,before_idandtotal_cap, and returnshasMoreandtotalCapped.- Behavior change:
notification_pagecounts at most 10,000 matches (totalCap: nullcounts all), andnotification_countsstops each count at 100 (cap: nullcounts all). Show "99+" for a capped badge.
-
With
blocks.audit.options.partitionedon,upgradewritesbetter_supabase.convert_audit_log_to_partitioned(batch_size, drop_old). Call it as the service role, outside a transaction block, to move an existing audit log onto monthly partitions while it keeps taking writes. It copies in committed batches, takes a short lock that blocks writes but not reads for the last rows and the swap, and keeps the old table asaudit_events_unpartitioned. -
Row audit triggers skip the rows of an import that runs with
imports.audit: summarybefore the audit function starts. The trigger has awhenclause that reads the import session, so a 20-row insert and update batch now startsaudit_row_changezero times instead of once per row. A user who sets the flag without an import session is still audited.better-supabase upgraderewrites every module with block-table audit triggers, and the next schema migration drops and creates eachbsb_audittrigger. No data migration is needed. -
Bank accounts take a
holderand aprimaryflag.saveAccountaccepts both, andBankAccountreturns them. Settingprimary: trueclears the flag on the organization's other accounts in the same currency, so each organization has at most one primary account per currency. Runbetter-supabase upgradeto add theholderandis_primarycolumns tobetter_supabase.bank_accounts. -
Five block clients read many rows in one call, so a page no longer sends one request per row. Run
better-supabase upgradeand apply the new migration to add the functions.Block New method Replaces a loop of ai-chatruns.steps.listFor({ runIds, limit })runs.steps.list(runId)versionsgetMany(ids)get(id)hiringapplicationsForJobs({ jobIds, state })applications({ jobId })templatesgetMany(ids)get(id)care-plansgetMany(planIds)get(planId)Results keep the order of the ids you pass. An id that is missing or that the caller cannot read has no entry instead of failing the batch.
-
blocks.<name>.indexes.skiplistscreate indexnames the module should not create, when the app's own index already covers them.invoicescan skipinvoices_tenant_status_idx. A name the module does not create is an error. Doctor BS390 still reports an index that is a prefix of another.better-supabase upgraderewrites a module whose config setsindexes.skip, and the next schema migration drops the skipped index if it was already created. No data migration is needed. -
gen.blockModules: truewritesblocks/slices.ts, one config slice per installed block instance (commentsConfig), andblocks/permissions.tswith the permission keys.blocks.config.tscomposesblockConfigfrom the slices for server code, and a generated record file imports only the slices of the blocks it binds instead ofblockConfig. A client passes the slices it uses tocreateClient({ blocks }), and a record's own slices fill in the blocks the client leaves out. Runbetter-supabase gento write the files. -
The sessions bootstrap returns the caller's permissions when the authorization provider sets
functions.bootstrapPermissions. The value is a versioned (apiVersion: 1), provider-neutral contract with a full form (keys per tenant) and a compact form (a key index and one bitset per tenant), read intoBootstrap.permissions; anotherapiVersionor a damaged value givesnull.compactBootstrapPermissionsandexpandBootstrapPermissionscome frombetter-supabase/server, and the types frombetter-supabase/contract. At 150 tenants and 300 keys the compact form is 21,314 bytes against 737,192.permissions: falseon a bootstrap entry leaves them out.better-supabase upgraderewrites thesessionsmodule only for an app whose provider sets the template; no data migration is needed. -
A soft-deleted row of the drive, memory and messaging blocks carries
archived_atwhere it carrieddeleted_at. Runbetter-supabase codemod namingto write the migration that renames the three columns of an installed app, thenupgrade. ThedeletedAtoption and Row field keep their names.auth.users.deleted_at, the organizations block'sdeleted_atand the column an app table gets fromsoftDeletestay.Old New drive_nodes.deleted_at,memories.deleted_at,messages.deleted_atarchived_aton the same tables -
Every check constraint a block adds is named
bsb_<table>_<column>_check(bsb_<table>_checkwhen it reads more than one column), where Postgres used to choose the name. Runbetter-supabase codemod namingto write the migration that renames the checks of an installed app; no data moves.Old New checks of block tables, <table>_<column>_checkthe same name with bsb_in frontchecks a module named, <table>_<name>the same name with bsb_in front -
Every policy a block generates is named
bsb_<name>, shortened with a hash past 63 bytes. Runbetter-supabase codemod namingto write the migration that renames them in an installed app (alter policy ... rename to); no data moves.bsbPolicyName()inbetter-supabase/sqlreturns the generated name for a module's name.Old New policies of block tables, <table>_readetcthe same name with bsb_in front -
A column that references a user is named by its role,
<role>_id, instead of<role>_user_id. Runbetter-supabase codemod namingto write the migration that renames the columns of an installed app, thenupgrade; no data moves. SQL function parameters take the same names.scim_group_members.scim_user_idstays because it referencesscim_users.Old New owner_user_idowner_idcustomer_user_id,reviewer_user_id,host_user_idcustomer_id,reviewer_id,host_idholder_user_id,assignee_user_id,speaker_user_idholder_id,assignee_id,speaker_idhiring_manager_user_id,referred_user_id,actor_user_idhiring_manager_id,referred_id,actor_idfrom_user_id,to_user_idfrom_id,to_idsubject_user_id(appraisals),decided_user_id(quotes)appraisee_id,decider_idgiven_by_user_id(consents),paused_by_user_id(lifecycles)grantor_id,paused_by -
stream_kvisstream_entries,invoice_e_endpointsise_invoice_endpoints(table and function) andworkflow_step_libraryisworkflow_step_templates. Runbetter-supabase codemod namingto write the migration that renames the tables of an installed app with their constraints, indexes and policies, thenupgrade; no data moves. Theset_configkeys of generated triggers moved frombsb.<key>tobetter_supabase.<key>and last one transaction.Old New stream_kvstream_entriesinvoice_e_endpointse_invoice_endpointsworkflow_step_libraryworkflow_step_templatesbsb.recorded,bsb.lane_movebetter_supabase.recorded,better_supabase.lane_move -
Every block table names its tenant column
tenant_idwhere 63 usedorganization_id. Runbetter-supabase codemod namingto write the migration that renames the columns of an installed app, thenupgrade; no data moves. Apps that adopt their own tables keep their column names and maptenantincolumns.memberships.organization_id, the default tenant column of an app table and the JSON keys of the SQL API stay.Old New organization_idonaudit_events,outbox_events,api_keys,invitationsand the other block tablestenant_id -
Every timestamp column a block adds ends in
_at, with one explicit new name per column. Runbetter-supabase codemod namingto write the migration that renames the columns of an installed app; no data moves, and theupgradeafter it replaces the functions that read them.recurrence_rules.dtstartandmaintenance_plans.dtstartkeep the name RFC 5545 gives them.Old New locked_untillock_expires_atleased_until,lease_untillease_expires_atsnoozed_until,paused_until,claimed_untilsnooze_expires_at,pause_expires_at,claim_expires_atdispatch_until,publish_until,legal_hold_untildispatch_expires_at,publish_expires_at,legal_hold_expires_atscheduled_forscheduled_atwindow_start,bucket_start,original_startwindow_started_at,bucket_started_at,original_starts_atpurge_after,not_before,effective_frompurge_at,not_before_at,effective_atfailing_since,missing_sincefirst_failed_at,went_missing_atsubject_updated_at_at_importsubject_imported_updated_atvalid_from,valid_untilon passes and pricesstarts_at,expires_atvalid_untilon consentsexpires_at -
Generated triggers are named
bsb_*, unique constraints end in_keyand exclusion constraints in_excl. Runbetter-supabase codemod namingto write the migration that renames them in an installed app; no data moves.Old New triggers conversations_broadcast,inbox_conversation_events_broadcast,inbox_message_deliveries_broadcast,bookings_engagement,passes_credit_refund,calendar_attendees_auto_decline,calendar_events_auto_declinethe same names with a bsb_prefixindexes bsb_rate_limit_rules_scope_global,bsb_rate_limit_rules_scope_orgthe same names ending in _keyconstraints flag_overrides_unique,flag_revisions_uniqueflag_overrides_key,flag_revisions_keyconstraints <table>_no_overlap(bookings, time entries, shift assignments, leases, passes, calendar events)<table>_no_overlap_excl -
The
bulkblock isbulk-actions. Import frombetter-supabase/blocks/bulk-actions, name itblocks["bulk-actions"], and usedb.$blocks.bulkActions. Runbetter-supabase codemod namingto rewrite imports and the config key, thenupgrade; the migration renames the block's registry row and its permission keys in place, so roles and overrides keep their grants. The run keeps its names: thebulk_runstable,start_bulk,BulkRunand theBULK_*hints.Old New better-supabase/blocks/bulkbetter-supabase/blocks/bulk-actionsblocks.bulkblocks["bulk-actions"]createBulk,bulkBlock,bulkEventscreateBulkActions,bulkActionsBlock,bulkActionsEventsBulk,BulkOptions,BulkEventsBulkActions,BulkActionsOptions,BulkActionsEventsbulk.run,bulk.*bulk_actions.run,bulk_actions.* -
createBulkSelectionController(frombetter-supabase/blocks/bulk-actions) keeps the checked rows of a table and runs a bulk action on them, with background progress.createBoardController(frombetter-supabase/blocks/pipelines) moves cards between lanes at once, saves each move and puts the card back when the save fails. -
bsb.cached()andbsb.bootstrap()takestage: "prefetch" | "navigation", which awaitsprefetch()ornavigation()fromnext/cachebefore the entry's context resolves, andlife: "max", the profile{ stale: 300, revalidate: 2592000, expire: 31536000 }. Without the gates, or inside a"use cache"scope where they throw,stageis skipped and development logs it once. -
Search joins and watch lookups compare keys on their own type, and a watch update fires only when
keyorwatch.columnschanged. Doctor BS632 reports a pair whose live types differ.An unbounded
listthat PostgREST cuts atmaxRowsreturns atruncatederror after a probe finds another row.truncation: "warn"keeps the previous warning. SetmaxRowsto the project's[api] max_rows.usage_overviewreads every meter in one statement.usage.remaining()callsusage_remainingand does not load the meter catalog.The server schema loads each table module on first use and function metadata on the first
rpccall.gen.serverTables: "eager"imports every table up front.Statement-level audit triggers skip an import that audits one summary per entity.
finish_import_runtreats a run as completed with issues only when aconflictedcount is above zero.better-supabase/client/liteis an Auth and Realtime client. Install@supabase/auth-jsand@supabase/realtime-jsto use it. Cookie sessions stay onbetter-supabase/client. -
classifyPartysplits a person, keeps initials, and treats a legal suffix as a company.autois the default. Passpersonorcompanyto decide yourself. -
CLI contract 3 follows the Vercel CLI guidelines. Exit code 3 is gone: a missing input, a login and a confirmation exit 2. A failed
--jsonrun prints one error document line on stderr (status,reason,message,next,data,userActionRequired,retryable) and leaves stdout empty; a success or a report printscli-result-v2on stdout. Next steps print on stderr underNext steps:and carry anargvarray.--yes --effects-digest <digest>replaces--confirm <token>(consent_requiredis nowconfirmation_required, and the MCP tools takeeffectsDigest), and--non-interactiveis a global option.--help --jsonprintscli-commands-v2. A removed flag exits 2 withflag_renamedand its replacement, with no alias.Old New exit code 3 exit code 2, userActionRequired: true--confirm <token>--yes --effects-digest <digest>consent_required,error.tokenconfirmation_required,data.digesterror.code,error.detailon stdoutreason,messageon stderrcli-result-v1.json,cli-commands-v1.jsoncli-result-v2.json,cli-commands-v2.json -
Adds
better-supabase db squash, which replaces the migrations with one baseline of the declarative schema and carries over the module extensions and the data migrations--keepnames, and thetooling.env.mapconfig key, which adds variables under the names your app reads to whatdev envanddev runset. -
Five CLI flags are renamed to the ones contract 3 names, and the old ones exit 2 with
flag_renamedand the replacement. Update scripts and CI that pass them.Old New db seed --applydb seed --yesdoctor --fixdoctor --yesdev env --writedev env --outgen --emit <file>gen --metadata <doc> --only <file>gen --out-dirgen --metadata <doc> --out <dir> -
better-supabase/reactgetsuseOptimisticAction,useActionover React'suseOptimisticwithoptimisticandconfirmedvalues.useSessionWatchtakesonEndedfor an ended session, a ban or a sign-out, anduseBroadcasttakesonRejoinandrejoinOnLoadto refetch after a realtime reconnect. -
better-supabase codemodno longer reads the SQL files the blocks wrote (module, data and test files). It writes a rename migration only for names your own SQL uses, becauseupgraderewrites the block files. -
better-supabase codemod configremoves thecolumnsentries the render refuses: anullfor an optional column the view a block runs over lacks anyway, and atenantthat repeatssql.tenantColumn. Doctor BS379 reports those entries as errors and names the codemod. -
Config keys have one spelling each. Rename them in
better-supabase.config.ts(or runbetter-supabase codemod naming, which rewrites the same-parent keys); a config that keeps an old key is refused, with the new name in the message.Old New subjectsrecordTypesgen.recordTypesgen.recordsgen.outputgen.filedatabase.seed.output,database.seed.sample.output,database.realtime.policies.outputdatabase.seed.file,database.seed.sample.file,database.realtime.policies.filetooling.env.output,tooling.keys.output,tooling.doctor.output,api.specs.outputs[].outputtooling.env.file,tooling.keys.file,tooling.doctor.file,api.specs.outputs[].fileintegrations(flat),organization(flat)adapters,auth.tenantthe integrationsfield of a presetadapters -
Three core hint codes carry the noun they belong to, and the policy helper functions live in
better_supabase.better-supabase codemod namingrenames the hints in your code and writes a hand migration that moves the helper functions.Old New CHAIN_SIGNERAUDIT_CHAIN_SIGNERAPPEND_ONLYTABLE_APPEND_ONLYFISCAL_YEAR_CLOSEDPERIOD_CLOSEDbsb.uid()better_supabase.uid()bsb.owns(uuid)better_supabase.owns(uuid)bsb.is_member(uuid)better_supabase.is_member(uuid)bsb.can(uuid, text)better_supabase.can(uuid, text)The naming table gains the
hint,eventandsqlFunctionkinds, and doctor BS260 reports a source file that still compares against an old hint code. -
Breaking default:
count(),page({ withCount: true }), the keyset total and the server resource list count in theestimatedmode. The total is exact up to 1,000 rows and the planner's estimate above it, so a page of a large table no longer scans every matching row (an exact count over 200,000 rows took 12 ms, the capped form 1 ms). Passcount: "exact"orcount({ mode: "exact" })where an exact total matters.better-supabase upgraderewrites no module and no data migration is needed. Returning{ count, capped }is not part of this change. -
Counts say whether the planner answered.
page.cappedis true when an offset page'stotalis the planner's estimate,repository.counted()returns{ count, capped }, andformatPageTotal(page)prints12,300or~12,300(passcapped: (n) => ...for another wording).count()still returns a number.better-supabase upgraderewrites no module and no data migration is needed. -
The custom-fields block sets, changes and removes a value by itself.
setValuereplaces a value that exists instead of failing on the key of record and field, and an encrypted value is sealed once. NewupdateValue({ id, value })anddeleteValue(id)call the SQL functionsupdate_field_value(value_id, value)anddelete_field_value(value_id), which the normalized and inline layouts now have (the keyed layout had them). They replace the app SQL that updated or deletedfield_valuesrows. Runbetter-supabase upgradeand generate a migration withsupabase db schema declarative sync. -
better-supabase db partition auditmoves an audit log created beforeoptions.partitionedonto monthly partitions without stopping writes. It calls the generatedconvert_audit_log_to_partitionedprocedure, which copies in committed batches and swaps the tables under one short lock. Pass--batch-size,--drop-oldor--dry-run. -
better-supabase db verifyreads row level security, grants, policies and definersearch_pathfrom the database, reports the findings and exits 1 on an error.--write-testsalso writes the access matrix as one pgTAP file per persona. -
The declarative base layer release gives every name one spelling and makes the files better-supabase writes declarative. The renames ship without aliases. This is a minor release; below 1.0 a minor version may carry breaking changes. Follow the 0.57 to 0.58 guide; this entry lists what breaks, by area.
Run the codemods in this order, then
gen,upgradeand your SQL workflow's sync:better-supabase codemod owned-columns better-supabase codemod extra-columns better-supabase codemod config better-supabase codemod generators better-supabase codemod naming better-supabase codemod table-modules better-supabase gen better-supabase upgradeConfig. Keys have one spelling each. A config that keeps an old key is refused with the new name.
codemod namingrewrites the keys that stay under the same parent. Move the flatorganizationkey toauth.tenantby hand; the codemod reports it and leaves it.extraColumnsand its prefixed forms are removed from every block (codemod extra-columns), and acolumnsentry for a column the view lacks, or atenantthat repeatssql.tenantColumn, is an error (codemod config).Exports and types. The renames of
api/naming.jsonapply (codemod naming).better-supabase/configno longer exports the generators; import them frombetter-supabase/generators/<name>(codemod generators). Generators are plugins atapiVersion: 2. Every exported*Args,*Settingsand*Failuretype has a name from its noun.Blocks.
time-trackingistime-entriesandbulkisbulk-actions, with their imports, config keys, clients and permission keys. The tasks block's default entity istask. Engagements are activities. Therankblock keeps its name.Database. Block tables name their tenant column
tenant_id, user references<role>_id, soft-deleted rowsarchived_atand timestamps*_at. Generated policies, triggers and check constraints carry absb_prefix. Three tables are renamed, and the policy helper functions live inbetter_supabase.codemod namingwrites the rename migrations for an installed app; no data moves.Module files. The files
upgradewrites are declarative DDL, with shared helpers in one prelude file and unscoped triggers in one file. Row audit triggers are static statements. Migrations the CLI writes are named by stamp and content hash.powersync streamsdeclares thepowersyncpublication insupabase/schemaswhen that folder exists.Generated client code.
genwrites one module per table and one slice per block. The server's schema is ingenerated-schema.ts(codemod table-modules). Frameworks are registrations throughdefineFramework.CLI. CLI contract 3 follows the Vercel CLI guidelines: exit code 3 is gone, the result documents are
cli-result-v2andcli-commands-v2, and five flags are renamed withflag_renamedas the error.gen --watchisdev, anddb prune-workflowsisworkflows prune.Removed. The 0.46 and 0.47 rename shims, the module upgrades for tables 0.47 renamed (upgrades start at 0.53),
$apiResult, thetriggerSqloverload, the moduleversionoption and theopenapiconfig key.Deferred. The generated file layout, reads through a view named after a block instance, child PowerSync streams and the owned-column default flip are not in this release (ADR 0393). Cloud design URLs that were saved earlier carry the old
integrationsfield.Old New subjects,gen.recordTypesrecordTypes,gen.recordsgen.outputand the otheroutputfile keysgen.fileand the otherfilekeysintegrations,organization(flat)adapters,auth.tenantbetter-supabase/blocks/time-tracking,blocks["time-tracking"]better-supabase/blocks/time-entries,blocks["time-entries"]better-supabase/blocks/bulk,blocks.bulkbetter-supabase/blocks/bulk-actions,blocks["bulk-actions"]organization_idon block tablestenant_idowner_user_idand the other<role>_user_idcolumnsowner_idand the other<role>_idcolumnsdeleted_atondrive_nodes,memories,messagesarchived_atlocked_until,scheduled_for,purge_afterand the other timestampslock_expires_at,scheduled_at,purge_atand so onengagement_*tables,Engagement*types,ENGAGEMENT_*hintsactivity_*,Activity*,ACTIVITY_*stream_kv,invoice_e_endpoints,workflow_step_librarystream_entries,e_invoice_endpoints,workflow_step_templatesbsb.uid(),bsb.owns(),bsb.is_member(),bsb.can()the same functions in better_supabasework_item(default entity of tasks)taskdefineSupabase,getBetterSupabase(Svelte)createSupabase,betterSupabaseBSB_STACK,BSB_CLOUD_URLBETTER_SUPABASE_STACK,BETTER_SUPABASE_CLOUD_URLdb seed --apply,doctor --fix,dev env --writedb seed --yes,doctor --yes,dev env --outgen --emit,gen --out-dir,gen --watchgen --metadata <doc> --only,gen --metadata <doc> --out,dev--confirm <token>, exit code 3--yes --effects-digest <digest>, exit code 2better-supabase db prune-workflowsbetter-supabase workflows prune -
Module files are declarative DDL. They no longer write
drop policy if exists,drop function if existsordrop trigger if exists,if not existson tables and indexes, orif not existson the columns of tables the block owns, so a schema diff reads each file as the end state. Runbetter-supabase upgradeand commit the result. The migrations workflow still writes statements that can run again.renderPolicyno longer takes adropoption. -
db.$decode(table)decodes relations embedded in a raw row (select=*,tag(*)) at every depth, with a codec failure reported asinvalid_value.createFakeClientanswers.single()over no data like PostgREST:PGRST116with the row count indetails, also for.maybeSingle()over several rows. Doctor reports a hand-mergedsettingsJSON blob as BS620. -
better-supabase devreplacesgen --watch: it listens for file events on the config,supabase/schemasand the task inputs, printsReadyonce on stderr, and reruns only the tasks a change affects.gen --watchandgen --intervalexit 2 withflag_renamed.better-supabase cache purge [--dry-run]deletes the CLI cache. A warmupgradeon a large project drops from about 1.4 s to 0.4 s because the adoption scan is memoized innode_modules/.cache/better-supabase/memo, andupgradeno longer renders the modules twice to plan renames.upgrade --jsonreportsdata.cache.rendered, the module files a fresh render produced.Old New gen --watch --interval 500dev --interval 500 -
The CLI keeps what each SQL file declares in
node_modules/.cache/better-supabase/parse/files.json, sodoctor,upgradeandsyncparse only the files that changed since an earlier run.--no-cacheskips it andcache purgedeletes it. -
better-supabase doctorreadssupabase db advisorsoutput that prints one lint per line as well as a list or an object withlints, and falls back to splinter for any other shape. A saved CLI document is now part of the tests. No module or data changes. -
better-supabase doctorreads the bodies of your own triggers for the same-tenant check. BS340 no longer lists a foreign key column that an app trigger reads or writes, matching whatsameTenant.autoleaves to the app, and the new BS398 warns when that trigger never mentions the tenant column, so the generated check is off and nothing replaces it.better-supabase upgraderewrites no module and no data moves. -
Doctor adds BS375 (two policies that decide the same way) and BS376 and BS377 (objects a migration creates and no schema file declares, and the reverse, under pg-delta) and BS378 (the
extraColumnsoptions).upgrade --checkalso fails ontransaction=false, a top-levelinsert, an object two block files declare and duplicate policies; its result data reports them asproblems, notduplicated. -
Doctor has four rules for declarative schema files. BS371 reports an object two schema files both declare, and names the prelude when a module file still pastes one of its helpers. BS372 reports a
doblock in an app file that creates objects, BS373 reportsif not existson an app table or index, and BS374 reports an insert in a block module file.better-supabase upgrade --checkalso fails while a module file declares a function the prelude defines. -
Doctor BS107 counts a restrictive
with check (false)policy as the denial of insert for a tenant table. An insert policy has nousing, so the rule could not be satisfied for insert before. -
better-supabase doctoradds four checks. BS394 holds a function that overrides a block function against the module's current text: write-- @bsb-override-of <schema.fn> <hash>above your owncreate function, and doctor prints the new hash when the module changes (BS369 no longer reports a tagged function). BS395 flagsverify_jwt = falsefor an Edge Function that usesauth: 'user', exceptmcp. BS396 flags ten or more single-row inserts into one table in a seed file. BS397 flags aninsert,updateordeletein a schema file for a table a migration or block data file also writes.better-supabase upgraderewrites no module and no data moves. -
Doctor BS381 flags
createNativeClient,powersyncEngine,attachmentQueueRouteorqueryEnginewhen it names a block table that one of your views projects, and BS382 fails asubjects.<type>config entry that disagrees with the table's@bsb subjectcomment.better-supabase powersync streamsnow reads your schema files. A table you project through a view streams the view's columns (under the view's names) and itswhererows, the authorization provider's version column (authz_version,permissions_version) is left out of every stream, a bigintidsyncs as text, and themembership_rolesstream covers the roles of every member of the user's organizations instead of the user's own. -
better-supabase doctorchecks scale practices. BS386 flags a volatile or PL/pgSQL function called per row in a policy, BS387 a table with six or more row-levelbsb_*triggers, BS388 a search trigger on an import target without the import guard, BS389 an audit log nothing purges, BS390 a redundant index, BS391 aparam is null or col = any(param)filter in a function, and BS392 a searched table without a trigram or time index. BS227 also reportscount()without amode.better-supabase upgraderewrites no module and no data moves. -
Doctor checks the app's own schema files against four Supabase and Postgres practices. BS365 warns about an update policy with no select policy, BS366 reports a policy that decides on
user_metadata, BS367 warns about a view withoutsecurity_invoker, and BS368 reportstimestampandserialcolumns.Doctor BS383 warns about a storage insert policy without select and update policies, BS384 about a policy that calls
auth.uid(),auth.jwt()orauth.role()outside(select ...), and BS385 about a policy column no index starts with. On a database on your machine, doctor readssupabase db advisorswhen the Supabase CLI is 2.81.3 or later and falls back to splinter otherwise. Token verification requires the audienceauthenticatedunlessauth.audienceis set. -
Doctor reports two more patterns that a declarative sync cannot keep stable. BS378 flags a
beforeoraftertrigger aimed at a view, which never fires for the table under it. BS380 flags a check constraint that joins abetweento other conditions withandoror, because Postgres reads it back as another expression and the next diff proposes the constraint again. -
entryContext(bsb, entry)frombetter-supabase/serverbuilds the sameServerContextfrom a request, a resolution, an auth state or a cron call.cronHandler(bsb, { name, secret }, run)is a guardedGETandPOSTroute for a scheduler that runsrun(ctx, request)as the service role. -
better-supabase codes --jsonprints the stable codes functions raise and import warnings report. The catalog isbetter-supabase/schemas/error-codes.json. Doctor BS627 reports a raise that has no hint. -
options.onof the time-tracking block lists the record types an entry can be tracked on (TIME_SUBJECT_INVALIDfor another type), replacing an app trigger that did the same. The tasks block takeslockedas an optional column, so a table without a lock maps it tonull. Runbetter-supabase upgradeand generate a migration withsupabase db schema declarative sync. -
A table comment
@bsb filled-by-trigger created_by owner_idmakes those columns optional on insert in the generated types, the same astables.<t>.insertOptionalin the config. A column the config lists too is kept once.better-supabase upgraderewrites no module and no data migration is needed. -
Doctor BS260 no longer reports
workItemIdorworkItemIdsfor an app that renamed the entity throughblocks.<name>.entities(ornames), such aswork_item: the verb arguments follow the entity name there, so they are not the old ones.codemod namingstill renames them in an app that keeps the default names. -
The built CLI bundles
valibotandjsonpath-rfc9535, which are also optional peers and were imported bare, so the CLI failed in an app that installs neither. Doctor BS330 readssql.tenantColumnoncecodemod configremoved the explicit entries, BS346 saysrecordTypes, and two new warnings report a block's unique index that one of your unique indexes repeats or makes redundant (BS623) and a blockupdated_attrigger next to yourtrack_updated_atcall (BS624).gennames the server schemagenerated-schema.tswhengen.fileisschema.ts. The renamed-key messages say 0.58. -
codemod namingno longer renames the column thatsql.tenantColumn(or acolumns.<table>.tenantentry) names, and leaves every column rename out, with a note, when the config did not load; before, an app withsql.tenantColumn: "organization_id"gotorganization_idrenamed totenant_idon 74 block tables, and the schema diff dropped the column. It also renamesjob_schedules.locked_until, the tasks verb arguments (workItemIdtotaskId), the former permission keys underblocks.<name>.permissions(view,viewAll,viewSensitive,edit,admin),blocks["time-tracking"]anddb.$blocks.timeTracking, and keeps the keys of a renamed config object sorted.codemod owned-columns,extra-columnsandconfigstop withconfig_invalidwhen the config does not load, instead of printing "Nothing to change".codemod server-importssplitsexport { ... } from "better-supabase/server"too, andcodemod generatorsflagsapiVersion: 1only inside a generator. Runbetter-supabase codemod namingfirst. -
Fixes found while upgrading a production app to 0.58.
same_tenant()refuses a reference to a row whose tenant is null unless the entry setsshared: true, and a deferrable foreign key gets a constraint trigger that runs at commit. The audit module's dynamic insert and the api-keys, flags, tenant switch, usage and knowledge results use the configured tenant column.clone_taskcopies taggings only when the tags block has the table. An@bsb fieldstag in a multi-line table comment is read, so the feature it turns on stays on.upgraderenames the registry row oftime-trackingandbulkinstead of adding a second one.schemaTextsreads the migrations before the schema files, so an old migration no longer overwrites the final state of the audit tables. The config refuses the former permission keys andinvoices.options.uniqueNumberwith the new name or a way out, and the 0.57 to 0.58 guide has a query that finds duplicate invoice numbers before the migration adds the key. -
codemod namingkeeps working for apps that own a block table. It writes ablocks.<name>.columnsentry that keeps the old name of a column your own table still has (drive_nodes.deleted_at, the actor columns of scorecards and status history), so the feature that reads it stays on, and it renames the block column names in your schema files and seeds, only in statements that name abetter_supabasetable and never in migrations. Blocks now leave out a unique index over the same columns as a unique key of yours, the invoices number key when your key is a subset of it, and their ownupdated_attrigger on a table your files track withtrack_updated_at(), so doctor BS623 and BS624 report only what a block can't decide. -
better-supabase initdetects SvelteKit, TanStack Start and React Router with their own framework bindings. It setsgen.hookstosveltekit,tanstack-startorreact-router, writes the server hook or middleware file the docs show unless it exists, and prints the server adapter to import.gen.hooksaccepts the three names. Upgrade: nothing to change; a project that setshooks: "svelte"or"react"keeps it. -
Frameworks are registrations.
defineFrameworkfrom the newbetter-supabase/pluginsentry builds a binding (name,tier,detect,integrations,hooksSubpathorhooksModule,hooksDirective), andframeworks: [binding]ingenregisters it.gen.hookstakes any registered name, the built-inreact,svelte,vueandsolidbindings use the same contract, andinitwritesgen.hooksfor a detected framework that no adapter selects.ResolvedConfiggainsframeworks, andgen.hooksnaming a framework nothing registers is an error. -
The generated hooks for Vue, Solid and Svelte read through the table module (
defineListHookanddefineOneHooktake it as a third argument), as the React hooks do, so a client onclientSchemaloads one table per page.hooks.tsexportsAppDb, an interface over the app'sdb. Doctor BS621 warns when a"use client"file importsgenerated-schema,blocks.generatedorblocks.config. -
initwrites the files a registered framework binding declares intemplatesand prints itsserverSubpathadapter.templatesreceiveserverImport, andbetter-supabase/pluginsexportsframeworkFilesandserverImportOf. -
gen.functions.<name>.returnstypes the result of a function that returnsjsonorjsonb:{ schema: "./file.ts#name" }takes a Standard Schema export and validates the result at runtime,{ import: "./file.ts#Type" }imports a type, and{ type: "..." }writes one. It does the same as the@bsb returnscomment tag and wins over it. -
gen.constants: truewritesenums.tsandcolumns.tsnext to the generated module.enums.tsholds every enum and CHECK value list as a constant array and a union type, andcolumns.tsmaps each column's row name to its database name for every table. Neither imports anything, so a browser form or a script uses them without the runtime package. -
gentypes a jsonb column from the schema value thatstandardSchema({ json })names for it, so you no longer repeat the type ingen.json. An entry ingen.jsonstill wins. -
better-supabase gen --offlinenever connects: it reads--snapshot <file>orsource.snapshotand fails with a usage error when neither exists, sogen --check --offlineruns in CI without a database. It refuses--db-url-stdinand--project-ref.better-supabase upgraderewrites no module and no data migration is needed. -
A column your own schema file adds with
generated always asorgenerated by default as identityis no longer a field of the block's table. A block's functions inserted it with the other columns and failed at run time, because Postgres refuses a value for a generated column. -
better-supabase genwritesnullableandhasDefaultintogenerated.meta.jsonly for the columns where they are true, and leaves the@bsbtag block out of a table or column description.ColumnMeta.nullableandColumnMeta.hasDefaultare optional in the type, and an absent value meansfalse. The metadata of a page's bundle shrinks and the OpenAPI documents stop showing the tags as text. Runbetter-supabase gento rewrite the file. -
Generators are plugins at
apiVersion: 2. A generator declaresname,version,options,pure,workerSafeandprovides, andgeneratereceives plain data:configis a view (output,databaseTypesOutput,casing,json) andimports.runtimereplacesruntimeImport.provides: ["validators"]replaces thevalidatorsflag on a file, and two generators that provide it are an error (the zod, valibot and standard-schema generators takevalidators: false).gencaches apuregenerator's files on its name, version, options and input. The newbetter-supabase/generatorsentry exportsdefineGenerator,relativeImportand the helpers the built-in generators use.testGeneratoris nowtestGeneratorPlugin, and it also checksstructuredClonesafety and the cache round trip. A generator atapiVersion: 1fails with a message that names the change. -
Each first-party generator has a subpath:
better-supabase/generators/zod,/valibot,/json-schema,/standard-schema,/factoriesand/nuqs.zod(4.x) andvalibot(1.x) are now optional peers with a tested range, likenuqs, andgenprints a notice when a configured generator's library is installed outside it.better-supabase/configstill exports the generators. -
genruns generators that declareworkerSafeand amoduleon worker threads once a schema has 1500 tables, and writes the same files as a single thread. The built-in generators declare their module;Generatorgainsmodule({ specifier, export }) andtestGeneratorPluginchecks that the generator rebuilds from it. -
better-supabase/configno longer exportszod,valibot,jsonSchema,toJsonSchema,standardSchema,factoriesandnuqsor their option types. Import each frombetter-supabase/generators/<name>. Runbetter-supabase codemod generatorsto rewrite the imports; it also lists the lines of any generator that still uses theapiVersion: 1shape. -
An imported accounting entry opens the fiscal year and its twelve periods when they are missing. Earlier open years close when the item asks, and an unbalanced opening set is refused.
-
An invoice import can set
settlementtorowand write a historical paid, partially paid or open state without a payment or a ledger entry.suppliedOnis stored and fills the issue date whenissuedOnis empty. A line with a product is markedproduct. A payment term code and a single matching tax rate are resolved when those blocks are installed. -
New sessions option
hookrendersbetter_supabase.hook_plan(event)for the app's access token hook. It returnsslimfor a token with aclient_id(the MCP OAuth server's tokens, withoauth: 'slim'),reusefor a refresh whoseauthz_veris still the user's current version, andfullotherwise, so a fast refresh makes 0 membership reads instead of 1 and an OAuth client token reads nothing.refresh: 'reuse'needsauthzVersionsor a provider withversions.better-supabase upgraderewrites the sessions module only for an app that setshook, anddb diffthen adds the function; no data migration is needed. Call the plan first in your hook and return the event forslimandreuse. -
invoice_allocationlinks an existing receipt to an invoice and moves the paid total without posting a ledger entry.allocateExistingis the same call from the invoices client. Row settlement still writes the paid state with no allocation. -
An import target can name
batch: "schema.function", a function(run uuid, items jsonb) returns jsonbthat writes the batch's items in set-based statements and answers one entry per item. When it raises, every item runs throughwriteon its own, so one bad row costs only its own error, and counts, record map rows and errors match the row path (a pgTAP parity test holds it). On the local fixture it is no faster thanwritefor customers, because the triggers dominate; it helps targets whose own function does the per-row work.better-supabase upgraderewrites theimportsmodule and the next schema migration replacesimport_apply_batch. No data migration is needed, and apps withoutbatchkeep the same generated SQL. -
Two batches of one import run no longer wait on each other.
import_upsert_batchreads the run withoutfor update, and only the counts update at its end locks the run row.imports.runalso adapts its batch size: a batch overtargetBatchMs(default 30,000) halves the next one,maxBatchSizelets fast batches double it, a batch that hits the statement timeout is split in two and sent again, and the result carriessuggestedBatchSize.better-supabase upgraderewrites theimportsmodule and no data migration is needed. -
enqueue_import_chunksputs its jobs on the queueimports. The name was passed with its own quotes, so the jobs went to a queue that no worker reads.better-supabase upgraderewrites theimportsmodule. No schema data migration is needed, but a chunk job queued under the quoted name before the upgrade stays there, so callenqueue_import_chunksagain for a run that still has unprocessed chunks. -
Large imports run in chunks from the library. The imports module has an
import_chunkstable and the service-role functionsstore_import_chunk,claim_import_chunk,complete_import_chunk,process_import_chunkandimport_chunk_progress;imports.chunks.{store, process, progress},importChunkSchema,importChunkHandlerandrunImportWorker({ imports, queue })drive them from theimportsqueue.processwrites a chunk once even when its job is retried, a failure leaves the chunk pending, and a claim older than five minutes is taken over.better-supabase upgraderewrites theimportsanddata-lifecyclemodules and the next schema migration creates the table and functions. No data migration is needed. An app's own chunk table and runner functions become removable once it calls these. -
An import batch names the keys of its conflicted items (
conflictKeys, the first 100), and a worker can mark a stored chunk failed withimports.chunks.fail, so a queue stops retrying it.chunks.progresscountsfailedchunks andchunks.processanswers{ status: "failed", message }for one. Runbetter-supabase upgradeand generate the migration: it adds thefail_import_chunkfunction and thefailedchunk status.The subject cascade deletes of
approvalsandrelationsread an index. Approval requests get a(subject_type, subject_id)index, relations get a tenant-led source index, and the relations cascade filters on the subject row's tenant. The drive retention sweep asks the retention and hold policies once per tenant and statement. -
A credit note import reads
resolved.originalas well asoriginalIdand the original number. A negative invoice total becomes a credit note when that original resolves. Without an original it stays an invoice and returnsIMPORT_CREDIT_WITHOUT_ORIGINAL. A row settlement with no original posts nothing and returns the same warning. -
Doctor BS629 reports a migration that drops a
when '<entity>' thenarm the schema file still dispatches, and animport_apply_batchthat omits an entity fromblocks.imports.options.targets.import_entities()returns the entities the imports module dispatches, so an override can call the list instead of copying it.better-supabase upgraderewrites the imports module. The next schema migration addsimport_entities. -
An imported invoice, credit note, quote or order stays as imported unless
data.updateisapply. Apply writes the header and, when the line count is unchanged, the line title and tax. A different line count replaces the lines. A void or paid document keeps its postings unlessdata.repostis true. -
A dry run keeps the counts and the first changed fields, and
list_import_diffreads them. The subject rows are not written. -
import_ensure_reffinds a reference row by kind and key, ignoring case, and creates it fromdefaultswhen it is missing. A created row returns the warningIMPORT_REF_CREATED.better-supabase upgraderewrites the imports module. The next schema migration addsimport_refsand the function. No data migration is needed. -
import_integrityreports duplicate import keys, unbalanced ledger entries, negative invoices that are not credit notes, issued documents without a number, and archived parties without a date.integrityReportreads that shape. -
start_import_runstoresoptions.plan(expected rows per entity) and takes a 30 second lease.heartbeat_import_runextends the lease.finish_import_runsetsoutcometocompleted,completed_with_issuesorincompletewhen an entity is below its plan.get_import_runreturns the plan, outcome and lease.better-supabase upgraderewrites the imports module. The next schema migration adds the columns andheartbeat_import_run. No data migration is needed. -
list_import_issuesandlist_import_difftake a fifth argument,after, and returnnext_cursor. Pass thenext_cursorof one page asafterto read the next page by keyset.row_offsetstill works whileafteris null. The issuestotalis null on a keyset page, and is counted with a bound of 10,000 on an offset page.Migration guide:
Before After list_import_issues(run, entity, 50, 100)Still works. Add after => page.next_cursorto page by keyset.rpc("list_import_issues", { ... })Pass afteras a fifth named argument when you want a cursor.Reading totalon every pageRead it on the first page, it is null on a keyset page. Run
supabase db diffto drop the old four-argument functions and to replace theimport_run_issues_run_idxindex. -
An import run records the version of its mapping code (
runs.start({ mapperVersion }),ImportRun.mapperVersion).reapply_import_records(tenant, source, mapper_version, entity?)makes the next run rewrite the records an older version wrote, andexport_import_hashes(tenant, source, entity?)lists the record map's hashes.better-supabase upgraderewrites theimportsmodule and the next schema migration adds one column and two functions. No data migration is needed. -
An import target can name
naturalKey, a function(tenant, item jsonb) returns text. When no import record exists and the function returns a subject, the write updates that row instead of inserting another. -
An imported quote or invoice can ask for the next free number when its own is taken: put
onTaken: "next_free"in the item'sdataand the import issues the next number and reportsIMPORT_NUMBER_REASSIGNED. Without it a taken number still fails the item.better-supabase upgraderewrites the quotes and invoices modules and the next schema migration replaces two functions. No data migration is needed. -
An import target can name
ownedHash, a reader of the columns the importer writes. A newer subject stamp is a conflict only when that hash changed. When only the stamp moved, the library realigns it and applies the row.rebase_import_recordscopies the current stamp and hash onto the stored rows for a tenant, source and optional entities and keys.better-supabase upgraderewrites the imports module. The next schema migration addsimport_records.owned_hashandrebase_import_records. -
An import target can declare
refs, a map from a field onitem.refsto the entity that field points at. The batch resolves every such key in one query and passes the subject ids to the write asresolved. A key with no import record adds the warningIMPORT_REF_MISSING. -
runImportreadsaccessTokenbefore every batch and retries once when the request reports an auth failure. A dropped batch returnsresumeFrom. Passing that asresumecontinues the same run from that chunk, so the earlier chunks are not sent again. -
pgTAP helpers
tests.import_run_fixture,tests.age_import_run,tests.bulk_touch_subjectsandtests.assert_override_dispatches_allset up a run in a chosen state, move its lease into the past, age stored import stamps and check that an override still dispatches every import entity. -
Import conflicts, errors and warnings are stored on
import_run_issues. A later run that applies the same key setsresolved_at.list_import_runsincludes open issue counts.list_import_issuespages one run, with the total capped at 10,000.resolve_import_conflicttakeskeep, which adopts the database stamp as the baseline, oroverwrite, which clears the stamp and owned hash so the next batch can write the source.better-supabase upgraderewrites the imports module. The next schema migration addsimport_run_issuesand the two functions. -
An import item can carry
sourceUpdatedAt. Apply skips a row whose source time is not newer than the stored one, anddiffItemsreports created, changed and unchanged rows the same way. -
defineImportSourceandrunImportSourceread a multi-entity source, preview it, and write each dependency wave. A dry run stops after the preview. -
import_sourcesis the registry an integration catalog reads.list_import_source_runslists every run of the tenant, whether it was started from the CLI, an API or the UI. -
An import can change a status the state machine would refuse. The transition check runs only outside an import.
-
An import target can set
replaces: trueto take the dispatch arm of a built-in entity, andbeforeorafterto adjust the item or the result. The batch loop stays the library's, so a later change to the hash or the record map still runs with the override installed. -
testImportTargetbuilds the pgTAP checks for an import target: insert, unchanged, update, conflict, dry run, no events, and updatedAt. The testing skill documents it. -
The default titles of imported quotes, invoices, opening balances and checkout invoices come from the new options
quotes.titleTemplate,invoices.titleTemplate,invoices.openingTitleTemplateandorders.titleTemplate, with{number}for the number. The defaults are the old English texts, so nothing changes until you set one, such asOfferte {number}.better-supabase upgraderewrites the quotes, invoices and orders modules and the next schema migration replaces their functions. No data migration is needed. -
Import targets can name
dependsOn.importWavesorders them into waves and rejects a cycle. A batch whose earlier wave still has open chunks is refused unless the plan setsunordered. -
better_supabase.importing()returns true while the transaction runs in an import session, so an app trigger or function can skip a side effect during an import withif not better_supabase.importing() then ... end if;. A user session always gets false.better-supabase upgraderewrites the prelude and the next schema migration creates one function. No data migration is needed. -
knowledge_searchsetsplan_cache_mode = force_custom_plan, so the planner folds a nullcollectionsargument and uses the collection index.mark_notifications_readreads itsidsargument through a union of the given ids and the user's unread rows instead ofids is null or id = any(ids), andlist_notificationsandnotification_pagefiltertypeswithtype = any(coalesce(types, array[type])).better-supabase upgraderewrites the knowledge and notifications modules; add the generatedcreate or replace functionmigration. No data moves. -
Config inference covers two more lines. The
notificationsblock is installed whengen.powersync.instancesorgen.clientBlocksnames it, andstandardSchema({ settings: "./src/settings.ts#settings" })gives thesettingsblock itsdefineSettings()schemas, soblocks.settings.options.schemascan go. An option you set still wins. -
A
columns.<table>.<column>: nullentry for an optional column the view you map a block over lacks anyway is now an error that names the entry, since the block already leaves that column out. Acolumns.<table>.tenantentry that repeatssql.tenantColumnis an error too.add --adoptno longer proposes the null entries for a view. Remove the entries the message names; anullentry for a column your view has, or for a table you own, still works. -
The inventory client gets
releaseAllocationandtransferAllocation, and the SQL functiontransfer_allocationrecords the newallocation.transferredevent, with the new document intoDocumentTypeandtoDocumentId. Runbetter-supabase upgradeand generate a migration withsupabase db schema declarative sync. -
The inventory block gets the SQL functions
release_allocation(allocation), which releases one open allocation, andtransfer_allocation(allocation, document_type, document_id, line_id), which moves an open allocation to another document. They replace the app SQL that updatedstock_allocationsrows. Runbetter-supabase upgradeand generate a migration withsupabase db schema declarative sync. -
inventory_levelsreads stock for the variants you pass, andinventory_status_countsandlist_inventory_movementsread the status totals and the stock ledger. A movement records its bin and lot. Open purchase orders still keepincomingon the stock level. -
inventory.levelsreads the stock levels of a list of variants in one call, andinventory.movementspages the ledger movements by variant, location, bin, lot or document.releaseAllocationandtransferAllocationtake an optionalquantity: a release shrinks the allocation and a transfer splits it, moving held stock first into a new allocation on the new document. The SQL functionsrelease_allocationandtransfer_allocationtake the same optionalquantity. -
The inventory block gets
stock_levels.reorder_quantitywithsetReorderQuantity, the SQL functionpick_serials(variant, location, quantity, lot)withpickSerials, which chooses the oldest serial numbers in stock, and a unique(id, tenant_id)on locations, reservations, transfers and purchase orders so your tables can reference them with a composite key. They replace app SQL that added the column, picked serials and added the constraint. Runbetter-supabase upgradeand generate a migration withsupabase db schema declarative sync. -
When tenant and platform invitations share one table, the table now gets one select policy that reads both. The declarative output dropped the platform clause, so platform invitations stayed unreadable.
-
The JWKS cache of a Supabase Auth key set (
/auth/v1/.well-known/jwks.json) is capped at 600 seconds, whatevercacheSecondssays, andpurgeKeys(url?)frombetter-supabase/serverforgets a key set (or every set and imported secret) after you revoke a signing key. An unknownkidstill refetches once per 30 second cooldown.upgraderewrites no module and no data migration is needed. -
The list functions of the risks, meetings, inspections and warranty blocks page by keyset. Pass
after(the previousnextCursor) with{ paged: true }to get{ items, hasMore, nextCursor }, and{ total: true }for a total capped attotalCap(default 10,000).offsetstays as an explicit option for callers that show page numbers, and a plain call still returns the array.risks.page()is the typed client, and each table gets a list index that ends in the id. Runbetter-supabase upgradeanddb diffto write the new indexes.The
access,listandidempotencytable tags render policies, a keyset list function with its indexes, and a unique index for retried writes:better-supabase table <name> enable <tag>reads the tag's arguments from the table comment. The authorization provider gains an optionalfunctions.canIntemplate for the policies; without it the tag callsbetter_supabase.tenant_ids_with, so existing providers keep working andapiVersionstays 1. -
Client sessions can omit JWT claims (
toSession(auth, { claims: false })).PermissionsProvider,cananduseCanread the compact bootstrap payload, and the roles and catalog models gainbetter_supabase.bootstrap_permissions(). Membership claims acceptclaimFormat: "summary".The verified-token memo is shared on
globalThisand keyed by the raw token. A stale JWKS is served while it refreshes. Role-default and platform-role changes bump authorization versions in one statement, andhook_planreturnsfullwhen the active tenant changed. The browser client refreshes onvisibilitychangeinside the leeway.Cursor pages count
estimatedunlesscountsays otherwise.defineInfiniteListHookpages withpage()and its cursor. Block list methods take an optionallimitand return only that many rows. Facet counts can use a capped sample, andcountFacetswithfacetCacheKeykeeps that sample out of later pages.OfflineBoundaryandnativePermissionscover React Native. A PowerSync reconnect refreshes server-backed reads only. -
client.queries.<table>now works for a table that alazyTablesclient registers after it was built. Before,queries.customerswasundefinedfor a table registered later, soqueries.customers.list(...)threwCannot read properties of undefined (reading 'list'). -
A write whose only
mutationlistener is the cache adapter no longer copies the returned rows:MutationNotice.rowsis copied on the first read. -
The browser client's
dbis smaller:createClientfrombetter-supabase/clientno longer carries$many,$search,$stats,$decodeor$decodeReadSet, soreactplusqueryships 35.4 KB gzip instead of 43.1 KB.client.dbis typed asCoreDb, so a call to a removed method fails at type-check time. The server, every adapter,createNativeClientandbetter-supabase/testinginstall the fulldband are unchanged.A filter tree (
FilterQuery) passed towhereneedsenableFilterTrees()frombetter-supabase/listin a bundle that builds no server. The server installs it.genwrites the composed block reads (readsand their argument and result types) toblocks.reads.ts, which imports no block, andblocks.generated.tsre-exports it. Define read sets over the app without blocks and importreadsfromblocks.reads.ts, so a route that runs a read set bundles only its own block set.Old New client.db.$many(...)in a"use client"fileMove the read to a server function, or call $runonce per specclient.db.$search,$stats,$decodein the browserCall them on the server's dbwhere: filterTreein a bundle without a serverCall enableFilterTrees()frombetter-supabase/listonceimport { reads } from "./blocks.generated.ts"in a read setimport { reads } from "./blocks.reads.ts"(the old import still works)createNativeClientis now its own function with the fulldbtype.provideConnectionRuntimemoved tocore/define-runtime-full, andprovideLeanConnectionRuntimeis the browser's. -
Ledger entries store the transaction's effective time and are indexed by tenant and that time.
get_manyreads the entries whose ids you pass. -
The new
better-supabase/list/exportsubpath exportsexportListCsv, which streams a cursor list as a CSV download page by page, andpageFromIds, which builds a cursor page from a page of ids and a function that loads rows by id. Text cells that a spreadsheet would run as a formula get a leading'. See the list page in the docs. -
defineListQuerytakes relation facets, a free multi-column sort and date buckets.- A facet can be
{ relation: "notes", column: "kind" }and filters on a related table (somefor a to-many relation). It has no counts, so itsfacetCountsentry is empty. freeSortfrombetter-supabase/list/orderlets the caller sendorder=status:desc,name(up to three columns).ListQuery.orderholds the terms, andlist.parsers.orderis the URL parser.- The
@bsb buckets column=<column> filter=<columns>tag renders<table>_date_buckets, andlistDateBucketsfrombetter-supabase/list/bucketscalls it and narrows by the facet values of a list query.
Existing lists keep working: the new
ListQuery.orderfield and the newFacetInfo.relationfield are optional. The./listentry grew by 1.3 KB gzip. Runbetter-supabase table <name> enable bucketsanddb diffto add the function to a table. - A facet can be
-
Maintenance installs without the dispatch block. Work orders are opened only when dispatch is installed.
-
The authorization provider's
functions.managedUserstemplate takes{tenant}, so a provider that keeps a manager chain per tenant can writeauthz.managed_user_ids({tenant})and a manager in one organization never reaches reports in another.{tenant}is optional: a template without placeholders still passestestAuthorizationProvider, andapiVersionstays 1. No module readsmanagedUsersyet, so nothing changes in the generated SQL and no migration is needed. -
MCP
tools/listdecides every tool in oneevaluationscall when the authorizer has it, instead of one call per distinct permission. A list of 300 tools with 300 permissions makes 1 call instead of 300.outcomesOfManyinbetter-supabase/coreis the helper behind it. An authorizer withoutevaluationsis called once per tool as before, so nothing changes for it.upgraderewrites no module and no data migration is needed. -
Every purge asks the retention and legal-hold tables once per tenant and statement instead of once per row, through the new
retention_for_memoandis_held_memo.purge_outboxon 100,000 expired events takes 540 ms instead of 2,343 ms. A hold or policy changed between two statements still applies. Runbetter-supabase upgradeand generate the migration. -
Importing a meter reading that is below the previous reading of the same asset and unit stores the row with reason
importand returns the warningIMPORT_SERIES_DECREASE. The guard still rejects a lower reading that has no reason.tests.expect_import_warningchecks a batch result for a warning code.better-supabase upgraderewrites the assets module. The next schema migration addsasset_meter_readingsand its functions. No data migration is needed. -
Every migration the CLI writes is named
<stamp>_better_supabase_<name>_<hash>.sql. The stamp is later than every migration in the folder, soupgradenever shares a version with another tool, and the hash of the statements lets a repeated run write nothing. Migrations from earlier releases are still found by their suffix. -
genwrites one module per table and one slice module for the block config by default. The server's schema moves togenerated-schema.ts, soimport { schema } from "./generated"becomesimport { schema } from "./generated-schema";gen.tableModules: falseandgen.blockModules: falsekeep the single module.better-supabase codemod table-modulesrewrites the import and, in a"use client"file, readsbsb.db.customersasbsb.table(customersTable).initwrites the new import, andgen --metadataand the content mapper keep one module. -
The tasks block's default entity noun is
task, notwork_item: its functions take ataskargument, its events carrytaskIdand its subject paths start withtasks/. An app that names the entitywork_iteminblocks.tasks.nameskeeps its tables and functions; its event types follow the entity (work_item.created). The built-in goal metric istasks.completed, so runupgradeand apply the migration that updates stored goals.TABLE_RENAMESandspec.formerlyare gone: permission keys such astasks.readkeep their names when you rename the entity.Old New work_item(default)taskworkItemId(default)taskIdbsb_work_item_guardbsb_task_guardwork_items.completedtasks.completed -
better-supabase/next/auth-gateexportsAuthGate, a Server Component for the app layout that renders a<Suspense>around onebsb.user()promise, anduseUser()for Client Components.bsb.user()returns{ id, email, name, organizationId }ornull, never the token or the session, and setscacheLife({ stale: 300 })likebsb.cached().AuthGatetakes the loader asuser, redirects or refuses a signed-out visitor, and keys the subtree on the user id. -
The Next.js auth guide maps the Next.js authentication guide (
verifySession(), the data access layer, DTOs, optimistic checks, actions and routes) ontobsb.claims(),bsb.cached(),bsb.user(),bsb.proxy,bsb.require(),bsb.action()andbsb.route(), and says whatcreateNextalready taints. Thebetter-supabase-authskill says the same in two sentences, and therecord-pagerecipe loads the task form on first use. -
initfor Next.js writes the feature-slicedapp/,features/andcomponents/layout thatcheck:app-architectureholds the example to (anAuthGatelayout, a synchronous page that passesparams.then()to a feature,*-queries.ts,*-actions.tsand*-cache.tsfiles, async components with skeletons), plusapp/manifest.ts,public/sw.js,public/offline.htmland the Web Push keys in.env.example. The proxy matcher skipshtmlandwebmanifest. Existing files are kept. -
useBlockQueryanduseBlockMutationfrombetter-supabase/next/client/offlinepause whileuseOffline()is true: a read keeps its last data and reportsoffline: trueinstead of an error and runs once on reconnect, and a write queues once and runs on reconnect. The block controllers gainsetOffline(offline), anofflineoption and an optionalofflinestate field. -
better-supabase/next/proxyexportscreateProxy(), the Next.js proxy without the Server Component side ofcreateNext, and the proxy helpersmutableResponse,overrideRequestHeaders,syncMiddlewareSetCookieandserverTimingValue.src/proxy.tsimports it, so the proxy bundle carries no sign-in flows, record bindings or REST resources.bsb.proxy()is unchanged. -
createNexttaints the access token and the refresh token (experimental_taintUniqueValue) and the auth state, the server context and thebsb.admin()context (experimental_taintObjectReference), so React refuses to serialize them to a Client Component. It does nothing withoutexperimental.taint: trueor on a React build without the API.createNextConfig()turns the flag on. -
better-supabase/normalizerepairs imported text and shapes names, phones, postal codes, streets, IBANs, BICs and national ids. Locale rules are data, and the named repair packs areutf8-as-latin1,windows-1252,cp437andcp850.better_supabase.validate_ibanandbetter_supabase.normalize_phoneare the SQL forms.better-supabase upgraderewrites the prelude, and the next schema migration adds the two functions. No data migration is needed. -
The notifications block deletes a subject's notifications and subscriptions when the subject row is deleted, for every app table in
config.subjects, without ablocks.notifications.onentry. Setonto choose the types yourself. -
A numbering entity needs less config:
columndefaults tonumberwhentableis set, and an entity that names onlycolumnnumbers the table of the subject with the same name. The tenant column already comes from the subject. Acolumnwithout a table or a matching subject fails with an error that names both fixes. -
observedFetchfrombetter-supabase/serverwraps afetchso each request reports its method, URL (without the query), status and duration toonCall. Pass it ascreateServer({ fetch })to count or trace the server's calls to Supabase. The observer can't change or fail a request. -
The generated data hooks and
RecordProviderpause while the app is offline: reads keep their last data and showofflineinstead of an error, and writes wait for the connection. Wrap the app inOfflineBoundaryfrombetter-supabase/next/offlineto feed themuseOffline().createDataList,createDataOneandcreateRecordControllertake anofflineoption and exposesetOffline.powersync streamskeeps only the files of an app subject's rows when a view keeps onesubject_type, andgen.powersync.childrenstreams an app table with its parent subject, such asjob_partiesunderjobs. -
list_rfqs,list_samples,list_till_sessionsandlist_calibrationspage through the keyset list template of ADR 0637, with a list index that ends in the id.rfqs.rfqPage,lims.samplePage,tills.sessionPageandmaintenance.calibrationPagereturn{ items, hasMore, nextCursor }, andtotalwhen asked. Doctor BS633 reports an app row trigger whose function never callsbetter_supabase.importing().Migration guide for the moved lists:
Before After listSamples({ offset: 100 })Still works. Keep it where you show page numbers. listSamples({ offset, after })Refused with an invalid error. Pass one of them. Deep paging with offsetsamplePage({ after: page.nextCursor }), which reads from the index at any depth.Rows with equal performed_atoropened_atCome back in id order, the same order as before. The same applies to
listRfqswithrfqPage,listSessionswithsessionPageandlistCalibrationswithcalibrationPage. Runsupabase db diffto pick up the new list indexes. The remaining offset lists keep their shape. -
The renames of
api/naming.jsonship without aliases. Runbetter-supabase codemod namingto apply them, andbetter-supabase doctor(BS260) to find what is left.Old New buildJsonSchema,buildApiModeltoJsonSchema,defineApiModelcreateRuleSink,workItemRecurrenceSinkautomationSink,taskRecurrenceSinkSessionEntryConfig,GuardEntryConfig,AgentPassthroughSettingsSessionEntryOptions,GuardEntryOptions,AgentPassthroughOptionsChainProofFailure,ParseScaledFailure,RefreshFailure,StorageFailure,SvelteKitFailure,TelemetryFailure,XhrFailurethe same names ending in ErrorBSB_STACK,BSB_CLOUD_URLBETTER_SUPABASE_STACK,BETTER_SUPABASE_CLOUD_URLAUTH_HOOK_SECRET,BEFORE_USER_CREATED_SECRETBETTER_SUPABASE_AUTH_HOOK_SECRET,BETTER_SUPABASE_BEFORE_USER_CREATED_SECRETbetter-supabase/ai-sdk/workflow/reactbetter-supabase/ai-sdk/workflow-reactdefineSupabase,getBetterSupabase(Svelte)createSupabase,betterSupabase -
Module files no longer paste the helpers they call.
better-supabase upgradewrites one900_better_supabase_000_prelude.sqlthat defines thebetter_supabaseschema, theblockstable,actor_may_write,raise_actor_readonly,acting_member, the column type helpers,import_run,merge_subject_refs, the memo functions andreplace_equivalent_triggersonce. Commit it with the module files. Without a memberships block, the prelude also defines an emptymember_organization_ids, where each module used to create it in adoblock. -
open_items_for_partyreads the invoice's storedpaid_totalwhenas_ofis omitted or today, and still replays the ledger for a past date. An import batch applies items indata.orderBy, thendata.readAt, then key order.Gen treats a function body that returns
coalesce(...)as not null when the catalog includes the body. AfunctionsnotNullentry or an@notNulltag still wins.better-supabase upgraderewrites the invoices and imports modules. The next schema migration replaces those functions. No data migration is needed. -
open_items_pagereturns one page of today's open items and a total that stops at the count cap. -
Today's open items are read from
invoice_open_items, which a trigger keeps current andrebuild_open_itemsrebuilds after an import. A past date still replays the ledger. -
An organization profile import writes the VAT number, registration, default rate, currency and payment accounts. A repeat matches accounts by IBAN, keeps the stored primary account, and skips a VAT number that is only a country prefix.
-
Blocks no longer add columns to a table you create: a feature whose column your table lacks is off. Upgrade: run
better-supabase codemod owned-columnsand commit the*.block-columns.sqlfiles beforebetter-supabase upgrade, then check doctor BS622. A database that has the columns changes nothing. The migration note is in the 0.57 to 0.58 guide. -
better-supabase codemod owned-columnsdeclares, in your schema files, the columns blocks add to tables you create, as<table>.block-columns.sql. Doctor BS622 warns for each such column. A later release stops adding columns to tables you own and turns the feature off instead, so run the codemod before you update. -
The contacts block gets
people.mode(externalortenant) and the company columnslegal_name,registration_idandphone. Document lines get aunit, adiscount_kindand an open-endedperiods(null), shipments get adirectionwithsetDirection, document-templates adds thepurchase_orderdocument type for inventory purchase orders and aletterheadtext block seed fornl,deandfr. They replace app columns and app SQL that added the same. Invoices are unique by identifier, andoptions.uniqueNumberis removed. Runbetter-supabase upgrade, delete your own columns with these names on block-owned tables, and generate a migration withsupabase db schema declarative sync. -
The contacts block reads one record by id:
getCompany(id)andgetPerson(id)return the active company or person, ornullwhen it is archived, missing or hidden from the caller. Runbetter-supabase upgradeto addget_companyandget_person.The read policies of field history, observations, SLA clocks, pipeline history, consents, medication orders and funding awards check the record inline, as reactions and attachments do, so a member reads 12,000 rows of 60,000 records in tens of milliseconds, where
can_subjectper row took seconds. A record type whose team holds the read action still lets the team in.upgradereplaces the policies.An import batch notes the records it changes for search in 256 settings instead of one, so a 30,000-record batch spends 130 ms there, where it spent 5,451 ms.
-
A
party_discount_groupimport puts one party in a customer discount group, or removes it when the group is empty. Quote and invoice lines still pass that party id as text whendiscountMatrixis on. -
The contacts block imports a party, a party contact, a contact method, a location and a bank account. A party name falls back from the display name, and an invalid IBAN is refused.
-
upgrade,syncanddoctorrender each block module once per set of inputs it reads. A change to the config or to an app schema file renders only the modules that read what changed, and serves the others fromnode_modules/.cache/better-supabase/modules/renders.json.--no-cacheskips it andcache purgedeletes it. -
options.resolveAddressof the notifications block names an app function that says where a member is reached on a channel, and deliveries, digests and bounce suppression use it. The Realtime triggers ofconfig.realtime.tablesand of block entities withsubject.realtimeare staticcreate triggerstatements in the schema file, so a schema diff sees them.workflow_opt_outsis an optional table. Runbetter-supabase upgradeand generate a migration withsupabase db schema declarative sync; delete atrack_realtimecall you wrote for a configured table. -
createPostgrestakesssl(trueverifies the certificate, or{ ca, rejectUnauthorized }), andbetter-supabase/postgresexportssharedPostgres, which keeps one pool per process and connection string. -
A product import writes the product and a default variant. The price falls back from the selling price to the list price, then to the last purchase price times a markup. A name that is mostly control characters is refused, and a sku already used by another product is refused.
-
Reads and cache tags follow the app's projection views. A generated block read (
reads.attachments.list) also lists the typed key of each view your schema files project over a table it reads, so a block write invalidates a read served from the view.hooks.tswrites no hooks for a block table that a view projects, and doctor BS351 reports a write through such a view.powersync streamsscopes an attachments view that keeps several subjects (subject_type in ('job', 'quote')) to the rows of each subject's own table, and the Lienlink fixture streamsjob_partiesas a child ofjobs. -
The authorization provider accepts the fields an authorization library fills from one definition, all optional and additive (
apiVersionstays 1, the hook topic staysbetter_supabase:authz):functions.subjectForTenant,approverForandmanagedUsers,memberships[].userKey,suspension.userKey,permissions[].levels(level keys are<permission>@<level>),tokenHook.teamIdsTruncatedClaim, andpersonas: "roles"withfixtureRoles. A provider that listsmembershipsfor the tenant scope no longer needsfunctions.memberIdsandmemberIdsFor: both are derived from the rows.suspension.userKeybecomesblocks.permissions.disabled.userKey, and BS426 reports adisabledvalue equal to the provider's. A bootstrap call that names a tenant gets the subject restricted to it when the provider setssubjectForTenant.better-supabase upgraderewrites thesessionsmodule only for an app that setssubjectForTenant; no data migration is needed. -
The 0.26 provider fields now have readers.
memberships[].userKeyis the column the derivedmemberIdsandmemberIdsFortemplates match againstauth.uid(). A level key (file.read@team) is neversqlComplete, so policies refuse it, and an unlisted level counts as missing.tokenHook.teamIdsTruncatedClaim(andpermissions_truncatedfromtruncatedClaim) feed the hook plan, andBootstrap.teamIdsTruncatedreports a partialteam_idsclaim. The sessionshookoption takesteamIdsTruncatedClaim.approverForandmanagedUsersstay accept-and-validate (ADR 0520).better-supabase upgraderewrites thesessionsmodule only for apps that sethook; no data migration is needed. -
An authorization provider can set
wildcardstoall,prefixornone, and the generatedpermission_matcheshonours only those wildcard grants. Unset keeps today's function. -
protectno longer runs whenbeforereturned a redirect. The redirect's target passes through the proxy again, soprotectruns there. Before, aprotectredirect won over a locale redirect frombefore: a signed-out visitor withNEXT_LOCALE=nlwho opened/projectswas sent to/logininstead of/nl/projects. If you relied onprotectanswering first, return the redirect fromprotectand leavebeforeout for that path. -
The definition from
createSupabase()no longer carries the code that turns it into adb.definition.connect()andregisterTable()call a connection runtime that the client, the servers, the adapters andbetter-supabase/testinginstall when you import them, so anext/proxyconsumer drops from 47.7 KB to 26.9 KB gzip (library code only).createProxy()no longer bundles the PostgREST executor, the query builder or the repositories.Code that imports only
better-supabaseand callsdefinition.connect()now throws aTypeErroruntil it imports a client or server entry. In a script or test, importcreateClient,createServeror a testing helper first.ProxyOptions.afteralso receives the request as its third argument, so a proxy built withcreateProxy()no longer closes over the incoming request:Old New after: (response, auth) => {}after: (response, auth, request) => {}The first two arguments are unchanged, so existing
afterfunctions keep working. -
A purchase order can carry a number and an exchange rate. A line can cancel a quantity and name a tax code. Receiving still posts stock with the receipt reason.
-
Purchase orders take a
numberonsavePurchaseOrder(an order without one gets the next all-digit number when it is placed) andcancelPurchaseOrderQuantitygives up part of what a placed order still owes. The units stop counting as incoming, receipts and the backorder count leave them out, and the event ispurchase_order.line_cancelled. The inventory block also contributes astock_allocationimport target, written byimport_stock_allocation, for the stock a source system's documents held. Runbetter-supabase upgradeto replacesave_purchase_orderand add the new functions. -
The UI recipes in the skill and the docs take plain ids and a
queryobject instead of theparamsandsearchParamspromises, and read the clock behindio()fromnext/cacheinstead ofconnection(). The page resolves the route props withparams.then(). -
A composite foreign key that starts with the same column as a single-column key to the same table keeps that relation's name. The composite is an alias of the join. Doctor BS626 reports two keys to one table whose first columns differ.
-
The last 15 exported types that ended in
Args,SettingsorFailurehave names from their noun, with no alias.better-supabase codemod namingrenames them in your code.Old New ActionArgsActionParamsArgsCallParamsAuthFailureAuthLinkErrorBlockActionArgsBlockActionParamsCliArgsCliValuesCursorPageArgsCursorPageParamsDoctorArgsDoctorValuesHookArgsHookParamsListArgsListParamsReactRouterArgsReactRouterParamsRequestArgsApiRequestParamsRpcArgsRpcParamsSearchArgsTextSearchParamsSettingsSettingsClientTableArgsTableValues -
list_checkout_sessions,list_agent_mandates,list_pick_lists,list_appraisals,list_usage_rightsandlist_maintenance_planspage through the keyset list template, with list indexes that end in the id.checkout.sessionPage,checkout.mandatePage,warehouse.pickListPage,appraisals.appraisalPage,dam.rightPageandmaintenance.planPagereturn{ items, hasMore, nextCursor }, andtotalwhen asked.Migration guide:
Before After listRights({ offset: 100 })Still works. Keep it where you show page numbers. listRights({ offset, after })Refused with an invalid error. Pass one of them. Deep paging with offsetrightPage({ after: page.nextCursor }).listPlans({ due: true, limit: 20 })returning fewer than 20 rowsThe duefilter now runs inside the query, so a page holdslimitdue plans.The same applies to the other five lists and their page methods. Run
supabase db diffto pick up the new list indexes.list_import_issuesandlist_import_diffkeep their positional arguments. -
The 0.46 and 0.47 rename shims are gone. Permission keys, event types, hint codes, subject types and entity keys from before those releases no longer resolve, and
upgradeno longer rewrites the stored permission keys, event types and subject types. This removescurrentPermissionKeys,isOldPermissionKey,PERMISSION_KEY_RENAMES,PERMISSION_KEY_SPLITS,RENAMES_CODEMOD,currentEventTypes,isOldEventType,legacyEventType,legacyHintOf,HINT_RENAMES,ENTITY_KEY_RENAMES,EVENT_TYPE_RENAMES,EVENT_TYPE_SPLITS,SUBJECT_TYPE_RENAMESandPROGRAM_EVENT_MOVES, theformerKeysconfig types, the audit and support action namesviewandviewAll(usereadandreadAll), theautomationSinkrelay of old trigger names, and doctor BS422 to BS425. -
Module upgrades no longer rename the tables 0.47 renamed (
engagementstoactivities,work_itemstotasksand the others in ADR 0130). Upgrades start at 0.53, where those tables already carry their names.codemod namingalso moves thebsb.*policy helper functions tobetter_supabase, and only when the project's SQL names them. -
The
extraColumnsoption and its prefixed forms (lineExtraColumns,categoryExtraColumnsand about 40 more) are removed from every block, and the Create design'sextraColumnskey is gone. A column your own schema file adds to a block's table is a field of the block; for a table you create yourself, list the columns in its comment as@bsb fields plan, seats. A config that still sets an option fails with a message that namesbetter-supabase codemod extra-columns, which moves the columns into your files. It replacesblocks.<name>.options.extraColumns,lineExtraColumns,calendarExtraColumnsand the other prefixed options. Doctor BS378 is removed, and fifteen blocks have no options schema any more. -
renameBlockfollows a renamed client four object levels deep and no longer counts functions, promises and results as levels, so the types instantiate two levels earlier with the same result for every block.better-supabase upgraderewrites no module and no data moves; a block type with more than four nested object levels below its methods keeps its original keys at the fifth. -
With
gen.blockModules,genwrites each instance that renames a block's entities toblocks/<instance>-block.ts, and the generated record types import their blocks from there instead of fromblocks.generated.ts. A record import no longer pulls in every installed block.blocks.generated.tsstill exports the same names. Runbetter-supabase gen. -
upgradeandsyncread rendered modules from a cache innode_modules/.cache/better-supabasewhen the block names, the layout and the CLI version match, and--no-cacherenders them again. Checks in generated SQL write a range asx >= a and x <= b. Doctor gains BS369 (an app file and a block module both declare an object) and BS370 (a schema file asks fortransaction=false). -
The block render cache now keys on a hash of the generator's files as well as the version, so a checkout or a rebuilt
distnever serves output an older generator wrote. -
Three more
@bsbtags render SQL throughbetter-supabase table <name> enable <tag>:rpcwritesget_<table>_by_ids(ids), which returns rows in the order of the ids,rollup storedwrites a trigger that keeps a count or a sum on a parent row, andcopywritescopy_<table>(source), which inserts a copy of one row. Each is written between-- @bsb-tag <name> beginandendmarkers, so a second run replaces it. See Tags that render SQL. -
A rerunnable render, the one a migration repeats, keeps a function a policy still calls instead of failing its
drop function, drops the policy it creates onrealtime.messagesorstorage.objectsbefore creating it again, and keeps the emptymember_organization_idsstand-in from replacing the function memberships defined. A declarative render declares a trigger or policy once when two entities of one block adopt the same app table. -
Under an authorization provider, a block's default permission falls back from
<block>.<action>to<resource>.<action>of its primary entity when the provider lists only the resource key, so a provider that names permissions after resources needs noblocks.<name>.permissionsentries. An explicit entry still wins. -
revoke_ai_chat_shareno longer failssupabase db lintwith an ambiguousidcolumn: the lookup inshare_linksqualifies its columns. Runbetter-supabase upgradeto rewrite the function. -
A function comment
@bsb returns=./file.ts#Schemamakesdb.$rpccheck the jsonb result with that Standard Schema. Zod and Valibot both work. A result that does not match throws. -
approvalWaiter.create(token)registers the approval hook up front and returns a handle towaiton later, so a wake between steps is not lost.resumeStreamResponsetakessse(answers astext/event-stream) andtransform(pipes the chunks through aTransformStream).problem429takes{ extra, headers, format }to add members to the 429 body. -
blocks.memberships.options.sameTenantdefaults to the foreign keys the schema files declare, soupgradewrites absb_same_tenant_<column>trigger for every single-column key between two tenant tables without a config entry. A composite key that pairs the column with the tenant column also counts as covering it. A list now adds entries to the derived ones, andsameTenant: falsewrites none. This replaces thesameTenant: { auto: true }line in app configs. -
A subject's
searchtakescolumnsnext tofrom: the columns of the record's own table the source view reads. The indexing trigger then fires on an update of those columns only, instead of every update. Thedrive_nodesubject sets["name"], so a move, a size change or a lock no longer re-indexes a file. Runbetter-supabase upgradeand generate the migration. -
An import batch indexes each search record once. While
import_upsert_batchruns, the search triggers note the records they touch and the batch indexes them when it ends, and a refresh that finds the same tenant, title, body, URL and description no longer rewrites the document. On a 1,000-row batch with an insert and a rename per row,search_refreshcalls fall from 2,000 to 1,000 and the statement from 500 ms to 240 ms.Watch triggers are plain
create triggerstatements instead of adoblock, andwatch[].columnslimits the update trigger to named columns.better-supabase upgraderewrites thesearchandimportsmodules and no data migration is needed. A watched table that is neither an app table nor a block table gets no trigger from the library, so create it in your own SQL. -
Seeded letterheads and the shared tax keys
STD,REDandZEROnow have English, Dutch and German text.enseeds those rows. The variant argument of a seed function is the brand.better-supabase upgraderewrites the document-templates and tax modules. No data migration is needed. Organizations already seeded keep their rows. -
better-supabase add --adoptwrites only the data statements that no data migration holds yet, andadd --adopt --checkandupgrade --checkexit with 1 when one is missing. Themembership_rolesbackfill moved out of the memberships schema file into its data file. Doctor gains BS357 (a data file insert without a key), BS358 (an app seed that writes a table a block seeds) and BS359 (aseed_*_defaultsfunction without a locale). -
adapterBase(server, options)frombetter-supabase/serverreturns the plumbing every framework adapter shares:expose,flush,refuseandextend. The eleven first-party adapters use it, and the write-an-adapter docs show it. -
gen.serverBlockswritesblocks.<name>.tswith<name>Instancesand<name>Blocks, adefineBlocksover only the instances you list, so a route that builds its server from the set bundles those blocks and not the rest ofblocks.generated.ts.genfails when a listed block requires a port no listed block provides. On the Next.js example the sign-in page, the customers API and the customers page lose 48, 54 and 50 percent of their server chunks. The key is optional and off by default:better-supabase upgraderewrites no module,genwrites nothing new without it, and no data moves. -
defineBlockschecks the port wiring of its blocks once and keeps the resolved providers, so building a block client orserviceBlocksno longer runs the blocks by ports by blocks loop again. -
Recorded in ADR 0451: the
server-importscodemod, and the server chunk and type gates that hold the server's cost. The generated file layout stays as ADRs 0262 to 0265 wrote it. Nothing else changes for apps. -
better-supabase codemod server-importsmoves the account, CSV and rate-limit helpers thatbetter-supabase/serverno longer exports tobetter-supabase/server/accounts,better-supabase/server/csvandbetter-supabase/server/rate-limit. Names that stayed onserverkeep their import, and an aliased or type-only import keeps its form. -
A plugin's
afterMutationevent copies the returned rows on the first read ofrows, so a hook that reads onlykeyspays no copy. -
AsyncResult.fromstarts its run at once instead of one microtask later. -
createNextresolves a request's auth once per read ofcontext()orclaims(): the extra snapshot pass is gone and the claims are derived from the one resolution. -
server.context(request)resolves and builds the context directly when neithertenantnorsupportis configured; servers that configure either keep the composed path. -
better-supabase/serveris down to the core. Import the account and support helpers frombetter-supabase/server/accounts, the CSV helpers frombetter-supabase/server/csvand the rate-limit header helpers frombetter-supabase/server/rate-limit. The old names have no alias.Old import from better-supabase/serverNew import deleteAccount,endSessions,suspendAccount,lastSignIns,supportSessions,supportStorage,sessionStatusRoutebetter-supabase/server/accountstoCsv,csvColumns,csvResponsebetter-supabase/server/csvrateLimitHeader,rateLimitPolicyHeader,isRateLimitPolicyName,periodSecondsbetter-supabase/server/rate-limit -
ServerOptions.sessionstakescounters, an object the verified-token memo counts its hits and misses on, so several servers in one process (a Next.js route handler is bundled apart from the pages) report one total. The memo's ownstats()reads it. Nothing changes without the option.upgraderewrites no module and no data migration is needed. -
The organization settings insert policy checks the tenant with
tenant_ids_withinstead of onecan()call per row. The attachments insert policy still callscan()because its permission depends on the subject type.better-supabase upgraderewrites thesettingsandread-setsmodules (the second because counts are now estimated) and the next schema migration replaces one policy. No data migration is needed. -
Orders take two staff states. Pass
draft: truetoorders.fromLinesororders.fromQuoteto save an order that holds no stock, thenorders.confirmDraftto allocate its stock and place it.orders.holdputs an order that waits for payment, or a confirmed one, on hold andorders.releaseHoldreturns it to the status it was held from;OrderreturnsheldAtandholdReason, and the events areorder.drafted,order.hold_placedandorder.hold_released. Purchase order lines taketaxRateBpsandtaxCode,savePurchaseOrderrebuilds the order's tax lines, andinventory.purchaseOrderTaxLinesreads them. A historical quote import withupdate: "apply"now replaces the lines of a sent or decided quote and applies its stored tax lines and totals. Runbetter-supabase upgradeto add theheld_at,held_from,hold_reasonandtax_rate_bpscolumns and thepurchase_order_tax_linestable. -
initno longer enables pg-delta in asupabase/config.tomlthat lists[db.migrations] schema_paths.upgradeunder themigraworkflow keeps seeing the app's tables once its module files exist insupabase/schemas, so a second run no longer writescreate tablefor them. Theprofilesblock addsactive_organization_idandactive_team_idonly next tomembershipsandteams, so an app with no organizations gets no tenant column. The generatedgenerated.tsno longer importsEnrichDatabasewhen no table needs it, which failednoUnusedLocals. -
The
state-machineblock gains three optional machine settings, and existing machines keep working unchanged.state()returnsnext, the statuses the caller may move the record to now: the edges from its status, without those whose guard the caller fails, and none while the record is paused.status_statereturns it asnext.genalso writes each machine'stransitionsto the block's generated options (blockConfig["state-machine"].options.transitions), so a UI, API or MCP tool reads the edges without a copy.stampssets a column tonow()when a record enters a status, such as{ sent: "sent_at" }, inside the same transition. An insert stamps an empty column, except during an import.guardschecks a transition inside the trigger:permissionis a key the caller must hold in the record's tenant (STATE_TRANSITION_FORBIDDEN, Postgres42501; the service role passes), andcheckis a function of the record's row that must return true (STATE_GUARD_FAILED,23514).
-
The generated schema files hold 4 top-level
doblocks, down from 27. The catalog's row level security and audit triggers are plain statements, thewebhook-inboxkey is oneadd constraint, and the attachments path and storage status backfills, the legal-entities duplicate-number warning and the vector search index notice move to the module data files. The profiles username check staysnot validand is never validated for you; runalter table ... validate constraint bsb_profiles_username_checkonce no profile breaks it.publish_webhook_eventbuilds an endpoint's held grants by the provider'swildcardssetting. Installed apps runbetter-supabase upgrade, then the Supabase CLI sync, thenbetter-supabase add --adopt. -
Block schema files no longer contain a
doblock that creates objects. Policies onrealtime.messagesandstorage.objects, the workflow World's types and row level security, and the flag and team upgrades are written as plain statements or moved to upgrade steps and data files.teamsis at version 3: runbetter-supabase upgradeandadd --adopt.driveandai-chateach leave a function thatdrive-filesandshare-linksdeclare, and doctor reports an object two block files declare. Lite and the Create check add the Realtime and Storage tables PGlite lacks. -
The audit block's row triggers on block tables are static
create constraint trigger bsb_auditstatements in each block's schema file, whatever the install order, so a schema diff keeps them. Runbetter-supabase upgradeand then your SQL workflow's sync. Doctor and the audit test file read the deferrable trigger form. -
Add
better-supabase/storage/client:defineBucketwithout the SQL,config.toml, drift and admin code, for bundles that ship to the browser.better-supabase/storageis unchanged, and itsBucketis now an extension of the new exportedClientBuckettype, whichdefineBuckets,.buckets()anddeleteAccountaccept. In the Next.js example, importing the client entry removes about 11 KB raw from every data route's first load.nextadapters now wait forio()before they read the clock inbsb.resolveandbsb.contextFromSession, so a Next.js runtime prefetch render no longer logsDate.now()prerender errors when the flags adapter or another caller resolves a request with cookies. A prerender never judges token expiry; the check runs when the request does. -
gen.tableModules: truewrites one module per table,tables/<table>.ts, and moves the server's schema togenerated-schema.ts. The generated module exportsclientSchemafor a browser client that registers the tables it uses:bsb.table(customersTable)returns a table's repository, the generated hooks read through it, anddefineListQueryaccepts a table module in place of a table name. A page then ships only the tables it imports.defineTableandTableModuleare new exports,SchemaMeta.lazyTablesmarks a schema whose tables register on use, andBetterSupabase.registerTableadds one. Generated record files importpermissionsfromblocks.config.tsinstead ofblocks.generated.ts, so a record no longer loads every installed block in the browser; runbetter-supabase gento rewrite them. -
A work item can carry ordered specification lines and material lines. Specification lines store a description, quantity, unit and estimate. Material lines point at a catalog variant.
estimated_minutesis an optional column on the item, and the columns and tables can be mapped. -
With the employees block installed, teams hold employees next to users.
team_membersgainsemployee_id(columns.members.employee),user_idbecomes nullable, and the(team_id, user_id)primary key becomes two partial unique indexes.add_team_memberandremove_team_membertakeemployeenext tomember;addMemberandremoveMembertake{ teamId, employeeId },setMemberstakesemployeeIds, andlistreturnsmemberEmployeeIds(member_employee_ids).memberIdslists only user ids. The user on an employee's rows follows the employee's account, so linking an account merges the user's own row, and unlinking it, deleting the auth user or removing the membership keeps the employee on the team. Settingemployees.team_idadds the employee to that team.team_member.addedandteam_member.deletedcarryemployeeId, anduserIdcan benull. Apps without employees see no change. An app that has both blocks runsupgrade, writes the migration, thenadd --adoptfor the data file that backfillsemployee_idand the primary teams. -
The tenant table can be a record type: set
recordTypes.<type>.tenantto its id column, and each organization is its own tenant. The consents block then records a decision on the organization itself, such as an agreement it accepts, and a member can only record one for their own organization.genno longer marks such a table as tenant-scoped, so the client keeps reading every organization the caller belongs to. -
better-supabase/testinggetscreateFakePostgrest, afetchthat answers PostgREST requests from a handler so the real supabase-js client runs without a stack, andasSignedInUser, a test user that signs in through the stack's Auth and takes its claims from the token. The pgTAP module addstests.act_as(role, user_id, claims)andtests.visible_row_count(relation, filter); runbetter-supabase upgradeto rewrite the file. -
The
time-trackingblock istime-entries. Import frombetter-supabase/blocks/time-entries, name itblocks["time-entries"], and usedb.$blocks.timeEntries. Runbetter-supabase codemod namingto rewrite imports and the config key, thenupgrade; the migration renames the block's registry row and its permission keys in place, so roles and overrides keep their grants.Old New better-supabase/blocks/time-trackingbetter-supabase/blocks/time-entriesblocks["time-tracking"]blocks["time-entries"]createTimeTracking,timeTrackingBlock,timeTrackingEventscreateTimeEntries,timeEntriesBlock,timeEntriesEventsTimeTracking,TimeTrackingOptions,TimeTrackingEventsTimeEntries,TimeEntriesOptions,TimeEntriesEventstime_tracking.read,.track,.approve,.managetime_entries.read,.track,.approve,.manage -
defineTopictakesbroadcast, a list of tables whose row changes the topic sends, andbetter-supabase upgradewrites their triggers next to the topic's policies in therealtime.policiesfile.gen.types.alsolists more files that get a copy ofdatabase.types.ts, for apps in a monorepo that share the types;gen --checkfails when a copy is stale. -
gen.types.tables.onlylists the relationsdatabase.types.tsincludes. A page that imports one table module does not bundle the other tables. -
upgradewrites event triggers and triggers onauthtables to one file,900_better_supabase_999_unscoped.sql, instead of into six module files. The workflow-sdk module grants its sequences by name, not withon all sequences. Runbetter-supabase upgrade; the migrations workflow keeps each statement in its module. -
codemod namingloads the config as it rewrites the renamed keys, and reads column pins without the options 0.58 removed (extraColumnsand its prefixed forms,uniqueNumber), so a 0.57 config gets its column renames and pins in one run. It writes{ taskId }instead of{ taskId: taskId }, and renames the key of adefineBlocksentry with its block ("time-entries": blocks["time-entries"]).codemod owned-columnsexitsconfig_invalidwhen the blocks don't render, instead of exiting 0 with advice to runupgrade, and the 0.57 to 0.58 guide runs it afterextra-columnsandconfig. Animports.options.targetsentry whose entity an installed block already imports now fails with a message that lists the entities and namesreplaces: true. Doctor BS330 skips an optional column the app's table lacks unless the config names it, and points tocodemod owned-columnsinstead ofupgrade. Doctor BS626 readsaudit_row_change()trigger arguments. New doctor BS631 reports an app'steam_memberstable that keeps employees while its user column isnot null. The attachments data file gives a record a new path only while no object is stored at the old one. The splitblocks.config.tstags itspermissionsre-export@publicfor Knip. A writtenupgradeno longer reports the problems of the files it replaced. -
codemod namingpins a state-machine historyactorand columns reached throughconfig.instances, and exitsconfig_invalidwhen the config does not load or a block context refuses it, instead of skipping the column renames and exiting 0.codemod owned-columnsskips a column that is the target of a pending pin, and declares an optional column only when the snapshot already has it.codemod extra-columnsexitsconfig_invalidwhen a block context throws. Argument renames stay inside{,blockConfig["..."]is renamed, andrenameSqlColumnstouches a block column only when it is qualified, listed, or set, includingauditignore and redact lists. A partial unique index whosewhereis<column> is not nullcounts as the full key. An expression unique index does not drop a block key.same_tenantrefuses a referenced row with no tenant unless the entry setsshared: true. Doctor BS625 and BS626 report a pinned column added again and an old name left in SQL. -
upgradewrites nothing when one block file was edited by hand, and the error includes the diff.--forceoverwrites that file and leaves the previous body at.bak.--preserve <file>leaves the hand edit and writes the new render beside it as.new.An app table stays free of block grants when
database.sql.ownTablePoliciesis"app". -
Upgrades start at 0.53. An app on an older version upgrades to 0.53 first. This release removes
$apiResult, thetriggerSqloverload, the moduleversionoption, theopenapiconfig key (usespecs), thecanApprovetemplate andapprovals.distinctApprover(isApproveralways refuses the requester),BLOCK_EVENT_RENAMES, the 0.15 block renames, the moved-command table, the codemods 0.4 to 0.53, thebetter-supabase/codemods/*.jsonexport and doctor BS415, BS418 and BS509. The migration guides before 0.53 are gone. -
The
vector-searchblock installs itself for an app with avectorSearchtable or a-- @bsb vector-searchtag, so theblocks: ["vector-search"]line is no longer needed. List the block only to set itsschemaoption. -
A warranty claim records the supplier or manufacturer, the asset, the covered amount, the status and the decision. Attachments hang off the claim, and an approval can make the decision.
-
better-supabase db prune-workflowsisbetter-supabase workflows prune, in aworkflowsgroup with its own docs page. The flags are unchanged and the old command has no alias, so change the cron entries and scripts that run it.Old New better-supabase db prune-workflowsbetter-supabase workflows prune -
upgradeno longer renders every module that adds app columns to a block table when an app file adds a column to one table. A module now reads only the entry of its own table in the app's added columns, so adding the first column to a table re-renders 4 modules on the CentraKit fixture instead of 30. The generated SQL is the same. -
An app table's reference to a tenant-scoped table is a foreign key on
(tenant, column). Its index now covers both columns,(column, tenant), instead of(column)alone, so the foreign key checks and joins read an index and the Performance Advisor no longer reports the key as unindexed. Runbetter-supabase upgradeand generate the migration; the old single-column index is dropped. -
The attachments read and insert policies compare the subject's tenant column with the attachment's tenant. For a subject table with its own
tenant_idcolumn, such asdrive_nodes, the policy text compared the column with itself, so the subject check passed for any tenant. The policies now qualify the attachment's columns. Runbetter-supabase upgradeand apply the migration it plans. -
A batch of permission checks (
tools/listof many tools, say) clones and freezes the verified claims once for the batch instead of once per check. -
With
blocks.sessions.options.authzVersions, deleting an auth user who belongs to an organization no longer fails onuser_authz_versions_user_id_fkey. The membership's cascade delete bumped the version of the user being deleted;bump_authz_versionsnow skips users that no longer exist. Runupgradeand write the migration. -
createVersionCachekeeps at mostmaxEntriesusers in process (default 10,000) and drops the least recently used one first, so a long-lived server no longer holds one entry per user it has ever seen.BlockSet.client(db, key)without options now shares one block builder perdb, so repeated calls wire the port graph once. -
A cursor page that asks for a count (
withCount) reads its rows and its count at the same time instead of one after the other, so a later page costs one round trip of latency, not two. -
BS405 names the estimated cookie chunks when the token's claims pass the limit, because the session cookie is split at 3,180 bytes and 50 memberships already need 4. Doctor output changes only in that message;
upgraderewrites no module and no data migration is needed. -
doctorreportsBS399(info) whenbetter_supabase.audit_eventsis still a plain table with an estimated one million rows or more, and namesblocks.audit.options.partitionedandconvert_audit_log_to_partitioned(). It needs a database; saved snapshots skip it. -
The trigger that freezes an issued invoice checks import mode in its
whenclause. The trigger is deferred and its function ran at commit, after an import had restored its flag, so an import of issued invoices froze every one of them (47,668 freezes, about 219 s on CentraKit's data). Runbetter-supabase upgradeand generate the migration. -
employee.offboardedno longer carries the free-textreason, so outbox consumers and outbound webhooks never receive it. The reason stays on the employee (offboard_reason); a consumer that needs it reads the employee. -
The error code catalog in
schemas/error-codes.jsonnow listsINVENTORY_OVER_CANCEL,INVENTORY_PURCHASE_ORDER_NUMBER_INVALIDandINVENTORY_PURCHASE_ORDER_NUMBER_TAKEN, and the message forIMPORT_DOCUMENT_CHANGEDmatches what the SQL modules scan to. -
field_sealreturns a value that already starts withbsf1:unchanged, so sealing it again does not wrap the ciphertext. -
The provider contract stays additive at API version 1. A provider that still sets
functions.canApproveorapprovals.distinctApproverloads, and doctor notes that both are ignored. Doctor also reports a template placeholder the function does not take, includingapproverForandmanagedUsers, which no module reads yet.Bootstrap.teamIdsTruncatedfollows the provider'steamIdsTruncatedClaim, then the sessions hook option. A compact permissions bitset still decodes after Postgres wraps the base64.claimFormat: "summary"keeps every role whenroles.manyis on: each tenant is a sorted array of indexes. A providersuspension.usermay be a column name, and itsuserKeyapplies only when that user setting is the one in use.A cached JWKS is served for
maxStaleSecondsaftercacheSeconds(the same length by default) and then the request waits. A Supabase key set stays within 600 seconds. A former permission key throwsFormerPermissionKeyError(code: "former_permission_key"), and doctor reports it instead of stopping. -
Maps the AI SDK's
steering-messageUI part to aui.steering-messagedata part that keeps its text and file parts, and letssyncWithAuthinfer its connector type from theconnectoroption, so PowerSync 2.5's overloadedconnectno longer breaks it. -
Moves
better-supabase/client/litetosrc/client/lite/index.tslike every other subpath, lists@supabase/auth-jsand@supabase/realtime-jsas the peers it needs, and widens the@supabase/configpeer range to>=0.9.0 <2(1.x loads on the current effect). A read whoseinlist the executor splits into chunks is no longer reported as truncated because the chunks together holdmaxRowsrows or more.db.$table(name)andwithBetterResultaccept the tables a server loads on first use (gen.serverTables: "lazy", the default), sowithBetterResult(db).customers.get()works over a lazy schema. -
Fixes four functions that failed when they ran:
ensure_import_periodscomputed a period end from a timestamp minus an integer,import_ensure_refandregister_import_sourcenamed columns their parameters shadow inon conflict, andimport_productread and wrote a product price column the block's own table does not have when a prices table is installed. Doctor BS627 and BS628 skip migrations and the files the blocks write, which an app can't change. -
list_inbox_conversationsreads the contacts, inbox and read times of a page in one pass, so a page of 50 conversations takes about 30 ms and a search over 20,000 conversations about 35 ms instead of minutes. The result has the same fields. The inbox module adds the internal functioninbox_contacts_json, so runbetter-supabase upgradeand apply the migration it writes. -
The inline read policies of attachments, reactions and scores compare a subject whose id column your schema files declare as
uuidon that type, so the subject table's primary key serves the lookup without settingidType. The cast sits in the subject's own branch behind a uuid shape check, so a malformed stored id reads as not found. Runbetter-supabase upgradeto pick it up. -
The reaction and score read policies check the subject inline instead of calling
reaction_subject_visibleonce per row. Counting 12,000 reactions as a member takes 20 ms instead of 4,863 ms. Runbetter-supabase upgradeand generate the migration. -
Deal contacts, subject knowledge and deadlines read through inline subject policies, so a read of 12,000 rows on 60,000 customers takes tens of milliseconds instead of seconds. The retention, hold, approval and audit memos keep their keys in 256 settings per connection instead of one per statement, a reply adds to its thread root in place instead of recounting the thread,
messagesgains an index onconversation_idalone, and fifteen(tenant_id, created_at desc)indexes end inid desc. Runbetter-supabase upgradeand generate a migration. -
Adds the JWT matrix bench (
pnpm --filter better-supabase bench:jwt) and records its findings: the access token hook stays under 32 ms at 500 memberships, while themembershipsclaim grows 95 bytes per membership (27 cookie chunks at 500). The package ships no new runtime code,upgraderewrites no module and no data migration is needed. -
Accepts React Native 0.88's
AppStateinautoRefreshOnForeground,startNativeAuthzRefreshand the native query focus helper:AppStateLike.currentStateis now optional and may benull. -
createProxyfrombetter-supabase/next/proxyno longer bundles the server's clients and query builder. It builds from the session runtime thatcreateServeralso uses, so a page and the proxy still share one JWKS cache and one session memo. The shipped proxy shrinks from 64.8 KB to 47.7 KB gzipped. -
A line update recounts a document only when the quantity or unit amount changed, and once for that document.
-
The
notification-bellrecipe reads the unread count in the browser: it calls thenotification_countsfunction on theapischema throughuseBlockEnv().supabase, so the bell no longer needs theloadNotificationCountsServer Action. -
better-supabase/postgresopens a transaction and sets its claims, role and timeouts in one message, so a statement for a signed-in session costs three round trips instead of four. The values are written as escape string literals, which hold on a server withstandard_conforming_stringson or off. -
better-supabase/next/proxyexportstoSession,permissionsOfandpostAuthPath, the helpers aprotectfunction uses, so a proxy can leave out thebetter-supabase/nextentry. -
better_supabase.session_active()parses the token claims once per call instead of three times: it readssubfrom the claims it already parsed rather than callingauth.uid(). Restrictive session policies run it once for each table a statement reads, so a query over many tables with a large token spends about a third of the time it did on the check. Runbetter-supabase upgradeand generate a migration to pick it up. An ended, expired or foreign session is still refused. -
Issuing an invoice with
options.lineRates: "percent"now writes the rate of a line's tax code to the line as a percentage. Before,issue_invoice_taxwrote the code's rate in basis points into the percentage column, so anumeric(5, 2)rate column overflowed and the invoice could not be issued. -
Deleting a subject row deletes its attachments, reactions, reviews and conversation rows through the tenant-led index instead of scanning the table: the cascade trigger passes the subject row's tenant. Run
better-supabase upgradeand generate the migration.
0.57.0 (2026-11-08)
-
deadlinesfollows the read access of each deadline's subject, andcomputeclears the groups a newer rule version dropped. See ADR 0242.- The module reads
blocks.deadlines.on, orconfig.subjectswhen it is unset. With subjects, thedeadlinesread policy,list,compute,recomputeandsatisfyalso need the subject row in the tenant and its read permission (key, providerrows,ownerorcheck).list_deadlinesis now security invoker, so the subject table's policies apply too. A subject type that isn't listed is hidden and refused withDEADLINE_FORBIDDEN. Without subjects nothing changes. computewithout a group deletes the subject's pending rows of that jurisdiction and kind whose group the applying version no longer has. Satisfied rows stay as history.
Run
better-supabase upgradeand generate a migration. If your app hasconfig.subjects, register (or list inblocks.deadlines.on) every subject type you compute deadlines for, or those rows become invisible. - The module reads
0.56.0 (2026-11-07)
-
deadlinesrule format v2: a rule set version is ordered groups of rules, a counting block and opaquemeta, and each group yields one deadline per subject. See ADR 0242.saveRulestakescontent({ rules, groups, counting?, meta? }) instead ofrules, andsave_rule_versiontakes the content as its third argument. Rules select subjects withapplies(codes,present/absent, one date regime), carryexceptionsand a deadline grammar: a countfromorbeforea fact in days, business days or months,day_of_month, monthlyeach: "furnishing_month",first_of,earlier_ofandlater_of. The counting block rolls a last day past weekends and the authored holidays.computeevaluates every group (orgroup) and returns the stored rows. A result isdue,unknown,pending,undated,not_covered,not_applicable,not_requiredorbarred, withprovisional,missing,exception,review,basisand the rule'sdeadline. A group that requires a barred group falls with it.- Facts are three-valued: a missing key is unknown,
nulldoes not exist or has not happened. evaluateVersionandvalidateRuleVersionreplaceevaluateRuleandvalidateRules;evaluate_deadlinesandcompute_deadlinesare the SQL functions.evaluate_deadline_ruleandcompute_deadlinestay as deprecated wrappers until 0.58.deadlinesrows gaingroup_key,period,provisional,exception,review,basis,deadlineandas_of;listfilters bygroupKey,periodandprovisional. Events carrygroupKey,periodandprovisional.
Run
better-supabase upgradeand generate a migration. The upgrade converts stored version 1 rules (anchor,offset) to one group per rule and keeps an approved version's old hash inmeta.previous_content_hash.
0.55.0 (2026-11-06)
-
Record templates live in the same tables as the records they create. A template is still a row in
templates. Its content is a versioned body, or rows whosetemplate_idis set. Tasks, quotes, invoices, orders and purchase orders opt in withoptions.templates. An app table opts in with the@bsb templatetag.While
template_idis set, numbering, search, pipelines, the state machine and domain events skip the row. Audit still records the edit.clone_task,clone_quoteandclone_invoicecopy a row and its children.instantiate_templatecreates a record from a published template and writestemplate_applications.pack_templateandunpack_templatemove a rows template through its version body. -
The PowerSync upload routes replay with
{ override: true }, so a row written offline keeps thecreated_at,updated_at, actor and trash values its device stamped. Before, the timestamps plugin refused them and every offline insert on a table with timestamps was discarded.
0.54.0 (2026-11-06)
-
Document templates take app-defined types:
options.documentTypesnames a type, the app function that builds its variables and its variable contract. Templates, text blocks, snapshots,render_documentandfreeze_documentaccept the new type, andvalidateDocumentTemplatetakes the app contracts as an optional argument. The built-in contract is unchanged. -
approval_eligible_idsnow answers for every pending request in one query. Users, roles, teams, managers and delegations are joins, and each permission is checked once per tenant and permission pair instead of once per request, so a list policy no longer scales with the number of pending requests. Only an access provider'sisApproverstill runs per request. On PGlite with 10 tenants, 54 pending requests take 2.5 ms (11.5 ms before) and 5,000 take 12 ms (920 ms before). Module version 5, no migration step. -
Run the audit log's hash chain on the shared
chainfunctions (audit module version 13).createAuditChainand its types are removed: callcreateChain({ table: "better_supabase.audit_events", tenantColumn: "organization_id", ... })instead, which also gives youproofand evidence bundles. Checkpoints move fromaudit_checkpointstochain_checkpointson upgrade, existing hashes stay valid, and a verdict no longer hasbrokenAt.record_chain_checkpointnow returns the tenant and the signature. -
audit(..., statement => true)works when the app keeps restricted details in their own table (options.restricted, or a mappedaudit_log_restricted_details). The statement trigger writes the log rows and the restricted rows from the transition tables in one insert each, instead of raising "needs an audit log without the restricted table", andimport_run()and the tenant name are read once per statement. On in-process Postgres (PGlite), anupdateof 48 rows went from a median of 20.3 ms in row mode to 8.5 ms in statement mode, and anupdateof 5,000 rows from 937 ms to 504 ms. The audit module is version 11: runbetter-supabase upgrade, thenadd --adopt. -
Adds the
better-supabase/authsubpath. It exportsauthErrorKindand theAuthErrorKindtype, so an app can classify an auth-js error ("retryable","session-missing","invalid-credentials","rate-limited","banned"or"unknown") without importing the server entry. The docs showed an import frombetter-supabase, which never exported it. -
createChainfrombetter-supabase/blocks/auditverifies, checkpoints and builds proofs for any table taggedchain.verifyChainProofchecks one row against its signed checkpoint on WebCrypto alone, andevidenceBundleandverifyEvidenceBundleseal and check a record's proofs and other sections. The audit module gainschain_heads,list_chain_checkpointsandchain_proof; no migration step. -
The
fieldsschema thatgenbuilds from a block'scolumns(andcolumnsSchema) no longer requires anot nullcolumn that has adefaulton input, so a create that leavesrisk text not null default 'low'or ametadatacolumn to its default passes validation. The column is still required on output, and an explicitnullis still refused.columnsSchemanow returnsStandardSchemaV1<ColumnsInput<C>, ColumnsOutput<C>>, andColumnsInputis exported frombetter-supabase/blocks. -
Record the SHA-256 of file bytes. Attachments (module version 9) get
sha256andhash_verified_at, set by the scanner from the file it downloaded. Versions (module version 2) getfile_hashandhash_version, andsnapshottakesfileSha256from the service role.set_attachment_status,version_insertandsnapshot_versiontake one more trailing argument, and the old signatures are dropped. -
New
deadlinesblock (better-supabase/blocks/deadlines): due dates computed from approved, cited rule sets.- Rule sets belong to the platform, one per jurisdiction and kind.
saveRulesstores a draft version andapproveRulesfreezes it with a SHA-256 content hash. Withapprovalsinstalled, approval needs an approved request of the subject typedeadline_rule_version. An approved version can't change (DEADLINE_RULE_VERSION_FROZEN). computeevaluates a rule against a subject's facts and stores the result asduewith a date and a citation, orunknownwith the missing facts named.recomputerefreshes a subject's open deadlines, andsatisfycloses one.evaluateRuleandvalidateRulesrun the same rules in TypeScript, so a preview matches the database.- Events
deadline.computedanddeadline.satisfied. The permission keys aredeadlines.read,deadlines.writeanddeadlines.manage. - The
filingspreset now includesdeadlines.
Run
better-supabase add deadlinesand generate a migration. - Rule sets belong to the platform, one per jurisdiction and kind.
-
Breaking: doctor reports BS315 (a table without an audit trigger, and an
audit.options.exemptentry without a reason) as an error instead of a warning. The 0.53 to 0.54 guide lists the steps: audit the table, or exempt it with a reason. -
Three
@bsbtable tags guard evidence tables.append-onlyrefuses update, delete and truncate,function-writesremoves the Data API write privileges, andchainlinks each inserted row to the previous one with a hash.better_supabase.verify_chain(service role) finds a changed, removed or reordered row, andrecord_chain_checkpointstores signed heads. The audit module is now version 12 and installs the helpers; no migration step. -
Add the
filingspreset for apps that prepare, sign, send and later prove documents. It installs contacts, versions, signatures, approvals, shipments, the ledger, cases, reminders and governance on top ofsaas. -
bsb.withContext(factory)accepts an async factory: each call awaits it, and concurrent calls on one context share a single run.blocks.sessions.options.bootstrapentries taketables(and a{ function, tables?, subject? }form), andgenrecords them inmeta.bootstrap.tables, deriving them from the function body when an entry doesn't declare them.bsb.bootstrap({ rpc })tags its cache entry with those tables, sobsb:<table>@<tenant>invalidation reaches payload RPCs. The snapshot gainsextras.functionSources. The Next.js docs now say which cache scopes tags invalidate. -
New
option-setsblock (better-supabase/blocks/option-sets), lane archiving with a move target, stage icons and brand starters.option-setskeeps tenant-editable items for a field such as priority. A bindingon.<type>.<field>adds an option column to the record and writes the chosen item's level to the field's number column.archiveItem({ itemId, replacementId })moves the records that use the item.createOptionSetsControllerwraps the client for a settings screen. The permission keys areoption-sets.readandoption-sets.manage.taskscontributes aprioritybinding with the items None, Low, Medium, High and Urgent at levels 0 to 4, and addspriority_option_id.pipelines.archiveStagetakes{ stageId, moveTo }. Records in the stage move tomoveTobefore it is archived, and the allowed stage changes do not apply to that move.archive_pipeline_stagenow has two arguments andsave_pipeline_stagetakes anicon. Stages, board columns and stage templates carry an optionalicon.blocks.pipelines.options.brandandblocks.option-sets.options.brand, with abrandsmap on a binding, start an organization of that brand with its own stages or items.
Run
better-supabase add option-setsand generate a migration.archiveStage(stageId)is nowarchiveStage({ stageId }). -
Breaking for generated pgTAP helpers:
tests.authenticate_asreadsauth.usersthrough thesecurity definerhelperstests._user_id_by_emailandtests._email_of, so a test that is already signed in can switch to another user by email or id withouttests.clear_authentication(). Runbetter-supabase gento refreshsupabase/tests. -
Adds
blocks.profiles.options.avatarSource. With"path", the author thatmessage_authorsandattachment_authorsreturn carriesavatarPath(the Storage path from the profilesavatar_pathcolumn) and a nullavatarUrl, so an app that stores avatars in Storage can build the URL itself. The default"url"is unchanged.Authorgains an optionalavatarPath. -
server.transaction(userId, fn, options)runs repositories and blocks as a user in one Postgres transaction. A throw rolls back, and so does a returnedResultthat is not ok. A nested transaction on a direct Postgres client now runs in a savepoint instead of being flattened, so one failed step no longer aborts the others.BetterPostgres.transactionForis the optional hook behind it. -
blockSet.serviceBlocks(admin, options)takesoptions.blocks, a typed map of options per block (a tenant for the comments copy, the Stripe and account resolvers for billing, a TTL for flags, the audit recorder). Each entry is whatblock.with(options)takes and applies for that call only, so a worker can build a different set per tenant or job.ServiceBlocksOptionsis exported. -
Shipments (module version 4) record the proof of delivery:
recordProofstoresdeliveredTo, aproofReferenceand aproofAttachmentIdonce for a delivered shipment and emitsshipment.proof_recorded. A carrier can add the optionalproofOfDeliverymethod. Tracking events are append-only: a trigger refuses edits and deletes withSHIPMENT_EVENTS_APPEND_ONLY, except in a tenant purge. -
Adds
archive_tasksanddelete_tasks, the set forms ofarchive_taskanddelete_task. The client takestasks.archive({ workItemIds })andtasks.remove(workItemIds), checks access once per statement, writes once, and returns{ ids, skipped }with the ids that were refused. The tasks module moves to version 5;better-supabase upgraderenders the new functions. -
The discount matrix on quotes, invoices and orders now casts the party to text before it calls
resolve_line_discount. A uuid company or customer column no longer fails withfunction resolve_line_discount(uuid, uuid, ...) does not exist. -
doctorrule BS243 no longer reports asecurity definerfunction because its body is wrapped in a tagged dollar quote such as$function$. It measures only the quoted literals inside the body, so a migration with a long body and short literals is quiet and a literal above 1,024 characters is still reported.
0.54.0 (2026-11-05)
-
Breaking: doctor reports BS315 as an error, and
tests.authenticate_asreads users throughsecurity definerhelpers. The 0.53 to 0.54 migration guide lists the steps.Old New BS315 warning BS315 error: audit the table or exempt it with a reason exempt: ["public.*"]exempt: [{ table: "public.*", reason: "..." }]Generated tests.authenticate_as(invoker)Run gen; it addstests._user_id_by_emailandtests._email_of -
Columns with a default are optional on input.
better-supabase/authexportsauthErrorKind.blocks.profiles.options.avatarSourcereads avatars as a path or a URL. -
audit(..., statement => true)works with the restricted details table: 48 rows take 8.5 ms (20.3 ms in row mode) and 5,000 rows 504 ms (937 ms), measured on PGlite. Audit module version 11. -
approval_eligible_idsis set based: 54 pending requests take 2.5 ms (11.5 ms before) and 5,000 take 12 ms (920 ms), measured on PGlite with 10 tenants. -
Doctor BS243 ignores a function body's own dollar quote.
-
withContexttakes an async factory, and bootstrap entries taketablessobsb:<table>@<tenant>tags reach payload RPCs. Tags do not invalidate private caches. -
tasks.archive({ workItemIds })andtasks.remove(workItemIds)check access once, write once and return the skipped ids. Tasks module version 5. -
serviceBlocks(admin, { blocks })takes typed options per block for one call.
0.53.0 (2026-11-04)
-
Doctor reports eight shims the library now covers (BS612 to BS619): proxy cookie re-sync with
setAll, an Auth call afterbootstrap, a hand-made authorization version seed, comment paging that filtersdeletedAt, an author re-read after a comment list,withPublicPolicyRoles, a unique violation found by code or message, and a hand-built supportAuthState. The shim registry insrc/cli/doctor/shims.tsholds them.Bootstrap.endReasonis required. A bootstrap wrapper generated before 0.44 returns noend_reasonand the call now fails with an error that tells the app to runsql upgrade; regenerate the wrapper and apply the migration.createEmployeesaccepts the app's own status values increate:genwritesblocks.employees.values.employees.statusinto the generated entry asoptions.statuses.Old New A bootstrap wrapper without end_reasonsql upgradeand apply the migrationBootstrapbuilt withoutendReason(tests)endReason: nullor the reason -
Generated block entries can carry
columns, andgeneratedOptionsturns them into thefieldsoption so block rows are typed from the app's own columns.BlockSet.serviceBlocks(admin)builds block clients that run asservice_role.db.$decode(table)reads rows from$clientorqueryRaw(database names) into the table's shape and codecs, and returns aResult. The api-keysprefixoption is emitted intoblocks.generated.ts.create_employeerejects every app value mapped to the offboarded label, not only the literaloffboarded. -
createNextkeeps the schema'sDatabasetype:ctx.supabaseisSupabaseClient<Database>inbsb.context(),cached(),getAccess()andaction.ServerContext,BetterNext,CachedContextandNextResourcetakeDas a last type parameter that defaults toany, so code that names them keeps compiling.bsb.actiontakes aboundschema for the leading arguments ofaction.bind(null, id), andtenantand the body read the validated tuple.bsb.withContext(factory)returnscached,getAccessandactionwith the app's own context, built once per scope.cached({ readSet })tags the entry with the read set's tables.genwarns about bare strings inblocks.audit.options.exempt; they become a doctor failure in the next minor. -
Adds
authErrorKind(error)tobetter-supabase/auth(retryable,session-missing,invalid-credentials,rate-limited,bannedorunknown; it readscodeandstatusfirst). The block auth failures anddeleteAccountuse it, so a 429 is arate_limitederror. TheSupportApimethods accept aSupportCaller: anAuthState, or{ token, claims }.bsb.actiontakesguard(tenant, ctx), which runs after authentication and the permission check, andresult(outcome), which maps theActionResult. -
Audit is cheaper per row. The row and statement triggers and
audit_eventreadimport_run()once into a variable. The row trigger looks up the tenant's name once per tenant and transaction (memo_get/memo_set), and the statement trigger joins the organizations table once per distinct tenant instead of once per row.sql upgradewrites one pgTAP file for all audited tables,900_better_supabase_audit_tables.test.sql, and removes the old per-table files.blocks.audit.options.exemptis typed asreadonly (string | { table, reason })[]; a bare glob string still works, and doctor reports it (BS315).The
webhooks-outdelivery indexes (due,open) use the mapped status values, so an adopted table with other labels is indexed correctly. Doctor reports a live partial index that differs from the module's definition (BS363);create index if not existsleaves such an index as it was, so drop it and runsql upgrade. Thegen.apiwrappers copystableandimmutablefrom the function they wrap instead of being volatile, so Postgres can inline and cache them; runsql upgradeto rewrite existing wrappers. Doctor reports a volatile wrapper around a stable function (BS364).approvalsaddsapproval_eligible_ids(tenant), the pending requests the caller may decide, as a set forid in (select ...)in policies and forlist_approvals. It callsapproval_eligible, so the two agree, and a pgTAP file checks that for each user.sql upgradewrites the function. -
better-supabase/testinggainscreateFakeClient(handler), a supabase-js stand-in that records each request (method, path, query, body), answers.single()and.maybeSingle()like PostgREST (a miss isPGRST116) and supports.schema()and.rpc(). Test tokens still come fromsignTestJwt. The pgTAP helpers addtests.authenticate_as(email)andtests.authenticate_as_issued(user_id, hook), which runs your custom access token hook for the claims.hookdefaults toauth.hook.custom_access_tokenfromconfig.tomlwhensql syncwrites the helpers. -
endSessions,lastSignInsandsuspendAccountaccept aBlockTransportbesides aSqlClient, and the sessions module gainsbetter_supabase.end_sessions(p_user).server.endSessionsandserver.suspendAccountuse the service role's Data API whenpostgresis not configured, andserver.lastSignInsis new.genadds the block API schemas thatschemasdoes not list todatabase.types.ts(turn it off withgen.api.types: false), soclient.schema("api").rpc(...)is typed.blockSet.serviceBlocks(admin)builds the block clients over onerpcTransport, calling the API schema each generated entry names. -
AuthorizationProvidergains optional fields that fill config defaults:functions.subject(the bootstrap subject), rolethroughwithtenantandwhere, membershipdisabledAt,platformRolesandpersonas.AuthorizationProvider<Key>types the permission keys inblocks.*.permissions,subjects.*.permissionsand role lists.providerPersonaTestswrites one access matrix file per persona, and doctor BS426 reports config values that repeat the provider's. -
Keeps block code out of the browser bundle.
genwritesblocks.config.ts(data only), the scaffold splitsindex.tsintoapp.tsand a serverindex.ts, andgen.clientBlockslists the instances the browser needs, written toblocks.client.ts. Generated data hooks use the newdefineListHookanddefineOneHook, and the block and schema definers are annotated as side-effect free so bundlers drop what the app doesn't import. Runbetter-supabase codemod 0.53, thengen.doctorrule BS511 flags a client component that importsblocks.generated,providers.tsordefineBlocks.Before After import { blockConfig } from "./blocks.generated"in client codeimport { blockConfig } from "./blocks.config"createClient(betterSupabase, ...)inclient.tscreateClient(app, { blocks: blockConfig })withappfromapp.tsexport const { useList: useX, useOne: useY } = defineDataHooks(...)useX = defineListHook(...),useY = defineOneHook(...)(defineDataHooksstill works) -
The approvals module (version 4) reads the caller's role, team and manager approvals once per statement through the new
approval_fact, kept withmemo_getandmemo_setunder the statement start and a generation that statement triggers on memberships, the roles table, team members and employees move. Permission approvers still callcan()for each request, so any authorization provider decides them live. The request's status, step and decisions stay live per row.approval_eligiblegains anapproval_eligible(approval_requests)overload, soapproval_eligible_ids,my_workand app policies pass the row instead of fetching it again. Runbetter-supabase upgrade, thenadd --adoptfor the block row.
0.52.0 (2026-11-04)
- The jobs drain makes fewer database calls.
ensureScheduleswrites only the schedules that are new or whose cron, time zone, queue, tenant or payload changed, so a reconcile on every drain costs onelist_schedulescall when nothing changed.drainRouteasks once which queues have a job to claim and claims only from those, instead of oneclaim_jobscall per empty queue. ThequeueSQL module moves to version 11: it addsready_job_queues(queues text[])and apayloadcolumn onlist_schedules, andQueueProvidergains an optionalreadyQueues. Runbetter-supabase upgrade; until then the drain reports the missing function and claims from every queue as before. - With
debug.enabled,bsb.actionlogs the request's database stats in the same format as thex-bsb-db-callsheader, because a server action cannot set response headers.testAuthorizerchecks that an authorizer ignores aruntime.seedfor another user or a version that is not live. better_supabase.audit()takesstatement => true, which audits a table with statement-level triggers over transition tables and writes every entry of a statement in one insert. The audit module moves to version 10 and drops the previousaudit()signature on upgrade; calls that name their arguments keep working.- Add
createVersionCache({ store, maxStaleMs })tobetter-supabase/server, asubjectoption on the sessionsbootstrapentries thatbsb.bootstrapreturns andaccessForpasses to authorizers asruntime.seed(AuthzSubjectSeed), and doctor code BS611 for a service-role client inside a"use cache: private"function. - Ship reads for the data most pages share.
comments(list,counts),notifications(inbox,counts),saved-views(list),tags(list,forSubjects) andattachments(list) now appear inreadsinblocks.generated.ts, so a read set loads them with the page's own rows ass.blocks.<instance>.<read>(args).tagsgains thesubjects_tagsfunction behindforSubjects, and a read argument can betext[]. - Load a read set with the session check.
blocks.sessions.options.bootstrapaccepts{ readSets, shell? }, the wrapper takesread_setandread_params, andbsb.bootstrap({ rpc, readSet, params })returns the decoded result asreads. When the request already ran the wrapper, only the read set runs.db.$decodeReadSet(readSet, params, payload)decodes a payload that ran elsewhere. Rendering the new wrapper drops the one-argument version. doctor --explainnow accepts a function name with--argsand reports the share of time spent in security definer helpers. New rules BS243 (a security definer function with a literal above 1 KB) and BS244 (schema cache pressure) check the schema. Theupdated-atmodule addsbetter_supabase.memo_getandmemo_set, a value kept for one transaction, and BS206 points to them.gen.api.expose: "used"andgen.api.exposeAlsowrap only the functions your sources call.better-supabase doctor --explain-write <tables>plans an insert (a copy of one row with fresh keys) and an update on each table in a rolled-back transaction, and reports the time of every trigger from theEXPLAINplan.better-supabase/nodeexportskeepAliveFetch({ connections, pipelining }), afetchfor the Supabase client that keeps sockets open through the optional peerundiciand falls back to the globalfetchwithout it.defineListQuery.run({ count: "planned" })is documented, andtests/benchholds a PostgREST floor script and an executor comparison.- Warn about nested private cache scopes. In development
bsb.cached()logs once when it runs inside another cache scope (best effort, from the async stack), andbetter-supabase doctorreports BS610 for a"use cache: private"function that calls another one. - Gate a read set entry on a permission with
s.when(auth.can("customer.read"), entry). The compiled function checksbetter_supabase.can, a refused entry isnull, and the batch path checks each gate once.ReadSetGateis a new type export. - Check a read set result with
readSet.parse(value), and find groups of parallel reads withbetter-supabase codemod read-many, which lists eachPromise.allthatdb.$manycan load in one round trip. Doctor BS609 counts$rpcand block calls in the samePromise.all. - Count token verifications and service-role calls per request.
db.$stats(), thex-bsb-db-callsheader, theauthevent and the OpenTelemetry spans now reportverificationsandadminCallsnext to calls and waves,expectDbBudgettakesmaxVerificationsandmaxAdminCalls, and the stats collector falls back to the trace id,x-vercel-idorx-request-idwhen a request has nox-bsb-request-id. Pass{ request }tobsb.admin()to attach an admin call to its render. - Add
bsb.sessionHandle()andbsb.cached({ session })tobetter-supabase/next. A page parks its verified session once, and each'use cache: private'island resolves it from the serializable handle without readingcookies()orheaders(), verifying the token or building another PostgREST client. The verified-token memo now keys by a SHA-256 digest of the token instead of the token itself. - Documents the cost of each render stage (database calls, waves, verifications and admin calls) for a customer page, and asserts it in
tests/next/customer-reads.test.ts.
0.51.0 (2026-11-03)
-
The invitations block adds
accepting_invitation(), which returns the invitation thataccept_invitationoraccept_invitation_by_idis accepting while it inserts the membership or platform role, and null otherwise. Triggers on the membership table can read the invitation'sprefillthrough it instead of matching on an email address. -
Chats can be shared with teams, customers and external people, and by a live link that you can rotate. The
ai-chatSQL module moves from version 5 to 6, so runbetter-supabase upgrade.- Visibility is now
private(the owner only),organizationorshared(the owner, participants, members of participating teams and the live link). Adding a participant to a private chat makes itshared, and the upgrade moves private chats that have participants toshared. An organization member who is not a participant can't read a shared chat. ai_chat_participantsgets a surrogateidand akind(user,team,customer,external) with the columnsteam_id,customer_user_idandemail; the upgrade backfillskind = 'user'.AiChatParticipant.userIdis nowstring | undefinedandlistreturns the owner first with the roleowner.- New
participants.addPartyandremoveParty,links.create,rotate,revokeandget(a newai_chat_linkstable and the SQL functionsadd_ai_chat_party,remove_ai_chat_party,create_ai_chat_link,rotate_ai_chat_link,revoke_ai_chat_linkandget_ai_chat_by_link), andchats.shareSummaries(ids). - The new
teamMembershipoption names the function(team uuid, user uuid) returns boolean. It defaults to the teams module's members when that module is installed. - Chats take an optional
modecolumn oncreateandupdate.
- Visibility is now
-
createAgentRuntimeapplies the AI Gateway attribution inprepareCalland merges it into the call'sproviderOptions(the library'suserwins,tagsare the union, other keys keep the call's value) instead of replacingproviderOptionsinprepareStep.createWorkflowAgentRuntimeinbetter-supabase/ai-sdk/workflowbuilds an AI SDK 7WorkflowAgentfrom the same options: the tenant'sasktools, high-risk operations and yourtoolApprovalcheck run as each tool'sneedsApproval, andtoolApprovalSecretsetsexperimental_toolApprovalSecret.agentRuntimePartsandmergeGatewayOptionsare exported for custom runtimes. -
createAssistantinbetter-supabase/ai-sdk/chatcontinues a turn after a tool approval and takes yourUIMessagetype as a generic.Option or field AI SDK 7 field toolApprovalSecretexperimental_toolApprovalSecret(HMAC-signed approvals)AssistantRunResult.toolstoUIMessageStream({ tools })AssistantTurn.continuationOftoUIMessageStream({ isContinuation })through the same idcreateAssistant<UI_MESSAGE>safeValidateUIMessages<UI_MESSAGE>,onEndmessage typeWhen the client sends the stored assistant message with
approval-respondedparts, the assistant copies only theapprovedandreasonfields onto the stored message, rejects a signature that differs from the stored one (403) and a decision with no pending request (409), then saves the answer under the same message id.assistantBodyinbetter-supabase/ai-sdk/reactsends that message after an approval. Theexperimental_lowMemorycomment now namesexperimental_streamTextLowMemory. -
appTables.<name>.embedding(or the@bsb embeddingtag) keeps a vector column current from the table's text columns through pgmq, pg_net and pg_cron. Serve the worker withembeddingWorkerordrainEmbeddingsfrombetter-supabase/ai-sdk/embeddings;renderAutoEmbeddinginbetter-supabase/sqlrenders the same SQL for other tables.blocks.knowledge.options.autoEmbed(knowledge module version 7) sends pending chunks to the same worker. Doctor gains BS241 (embedding jobs read five times or more) and BS242 (failed pg_net requests). -
durableTransportanduseDurableAssistantinbetter-supabase/ai-sdk/workflow/reacttake every AI SDK 7WorkflowChatTransportOptionsfield exceptapi:fetch,onChatSendMessage,onChatEnd,maxConsecutiveErrors,initialStartIndex,prepareSendMessagesRequestandprepareReconnectToStreamRequest.useDurableAssistantreads them fromtransportOptions. The library builds the request first (the approval body,config.headers), then yourprepareSendMessagesRequestandprepareReconnectToStreamRequestextend or replace it, and itsheadersare honored. A reconnect that gets204resolves to no stream. -
better-supabase/ai-sdk/workflowkeeps more of the AI SDK 7 answer in a durable chat.Change AI SDK 7 field DurableTurnAgentResult.errorerroron theWorkflowAgentstream resultThe save step keeps data-*partsdata-*chunks andmessage-metadataof the UI streamcontext,userId,organizationIdpassed to the agent function as DurableTurnAgentArgsdurableChat({ context })typed per app: durableChat<UI_MESSAGE, CONTEXT>resume({ startIndex: -5 })WorkflowChatTransportnegativestartIndexfor reconnectsx-workflow-stream-tail-indexon streamsthe World's stream tail index, counted in UI chunks A result with an
errorends the turnfailedand saves the error on the run.DurableTurnInput,DurableTurnAgentArgs,DurableTurnDepsandDurableChatOptionstake the context type as a generic that defaults toundefined, so existing code compiles unchanged. -
New
embeddingCacheMiddlewareandrerankHitsinbetter-supabase/ai-sdk/embeddings, anddimensionsonembedWithand the searchEmbedder. -
AI SDK 7 settings reach more of the library.
createAgentRuntimesetstelemetry(functionId: "agent:<id>",includeRuntimeContext: { organizationId: true }) someterTelemetrymeters agent calls, and takestelemetry,settings(the otherToolLoopAgentsettings),prepareCall,prepareStep,compact(pruneMessagesoptions) andtoolApprovalSecret(experimental_toolApprovalSecret).rerankWithand the memory extraction call pass the tenant, sorerankandgenerateTextusage is metered.searchToolisstrictand takesmodelOutput: { maxCharacters }.connectToolstakesmaxRetriesandaskUnlessReadOnly.useAssistantcalls the server's stop endpoint before it stops the local stream, and the completion and object routes settleonFinishwhen the request aborts.WorkflowAgentRuntimeOptionsomits the options aWorkflowAgenthas no setting for (WorkflowOmittedOptions). -
guardrailsMiddlewareinbetter-supabase/ai-sdkis an AI SDK 7LanguageModelMiddlewarethat runs the ai-guardrails policy arounddoGenerateanddoStream: a blocked input returns the refusal without calling the model, a redaction rewrites the prompt, and a streamed text block is held untiltext-endand emitted redacted. The text helper that was calledguardrailMiddlewareinbetter-supabase/blocks/ai-guardrailsis renamed, because it never was a middleware.Old New guardrailMiddleware(block export)guardTextGuardrailMiddlewareOptionsGuardTextOptions -
The
Embedderinterface acceptsapiVersion: 2, whoseembedreturns{ embeddings, usage?: { tokens } }; version 1 embedders keep working, andembedVectorsnormalizes both.embedWithfrombetter-supabase/ai-sdk/embeddingsnow returns a version 2 embedder that reports the AI SDK 7embedManyusage.tokens, so code that calledembedWith(...).embed(values)directly reads.embeddings.KnowledgeHitgainschunkIdandorganizationId,createKnowledgetakesdimensions(the hintKNOWLEDGE_DIMENSION_MISMATCH) andpriorityOrder, and the memory block accepts the same embedders. The knowledge module is now version 6:knowledge_searchtakespriority_order(default true, false ranks by score alone) and returnschunk_idandorganization_id, so run the upgrade migration to replace the function; the earlier signature is dropped. -
better-supabase/ai-sdkkeeps the AI SDK 7 tool fields when it converts messages, and the canonical AI message format moves to version 2 (schemas/ai-message-v2.json,SPEC_PINS.aiMessageis"2"). Version 1 messages stay valid andai-message-v1.jsonstays published.Part New field AI SDK 7 field tool-calldynamic,title,toolMetadata,rawInput,inputEncoding,statedynamic-toolpart,title,toolMetadata,rawInput,inputEncoding,input-streamingtool-resultpreliminarypreliminarytool-approvalsignature,isAutomatic,requestReason,descriptor,inputSchemaInputthe same names on approvalA call the SDK reported as dynamic now comes back from
toUIMessageas adynamic-toolpart instead oftool-<name>, and aninput-streamingcall comes back asinput-streaminginstead ofinput-available.toUIMessage,toUIMessages,fromUIMessage,validUIMessagesandUIMessageSchemastake yourUIMessagetype as a type argument. -
meterTelemetryinbetter-supabase/ai-sdkrecords each row under the sourceai:<functionId>(for exampleai:inbox.suggest-actions) instead ofai:telemetry, and takesidempotencyKey(event),actorandmetadataoptions plus a function form ofsource.rateLimitMiddleware({ rateLimit, scope, key, organizationId })is a language model middleware that refuses a call before the model runs with arate_limitederror (codeAI_RATE_LIMITED). Setsource: "ai:telemetry"to keep the old source. -
New
uploadToProviderandproviderFilePartsinbetter-supabase/ai-sdk/filessend an ai-files file to a provider's Files API and reuse the stored reference. -
New
postgresMcpEventStoreanddedupeMcpEvents(MCP event subscriptions in Vault),aiTranscriber,realtimeTokenRouteandtoolSearchFrominbetter-supabase/ai-sdk. -
Agent skills carry files and provider references. The
agentsSQL module moves from version 1 to 2, so runbetter-supabase upgrade. NewsyncSkill,anthropicSkillOptions,openaiShellSkillsandharnessSkillsinbetter-supabase/ai-sdk/agents, andagents.recordSkillSync. -
meterTelemetrykeys each usage row onai-call:<callId>:<responseId>, the AI SDK 7LanguageModelCallEndEvent.responseId, and falls back to the step index when the provider returns none. It keeps at most 1,000 calls in flight and releases a call on theonEnd,onAbortandonErrortelemetry hooks, so an aborted stream no longer leaks its tenant. -
better-supabase/ai-sdk/workflowseparates permanent from transient step failures and renames two types.The durable steps throw a
FatalErrorfor a database failure a retry can't fix (forbidden,not_found,validation,conflictand the other constraint kinds), and aRetryableErrorwith the error'sretryAfterforrate_limitedandquota_exceeded. Other errors keep the step's default retries.durableStepError(error)exposes the mapping.Old New DurableAgentArgsDurableTurnAgentArgsDurableAgentResultDurableTurnAgentResultDurableAgentis the deprecated@workflow/ainame. The old names were never released, so no aliases remain. -
App tables take
columnGroups:tables.<name>.columnGroups.<group> = { columns, update }renders abefore updatetrigger that raises42501when a caller signed in asauthenticatedoranonchanges a listed column without theupdatepermission in the row's tenant. Doctor adds BS362 for an update policy that checks a permission ending in.reador.view. -
Approval requests can ask for several items, each decided on its own.
approvals.request({ subject, input: { action, items } })filesapproval_itemswith a permission anddependsOnper item,decideItemsapproves or rejects them (an item waits for its dependencies, and the request settles when none is pending),recordCreatedstores the record an approved item created, andsettlelets the service role close a request with a system decision that wakesrequestAndWait.getreturnsitems, anddecideForSubjecttakesdecidedBy.approveandrejectrefuse a request with items. TheapprovalsSQL module moves from version 1 to 2, so runbetter-supabase upgrade. -
Chat SDK webhooks can be received and processed in two steps, WhatsApp replies respect the 24-hour window, and the inbox broadcasts more. The
inboxSQL module moves from version 8 to 9, so runbetter-supabase upgrade.- New
chatWebhookPipeline({ chat, receiveChat, adapter, inbox, retry })returns{ receive, process }.processreplays withdeduplicate: falseandpropagateHandlerErrors: true, so a handler error fails the queue job; it throws aTypeErrorwhen both Chat instances share a state prefix. inboundHandlertakesdeduplicate("first-attempt"by default,"always","never"),interactive,actionsandonAction.ChatInboundEventgetsattemptandChatWebhookResultgetsretryIn. A webhook-inbox handler may return{ retryIn }to pick the retry delay.- Inbound events get a
processingstatus, anavailable_atbackoff and a lease; a stale lease is picked up again. - New
sendWithinWindowOrTemplateandChatWindowClosedError(CHAT_WINDOW_CLOSED), andwhatsappInteractiveOffor button, list and quick replies. Conversations getlastInboundAtandactiveStreamId; deliveries getdeliveredAt,readAtandfailedAt. - New
conversations.setActiveStream({ conversationId, streamId }), theINBOX_STREAM_ACTIVEerror, theevent.createdbroadcast and therealtimeColumnsoption.Topic.triggertakescolumns.
- New
-
chat-sdk-stateis now version 2: TTLs arebigintmilliseconds, list trimming takes an advisory lock, andcreateSupabaseState().connect()fails with a clear error when the module is missing. Re-runbetter-supabase add chat-sdk-stateand apply the migration; the upgrade drops the version 1int4functions.The scheduler stores its queue under
better-supabase:scheduledinstead ofchat:scheduled. A value under the old key is read once and moved.Old New chat:scheduledbetter-supabase:scheduledAlso new in
better-supabase/chat-sdk: theChatInboundStoreport (inboxStore,webhook({ sink })for the queue block's webhook inbox),capabilitiesOf(needs the optional peer@chat-adapter/catalog), andInboxAdaptersupport for actions, reactions, stop actions, file upload andai_generatedmetadata. -
db backfillchanges the elements of a jsonb array with--array <path> --match <json>and--deleteor--merge <json>. It runs inctidbatches, and--dry-runprints the number of rows and elements it would change. Doctor adds BS240 for a migration that renames or removes an enum value (alter type ... rename value,delete from pg_enum), and thedbdocs describe how to remove a value through a new type. -
New
better-supabase/json-renderapplies, collapses and validates json-render specs.assistant({ parts: { compact } })rewrites the response before it is saved, and the ai-files document kindspecstores a spec (ai-filesSQL version 3, so runbetter-supabase upgrade). -
The
queueblock gets leases with a completed state and a bounded wait. ThequeueSQL module moves from version 9 to 10, so runbetter-supabase upgrade.- New
createLeases(source)inbetter-supabase/blocks/queuewithclaim({ scope, key, timeoutMs, leaseSeconds }), which answersclaimed,busy(withretryAfterMs) orcompleted, andwithLease(options, fn), which extends the lease whilefnruns, releases it whenfnthrows and marks it completed withcompleteFor. - New SQL functions
claim_lease,extend_lease_claim,complete_leaseandrelease_lease_claimover a newjob_leasestable. Theidempotencyblock'sacquire_leasefamily and thewithLeasehelper are unchanged. startOncewith a run registry now ends its dispatch claim when the workflow start throws, so the next caller starts the run at once instead of waiting for the 60 second lease.
- New
-
The
rate-limitSQL module is at version 2:rate_limit_rulesgetsorganization_id, so a scope has one global rule and one rule per organization.RateLimit.setRule({ scope, organizationId, max, period })writes it (set_organization_rate_limitin SQL), andcheckandcheckAlltakeorganizationIdto apply it.hit_rate_limitandcheck_rate_limittake a fifthorganization_idargument. Runbetter-supabase upgradeto add the column and drop the primary key onscope. -
The
streamsmodule stores chunks asbytea(module version 2, with an upgrade that converts existing text chunks).StreamStore.appendacceptsstringorUint8Arraychunks, the Postgres store addsreadBytes, andresumableStreamContext(store)frombetter-supabase/streamsanswers theresumable-streamcontext API, so the AI SDK resume route works on Postgres. Thequeuemodule moves a waiting message earlier when a repeated dedupe key arrives with a shorter delay. -
Streams work with the
resumable-streampackage and the AI SDK'sconsumeSseStream. ThestreamsSQL module moves from version 2 to 3, so runbetter-supabase upgrade.resumableStreamContextnow matchesresumable-stream:resumeExistingStreamresolvesundefinedfor a stream that was never created andnullfor one that finished (it replayed the whole text before; passreplayFinished: trueto keep that), and a newresumableStream(id, make, skip)creates the stream or joins the running one.- New
consumeSseStreamInto(store, { streamId, onStreamId, waitUntil })fortoUIMessageStreamResponse({ consumeSseStream }). - New
better-supabase/streams/resumablewithpostgresPublisherandpostgresSubscriber, socreateResumableStreamContextfromresumable-stream/genericruns on Postgres and Realtime without Redis. It uses the newstream_kvtable and the functionsstream_kv_get,stream_kv_set,stream_kv_incrandstream_kv_publish.resumable-streamis an optional peer. - New
purgeScheduleandpurgeOlderThanoptions schedulepurge_streamswith pg_cron, which also deletes expired keys. redisStreamStore({ reader })hides streams that anotherowneropened fromread,status,isCancelledandcancel.
-
usage.setQuotaandusage.removeQuotaset and remove the quota of an organization or a plan with a service transport, over the newset_usage_quotaandremove_usage_quotafunctions of theusageSQL module (version 8). Runbetter-supabase upgradeto install them. -
better-supabase/workflow-sdkaddsstartChild, which starts a child run with the parent's tenant, actor, ticket and subject.approvalWaiter.wakeretries a missing hook up to four times, so an approval decided before the run reachescreateHookstill resumes it.createWorkflowsreturnsWorkflows<F>, with the extra run columns fromfieldstyped and parsed onrun.fields.teeToStorecounts UTF-8 bytes forflushBytes. -
better-supabase/workflow-sdk/worldfollows@workflow/worldand@workflow/world-postgres5.1 (peer range>=5.1.0 <5.2, protocol 5.1.0). Theworkflow-sdkmodule is version 4: apply its migration before you deploy, because it converts the World timestamps totimestamptz.createWorld()now returns one World per process,onDeadLetter,enableInvokeandstreamFlushIntervalMsare new options,world.start()fails withMigrationDriftwhen the installed World migrations differ from the generated ones, andopenHooks()decodesmetadata_cbor.Release age exception (ADR 0210): the repo owner allowed
@workflow/world@5.1.0,@workflow/world-postgres@5.1.0,@workflow/world-local@5.2.0and@workflow/errors@5.1.0throughminimumReleaseAgeExcludebefore the 1440 minute window closed; remove the list on or after 2026-11-03 22:46 UTC. -
The
workflowsrun registry takes an idempotency key and a dispatch lease (module version 4), accepts run extra columns throughblocks.workflows.options.runExtraColumns, and installs without schedules, semaphores or start requests when those tables are mapped tonull.startOnceinbetter-supabase/workflow-sdkacceptsregistry: workflows.runsand throwsWorkflowRunKeysMissingError(WORKFLOW_RUN_KEYS_MISSING) when it has neither a registry nor World run keys. The resume route maps a missing hook to 404 and other engine failures to 503 or 500. -
Tested against ai 7.0.159, @ai-sdk/react 4.0.163 and @ai-sdk/workflow 2.0.91. Adds
@chat-adapter/catalog(>=4.43 <5) as an optional peer for the chat-sdk helpers that read the adapter catalog. Install it only if you use them. The peer ranges for the AI SDK packages are unchanged. -
bulkDecideon the Flags SDK adapter no longer answers{}when the flag definitions fail to load. It now answers each flag'sdefaultValue, and throws with the load error for a flag that has none, asdecidedoes, soevaluate([...])reports an outage instead of serving no value. The Flags SDK docs showmergeProviderDatafor a project that uses this adapter next to Vercel Flags, and the chat UI recipes add achat-message-markdownrecipe that renders answers with Streamdown. -
record_inboundnow works as a realservice_role. ThecontactsSQL module moves from version 2 to 3 and grantsresolve_persontoservice_role, and theinboxmodule moves from version 9 to 10 sorecord_inboundruns assecurity definer. Runbetter-supabase upgrade.
0.50.0 (2026-11-03)
-
Doctor reports BS361 when an app table's check constraint or enum rejects a value the installed block writes. The check renders the block with the adopter's config and reads the literals its insert and update statements write, so a value the config stops the block from writing, or one only an API caller can pass, is not reported. A narrower check, such as one on an adopted
notification_deliveries.statusthat predates digests, still reports theheldanddigestedwrites and names the constraint.The notifications docs name the statuses the block writes (
pending,sent,failed,skipped,heldanddigested) and the migration guide from 0.48 to 0.49 explains the upgrade.
0.49.0 (2026-11-03)
-
Finish the renames that the naming convention left open, and give each block manifest a
description.Old New operation actions view,viewAll,edit,admin,viewSensitiveread,readAll,write,manage,readSensitiveEngagementNotes.actionItemsand the columnaction_itemsactionTaskIdsand the tableactivity_note_actions(tasks)table invoice_e_deliveriese_invoice_deliverieshint codes EINVOICE_*E_INVOICE_*Run
better-supabase upgradeto rename the table and to copy stored action items into tasks (thetasksblock must be installed). Old operation action names in delegated tokens still resolve.parseScaledis exported fromcommerce/moneyand shared with the audit file readers. Every block manifest takes adescription, which the block catalog reads. ADR 0206 recordsinvoice_e_endpointsas the one naming exception. -
Add the
commissionsandreferralsblocks. Commissions keeps plans (flat or marginal tiers) per seller, accrues commissions on the ledger from sold records or, with theinvoicesoption, from paid invoices, builds statements per period and pays them out, and exposescommission_payroll_linesfor payroll. It contributes acommission_periodkind to the periods block. Referrals keeps codes per member, attributes signups (and accepted invitations with theinvitationsoption) and posts a reward once to the ledger when a referral qualifies. -
pipelines,accountingandpermissionsdeclare their defaults.pipelinesdeclares the default pipeline and stage template of every record type without ascopeasseed_pipelines_defaults, with the named variantsb2b-sales(deals) andrecruiting(applications) that a binding picks throughon.<type>.variant;default_pipeline()keeps its name and signature and applies the declared defaults on first use, and scoped bindings are still created on first use.accountingdeclares its dimensions, thegenericchart (also the default) and a newnl-rgsDutch chart with its account roles and journals asseed_accounting_defaults;setup_accountingcalls it for an organization with no accounts. Thepermissionsdata step adds the catalog rolesowner,adminandmemberwhen the roles table lacks them.SeedTablegainsdefaultVariant, and a seed reference can match a null column. -
drive_transfer_ownership(drive.transferOwnership) no longer lets a member withdrive.managetake another member's items. A member hands over only their own items. Moving someone else's items, asdriveOffboardingSinkdoes when a member leaves, needs the service role. Before, a member withdrive.managecould transfer another member's private files to themselves and read them. -
Maintenance can run without pg_cron:
maintenanceTimerandmaintenanceTickinbetter-supabase/blocks/queuerunbetter_supabase.maintenance()from theblock_ticksqueue, and skip the run when pg_cron already has it.support(expired sessions),usage(idempotency keys and computed meters) andwebhooks-out(the delivery log) now register their cleanups with thehousekeepingmodule, which becomes a requirement of those three modules.leaverefuses a request that starts in aleave_yearperiod the periods block locked or closed, with the hintLEAVE_PERIOD_CLOSED.finance.reconcilematches an account's unmatched bank transactions to their best open invoice.doctorreports BS510 when the housekeeping module is installed and nothing schedulesmaintenance(). -
billingkeeps subscriptions in Postgres:billing_native_subscriptionsholds a plan, a price in minor units, a quantity and the period, independent of Stripe.create_native_subscription,prorate_changeandcancel_native_subscriptionare service-role functions, andcreateNativeSubscriptionsinbetter-supabase/blocks/billingcalls them.prorate_changereturns the credit, charge and net of a mid-period change and, with theledgerblock installed, posts the net as onebilling.prorationtransaction. Existing apps runbetter-supabase db diffto pick up the new table and functions. -
notificationsgets digests:notification_preferenceshas acadence(immediate,daily,weeklyoroff), a daily or weekly delivery is held, thedigest_runhousekeeping job folds held deliveries intonotification_digests, andcreateNotificationDigestssends each as one email through themail-syncmailer.set_notification_cadencesets the choice. Theconsentsblock addsrequires_consent(subject_type, subject_id, purpose_key)and aconsentscontribution key for system purposes.sequencesemail steps takeconsentPurposeandsendinnotificationstakesconsentPurpose; both skip a send while the subject has no consent. Existing apps runbetter-supabase db diffto pick up the new column, table and functions. -
accountingcan recognize revenue over time. Withoptions.recognition: true,schedule_revenue_recognitionsplits an amount over the months of a service period, books the deferral against the newdeferred_revenueaccount (2200in the generic chart) andlist_revenue_recognitionreads the rows. Therevenue_recognitionperiod kind posts each month's row when that month closes. The twoaccounting_recognition_*tables always exist, so existing apps runbetter-supabase db diffto pick them up. -
Named presets can start from seed variants, a Create design can carry seeds, and doctor checks them.
crmseeds theb2b-salesvariant ofpipelines,atstherecruitingvariant, anderpthegenericchart ofaccounting.expandPresetwrites them underdatabase.seed.defaults.variants, and the app's own variants and locale win.- Design format 9
seedstakessample: { size, seed }next tovariantsandlocale.init --presetandadd --presetwrite all of it to the config, andschemas/design-v1.jsondescribes it. - New doctor checks: BS354 (declared defaults that new organizations don't receive), BS355 (a configured variant the block doesn't declare) and BS356 (a generated sample file outside
database.seed.sample.output).
-
Three more blocks declare tenant default seeds, applied by
seed_tenant_defaults.inboxcreates a "Help" inbox on the in-app channel.attachmentscreates the document typescontract,invoice,receipt,identity,reportandother(the drive uses the same types).calendarcreates a "Public holidays" calendar for the localesnl,de,fr,en-gbanden-us, with an all-day event per holiday for the years 2026 to 2030, each with a stableuidso running the defaults again keeps existing events. Apply the new functions to an existing app withbetter-supabase db diff, then callseed_tenant_defaultsfor the organizations that should get them. -
The
organizationsblock now installs aseedsmodule withseed_tenant_defaults(tenant, variants, locale), which calls theseed_<block>_defaultsfunction of every installed block that declares rows, in install order.create_organizationcalls it for the new organization unlessdatabase.seed.defaultsisfalseor itsonCreateisfalse, and the configuredlocaleandvariantsbecome the function's defaults. Thedeveloper-apipreset now also installshousekeeping, which runs notification digests.
0.48.0 (2026-11-02)
-
better-supabase/presetnow exportsBLOCK_CATALOG: every block with its title, category, description, requirements, events and docs link, generated from the block manifests.better-supabase/testingaddstestRouteOptimizer, the conformance kit for aRouteOptimizer. The named presetscms,erp,manufacturing,care,qms,ismsandai-agentsnow includedam,payroll-export,periods,rfqs,e-prescribing,clinical-decision-support,lims,advisories,prompts,ai-evalsandai-guardrails. A preset only gains blocks, so an app that installed one before can add the new blocks withbetter-supabase add. -
Remove the deprecated aliases and options that were due, and share helpers that several modules had copied.
Removed or changed Use instead createOAuthServerand theOAuth*type aliasescreateOauthServerand theOauth*types fromblocks/oauth-servercreateRateLimit,rateLimitedandRateLimit*fromblocks/queuethe same names from better-supabase/rate-limitreceiveEInvoicesoptionsxmlParserandFromUblOptionspass readUbl: (xml) => fromUbl(xml, options)outbox legacyEventTypesand thecurrenttypeextensionthe event type <prefix>.<entity>.<verb>DbError.legacyHintDbError.hintSequenceEnrollmentEventDataEnrollmentEventDatafromblocks/enrollmentsworkItemChecklistBindingtaskChecklistBindingAssistantRunResult.toUIMessageStream,totalUsage,providerMetadatastream,usageandfinalStepNew exports:
dbErrorOfStatus(maps an HTTP status to aDbError). The SQL helpersha256Hexinsql/sharedis nowsha256HexSql. Themaintenanceblock callsbetter_supabase.rrule_occurrencesand dropsmaintenance_rule_starts; the migration20261102110000_maintenance_use_core_rrule.sqlapplies this. -
Messaging reads prune record conversations by the record table's own visible rows before the per-row
can_subjectcheck.- Messaging: a commented subject type whose
permissions.readnames the provider'srowsrenderssubject_id in (select s.<id>::text from <subject table> s)in the follows branch instead of letting every row reachcan_subject. The set is a superset of the rowscan_subjectcan pass, becausecan_subjectalready requires the record row to be visible under the same policy, so visibility does not change. It runs once per statement as a hashed subplan, so a conversation in another tenant no longer calls the provider's row function once per row. A commented type withoutrowskeepstrue. - Subjects and permissions:
can_subjectandcancarrycost 1000, so the planner keeps the set check ahead of them.
Run
better-supabase upgradeto rewrite the messaging module's policies and functions. - Messaging: a commented subject type whose
-
Every port an app plugs in now needs
apiVersion: 1. The prescription gateway, the clinical decision support engine and the funding claim format and channel used to accept a missingapiVersion; addapiVersion: 1to yours. All ports now share one check,portOf, so the error for a wrong version reads the same everywhere.
0.47.0 (2026-11-02)
-
The
accountingblock is now a general ledger. Accounts gainnormalSide,level, roll-ups throughparentId,defaultTaxCodeIdandactive. Periods can be locked withlockPeriod, and posting into one fails withACCOUNTING_PERIOD_LOCKED. Journals gain a contra and a bank account, entry lines gaintaxAmount, andcost_centerandcost_objectare built-in dimensions. Opening balances (saveOpeningBalances,postOpeningBalances) are carried forward bycloseFiscalYear. New reports arecolumnBalance,journalListingandperiodTrialBalance, and billable time gainswipValuation. Theimportsblock gets theaccounting_account,accounting_journal,accounting_entryandaccounting_opening_balancetargets, which may post into closed periods but never locked ones. The SQL functionssave_accounting_accountandsave_accounting_journaltake extra arguments, so runbetter-supabase upgradeto regenerate the module. -
The
accountingblock now books other blocks' documents in the same transaction. Invoices book on issue, payment, refund and void. Expense reports book on approval and reimbursement. Costed stock movements book at average cost, lease rent charges and payments book as they post, and gifts book when they post and reverse on refund. Entries post at once, or stay drafts with the newautoPost: falseoption.postSource(sourceType, sourceId)books a document by hand. Blocks declare their sources through the newaccountingcontribution kind. The generic chart maps a newexpenserole.taxReport(organizationId, since, until)sums posted tax per tax code and report box, withsalesTax,purchaseTaxandnetTax. TheTaxReportFormatport (apiVersion: 1, checked withtaxReportFormatOf) renders a report as a country's file, and none is bundled. Budgets (saveBudget,budget,budgets) hold amounts per account, period and dimensions, andbudgetVsActualcompares them with the posted amounts. Saving a budget recordsaccounting_budget.createdoraccounting_budget.updated. Apply the new migration withbetter-supabase upgrade. -
Add the
accountingblock (better-supabase/blocks/accounting): double-entry books in money beside the operational ledger. It has a chart of accounts with account roles, journals, fiscal years of monthly periods, draft entries that post when they balance and are numbered per journal and year (SAL-2026-00001), reversals, dimensions, exchange rates and tax codes, and the period and year-end close into retained earnings. It also has the trial balance, profit and loss, balance sheet and general ledger reports. The permissions areaccounting.read,accounting.write,accounting.post,accounting.closeandaccounting.manage. ADR 0136 explains the split fromledger. -
The new
acknowledgementsblock (better-supabase add acknowledgements,better-supabase/blocks/acknowledgements) records who confirmed they read which version of a record.assign(organizationId, record, { type, id }, { dueInDays })asks a user, a team or a role;mine(organizationId)lists what the caller still has to read;acknowledge(record, { versionId, signatureId })records the caller's acknowledgement of the current version and fails withACKNOWLEDGEMENT_VERSION_STALEwhen a newer one was published;status(record)andof(record, versionId)show who acknowledged and who is pending;notifyDue()reminds members once their acknowledgement is overdue.List the record types under
blocks.acknowledgements.on, each with itstableand an optionalversionColumnthat holds the record's current version; without it, the current version is the record's latest frozen version in theversionsblock. The block adds theacknowledgements.read,acknowledgements.manageandacknowledgements.acknowledgepermission keys (members getacknowledge), the eventsacknowledgement_assignment.created,acknowledgement_assignment.deleted,acknowledgement.createdandacknowledgement.reminded, and theacknowledgement-inboxUI recipe. An app on a permission catalog adds the three keys to its catalog. -
New
advisoriesblock (better-supabase/blocks/advisories) for software vendors: products and versions with CycloneDX SBOM import, vulnerabilities enriched hourly from OSV, EPSS and the CISA KEV catalog through the versionedVulnerabilityFeedport, OpenVEX statements, and CSAF 2.0 advisories with a/.well-known/csafhandler.testVulnerabilityFeedinbetter-supabase/testingchecks a feed. CVSS 3.x vectors are scored; 4.0 vectors are parsed but not scored. Runbetter-supabase upgradeto add the tables and theadvisories.*permissions. -
Agents can check out, be discovered and be called by other agents.
- New
agent-checkoutblock (better-supabase/blocks/agent-checkout): ACP and UCP checkout sessions over an orders cart with idempotency keys, AP2 mandates signed and verified withsigning-keys, and an x402paymentRequiredandwithPaymenthelper. The permission keys areagent-checkout.read,agent-checkout.writeandagent-checkout.manage. better-supabase/blocks/agentsserves an A2A 1.0 Agent Card (agentCard,agentCardResponse) and a JSON-RPC task endpoint (createA2AHandler) that maps A2A tasks to ai-chat runs.- New
better-supabase/webmcpsubpath:registerWebMcpToolsregisters the block actions a user may run as WebMCP tools, andmcpToolsOfoffers the same actions tocreateMcp. SPEC_PINSgainsacp,ucp,ap2,x402,a2aandwebmcp.
Run
better-supabase add agent-checkoutand generate a migration. - New
-
New
ai-evalsblock (better-supabase/blocks/ai-evals). It stores eval datasets and items, runs them against a prompt version and a model withcreateEvalJob, scores withexactMatch,jsonSchemaand an injectablellmJudge, compares two runs for regressions and exports a promptfoo config.items.addFromFeedbackcopies ratedai-chatreplies into a dataset. Newai-guardrailsblock (better-supabase/blocks/ai-guardrails) with per-agent input and output policies: prompt-injection heuristics, PII redaction, topic deny lists and a tool depth limit. It logs decisions as hashes, records theguardrail.blockedevent and offerscheckandguardrailMiddleware. Runbetter-supabase add ai-evals ai-guardrailsto install them. -
AI documents keep their versions in the
versionsblock, andai-filesnow requires it. Each version is aversionsrow withsubject_type = 'ai_document'and the text incontent.better-supabase upgrademoves the rows ofai_document_versionsand drops that table. An edit that leaves the text unchanged writes no version, a document keeps its latest 50 versions, and the versions functions and RLS keep document versions private to ai-files. Theblocks["ai-files"].tables.versionskey is removed.With the
tasksblock installed, incident postmortem action items are tasks.addPostmortemAction(postmortemId, { title, assigneeId, dueAt })creates one and links it in the newincident_postmortem_actionstable,removePostmortemAction(actionId)removes the link, and a postmortem'sactionslists the linked tasks.actionItemsis deprecated and is removed in 0.48; withtasks,savePostmortemrefuses it.codemod 0.47lists the lines that useactionItemsorai_document_versions. -
New
appraisalsblock (better-supabase/blocks/appraisals): review cycles with self, peer and manager reviews, calibration sessions, goals and sign-off.createCycleandopenCyclestart a cycle and create one appraisal per person, with a self review, a manager review and one review per peer.closeCycleends it once every appraisal is signed off.submitReviewtakes a rating from 1 to 5, comments and an optionalformssubmission id. Only the assigned reviewer submits, and a member reads only their own reviews.calibratemoves a reviewed rating with a reason and keeps the previous value.setGoalslinks goals from thegoalsblock.signOffsigns an appraisal off. With theapprovalsblock it files an approval and the appraisal waits asawaiting_signoff. Withenrollmentsand a cycleprogram, each stage marks a program step.- The permission keys are
appraisals.read,appraisals.reviewandappraisals.manage.
Add
appraisals: {}toblocks, runbetter-supabase add appraisalsand generate a migration. -
Appraisal cycles take a rubric of weighted competencies (
competencies,setCompetencies, per-competencyratingsandcalibrateCompetencies) and ananonymitymode (none,subjectorall, defaultsubject) that hides peer reviewers in function outputs and row-level security, plusshareFeedbackfor the appraised person after sign-off. Adopted appraisal tables gainanonymity,share_feedback,calibrated_competenciesandcompetency_ratingscolumns, and the block addsappraisal_competenciesandappraisal_review_ratings. With the default, a person who heldappraisals.readno longer sees who wrote a peer review about them. See ADR 0180. -
Approval steps with
required: "all"wait for each named approver, and managers can decide leave and expenses directly. Runbetter-supabase upgradeand generate a migration.- Approvals: a
required: "all"step completes only once each listed user, or a delegate acting for that user, has approved. Before, any approvals reaching the count completed it, so a delegate and the user who delegated counted twice. After the step escalates, the fallback approvers count toward the number again. Steps resolved from"all"keepall: truein the policy snapshot and inlistPolicies; a tenant can't set it on other steps. - Leave and expenses:
options.approver: "manager"lets the requester's manager from the employees block calldecide_leave_request,decide_expenseanddecide_expense_report(decide,decideExpenseanddecideExpenseReport), next to holders of the approve permission. The default stays"permission". - Leave: with
approvals: falseon the block's own tables, request reads no longer refer to the approval column, which the table doesn't have without the approvals block. - Time tracking: with
approvals: false,approve(id, { decidedBy })andreject(id, note, { decidedBy })let the service role record the user who decided (decided_byin SQL), never the week's owner.
- Approvals: a
-
Attachments carry per-organization document types with typed metadata, and files can be registered before they are uploaded (breaking).
attachments.documentTypes.define,listandremovemanage types such assupplier_invoicewith typed fields (text,number,amount,date,expiry,boolean,select). A bad value fails withATTACHMENT_FIELD_INVALID.- Attachments gain
documentTypeId,source,externalId,storageStatus(stored,pending_upload,missing) andsourcePath.(organization, source, externalId)is unique,sourcemust be inoptions.sourcesor belong to an import run, andsubjectTypemust be a registered subject type. - The
importsblock gets anattachmenttarget that registers the record first.claimandmarkMissingfinish it later. create_attachmenttakesdocument_type,source,external_idandsource_path; the old overloads are dropped. A table adopted fortables.attachmentsmaps the five new columns or sets them tonull.
See the 0.46 to 0.47 migration guide, "Attachment document types".
-
New subpath
better-supabase/audit-filesreads and writes audit files for the general ledger. A versionedAuditFileAdapter(apiVersion: 1) parses a file as a stream of ledger records and exports books, withsaftAdapter()for OECD SAF-T 2.00 andxafAdapter()for the Dutch XAF 3.2 (SPEC_PINS.saftOecd,SPEC_PINS.xaf).importAuditFile(adapter, file, { run, imports })writes accounts, journals, opening balances and entries through the accounting import targets, so a repeat changes nothing, andexportAuditFile(adapter, accounting, { organizationId, company, currency, selection })writes a fiscal year. Parsing uses a small built-in streaming tokenizer with limits and no XML dependency. Elements and links the ledger cannot store come back as warnings. -
Add
better-supabase automations list, which prints the automations the installed blocks ship, and--explain, which says which block's event starts each one and what its actions do. Field history now also watches columns that a block entity declares insubject.history, and theeventsandaudit-readstable tags write their SQL throughtable enable. -
Add the
bankingblock (better-supabase/blocks/banking): bank accounts, statements and transactions with reconciliation.parseCamt053reads camt.053.001.02 and .08 (with the optionalfast-xml-parserpeer) andparseMt940reads MT940. Importing a statement twice adds nothing.suggestMatchesranks open invoices by RF creditor reference (ISO 11649), Dutch betalingskenmerk, invoice number in the remittance, amount and counterparty IBAN, andmatchrecords the invoice payment. Bank rules match transactions by a filter tree and book them in the bank account's journal or ignore them, andreconciliationcompares the statement balance with the books. Bank feeds plug in through the versionedBankFeedport; none is bundled. The permissions arebanking.read,banking.import,banking.reconcileandbanking.manage. ADR 0153 explains the design. -
Build the automation action registry from the installed blocks with
blockActions(blocks, { clients })frombetter-supabase/blocks/automations. Manifests gain ahandlersfield,quotes.from_dealcreates a quote from a won deal as a default automation that ships off, and doctor reports BS507 when blocks ship actions and no source builds a registry. -
Block clients cover more of what apps wrote by hand:
webhooks-outmanages endpoints as the user withcreateEndpoint,updateEndpoint,listEndpointsanddeleteEndpoint, checked against the module's manage and view permissions. The block SQL addscreate_webhook_endpoint,update_webhook_endpoint,list_webhook_endpointsanddelete_webhook_endpoint(module version 6); runbetter-supabase upgrade.- Notifications
sendtakes{ email, name? }recipients for contacts without an account. The email channel sends to them right away throughsendToContact, with an optionalcomposeContact, and the result reports each contact incontacts. - Comments
listtakesincludeDeleted: falseto leave deleted comments out in the database.list_commentsgains aninclude_deletedargument (module version 9); the upgrade drops the old signature. viewOffrombetter-supabase/blocks/saved-viewsandsubscriptionOffrombetter-supabase/blocks/notificationsparse rows from a page payload RPC the way the clients do.
-
Two more block reads, each one SQL call that runs as the caller.
banking.reconciliationBoardreturns an account's status, its latest transactions and the best invoice suggestion for each unmatched one.orders.boardreturns the orders by status with counts, totals per currency and the latest orders of each status. Both appear in the generatedblocks.reads, the catalog and the example's migration. -
Read sets take block reads and record summaries.
defineReadSet(db, name, { blocks: reads }, ...)addss.blocks.<instance>.<read>(args)for the reads the installed blocks ship, ands.record(type, id, { sections })adds the record summary. Both run inside the singlers_<name>round trip, as the caller. -
Blocks can ship composed reads.
deals.board({ pipelineId })returns a pipeline's stages with their deals, counts, totals per currency and the weighted forecast in one call, from the newdeal_boardfunction.better-supabase genwritesreadsand a result type for each read intoblocks.generated.ts,defineReadSettakes them asblocks: reads, and the block catalog lists them. -
Two more block reads, each one SQL call that runs as the caller.
organizations.overviewreturns the organization, the caller's role, the members with their roles, the open invitations and the billed seats.billing.overviewreturns the Stripe customer, the seats, the subscription item, the latest invoices and the usage per meter.organizationsnow listsbillingandbillinglistsusageas integrations in the catalog. -
More composed reads and helpers.
sessions.overviewreturns the caller's sessions, their count and the current session id in one SQL call.inventory.overviewreturns the stock level count, the levels at or below their reorder point and the lots that expire soon.audit.pagereturns a page of entries with the total and anactorNameon each.quotes.duplicatestarts a new draft from a quote you hold, throughcreate. -
The calendar block takes
options.defaultAlarms: each calendar keeps the alarms a new event gets when its input sets noalarms, incalendar_default_alarms, with an anchor time of day for all-day events (default 09:00). The client reads and replaces them withdefaultAlarms(calendarId)andsetDefaultAlarms(calendarId, alarms).save_calendar_eventalso takes an optionalactor, andupsert(calendarId, input, { actor })passes it: a new event's creator and owner are that user, and only the service role may name a user other than the caller.The tasks block's
update(changes, { atomic: true })applies a batch in full or not at all, and awindowchange ({ startAt, endAt }) moves both dates in one write, so a Gantt drag past the old end no longer fails the date check halfway.update_taskstakesatomic boolean default false.In the keyed layout,
custom-fieldstakeson.<type>.keyswithmanageandread, the tenant keys that writing and reading that type's values ask for instead ofcustom_fields.manageandcustom_fields.read.Over an app's runs table, the workflows block's
principalKindandprincipalIdcolumns are optional as a pair. Without them the principal stays in the run'sattributes, andrun.principalreads it from there.Run
better-supabase upgradeand generate a migration to pick up the new SQL. -
bsb.bootstrap()tells a banned user from an ended session, the proxy hands refreshed cookies to the render, andSessionProvidercan skip the authorization refresh.- Bootstrap: the
bootstrap_<rpc>wrappers returnend_reason(user_bannedorsession_not_found) from the newbetter_supabase.session_end_reason(). The result carries it asendReason, the redirect uses?reason=user_bannedfor a banned user, andreasons: { ended, banned }sets other values, as inverifySession. Runbetter-supabase upgradeand generate a migration; a wrapper generated before reportssession_not_foundfor both. - Proxy: under
verifySession: "bootstrap", a session thatbsb.bootstrap()found ended has its cookies cleared on its next request in the same process. The proxy also copies itsset-cookieheaders intox-middleware-set-cookie, so the render after a refresh reads the new token instead of the old one. - React:
SessionProvidertakesauthzRefresh,falseor a test on the session, such as(session) => !supportOf(session)to keep a support session off the target user's topic.
- Bootstrap: the
-
blocks.sessions.options.bootstrapaccepts{ readSet: "name" }next to"schema.function". The generatedbootstrap_<name>wrapper then callspublic.rs_<name>, so one page load carries the session check, the authorization version and a whole read set in one query. -
The care blocks work offline on PowerSync.
powersync streamsandgen.powersync.instancesacceptactivities,observationsandmedications. They needauthorization: "roles": a user syncs the organizations where their role holds the block'sreadkey.better-supabase/powersyncaddsprogressNoteRoute,activityLinksRoute,observationRoute,medicationAdministrationRouteandcareUploadOutcome. Clinical conflicts (a dose already recorded, a locked note) land inconnector.rejected.
No migration is needed.
-
New
care-plansblock (better-supabase/blocks/care-plans): care plans for any client record, such as a customer, a resident or a member.- A plan belongs to one subject and holds problems (with a code from
options.codeSystems, such asomaha), goals with a target date and actions of kindintervention,appointment,taskormeasure. publishfreezes the draft as a version, makes it the client's active plan, archives the plan before it and starts its actions.createwithcopyFromPlanIddrafts the next plan from an earlier one.evaluaterecords what a goal reached; a new status becomes the goal's status. The dailyreviewsschedule runsdueReviews, which notifies the owner and emitscare_plan.review_date_reachedorcare_plan_action.review_date_reachedwhen a plan or an action comes up for review.- A restrictive measure (
kind: "measure", one ofoptions.measureKinds) waits for an approval before it starts, through the approvals block.requestAgreementasks the members who speak for the client to sign the active plan through the signatures block, which gains the signature meaningagreed. - Guests granted a client see its published plans. A task action can open a work item in the tasks block.
- The permission keys are
care_plans.read,care_plans.write,care_plans.evaluate,care_plans.publishandcare_plans.manage; the default member role reads plans.
Add
"care-plans": {}toblocks, runbetter-supabase add care-plansand generate a migration. - A plan belongs to one subject and holds problems (with a code from
-
Adds the
carepreset for home care, nursing homes, disability care and youth care. It installs contacts for clients and their representatives, guest access, encrypted fields, audit with read logging on the client, data lifecycle, consents, activities, care plans, observations with the vitals catalog, medications, forms, bookings, calendar, reminders, time tracking, funding, shifts, qualifications, courses, cases for incidents, staff incidents and complaints, acknowledgements, the drive with controlled documents released through approvals, and signatures. Missed doses open an incident, and tracked time registers funding deliveries. Install it withbetter-supabase add --preset care.A block entity that registers a subject now takes
teamandauditReads, the same settings as an app table subject, and a preset instance passes them undersubjects:blocks: { contacts: { entities: { person: { team: { actions: ["read", "write"] }, auditReads: true } }, }, },The settings are refused on an entity that registers no subject.
-
New
casesblock (better-supabase/blocks/cases): nonconformities, complaints, incidents and other cases per organization, from report to a verified close.- Each organization starts with eight kinds from
options.kinds(nonconformity, complaint, incident, near miss, observation, improvement, change request and audit finding). A kind sets the number prefix (NC-,CMP-) and what closing requires;saveKindadds your own. Each kind gets its own pipeline with the stages reported, investigating, acting, verifying, closed and canceled. openputs a case on its kind's first stage,movemoves it on the board,recordRootCauserecords the root cause andcreateActionorlinkActionadds containment, correction, corrective, preventive and improvement actions as work items of the tasks block.blockerslists what still stops a case from closing (CASE_ROOT_CAUSE_REQUIRED,CASE_ACTIONS_REQUIRED,CASE_ACTIONS_OPEN,CASE_EFFECTIVENESS_REQUIRED,CASE_DOCUMENTS_NOT_REVISED), andcloseor a move to a closing stage fails with the first one while any remains.- A kind with
effectivenessAfterDayssets the effectiveness check date after the last required action is done; the dailyeffectiveness-dueschedule runsnotifyDueEffectiveness, which notifies the owner and emitscase.effectiveness_date_reached. case_from_submissionis a forms submission handler, so a public form opens cases of the answers' kind oroptions.intakeKind.- The
medicationsblock's newmissedCaseKindoption opens a case of that kind for each missed dose. - The permission keys are
cases.read,cases.create,cases.write,cases.closeandcases.manage; the default member role reads and opens cases, and a case's owner may change and close it.
Add
cases: {}toblocks, runbetter-supabase add casesand generate a migration. - Each organization starts with eight kinds from
-
Connect
casesandinspectionsto the other blocks. A tenant policy for subjectcaseand actionclosenow blocks closing (CASE_APPROVAL_REQUIRED) until the request is approved, and closing a case writes a version. Inspections take acalendaroption that mirrors planned inspections as all-day events, sendinspection.assignedwhen someone joins the team, and report overdue inspections throughnotifyOverdue()and a dailyoverdueschedule. See ADR 0148. -
The preset catalog lists each block's automations, the generic blocks it contributes to and every port it provides, including
mailerandrecordAccess.better-supabase blocks view <block>prints Ports in, Ports out, Contributes, Fires and Listens lines. -
The
catalogblock now keeps product identifiers (EAN, supplier and manufacturer codes), relations between variants (alternative, superseded by, accessory), supplier items with a column mapping per supplier and keyword search, andpromoteSupplierItem, which creates a product from a supplier item on first use. Variants gainsetVariantTradeCodefor the CN code, andinventorylocations gainsetLocationAddress. The catalog contributessupplier_itemandproduct_identifierimport targets, so price lists and code lists load by external key. Existing installations get the new tables and columns frombetter-supabase upgrade; the new tables follow thecatalogmodule to version 5 andinventoryto version 4. -
Two versioned ports (
apiVersion: 1) with no bundled implementation.better-supabase/blocks/invoicesaddsEInvoiceFormat,EInvoiceChannelandsendEInvoice, which renders an issued invoice and sends it through your access point. Drafts and void invoices are refused withEINVOICE_NOT_ISSUED.better-supabase/blocks/accountingaddsAccountingChartFormatandimportChart, which saves a reference scheme's chart (such as RGS) parents first and maps its roles. An invalid chart saves nothing (ACCOUNTING_CHART_INVALID).
No migration is needed.
-
better-supabase add <composite>lists a composite block inblocksand writes the modules of all its parts.better-supabase remove <composite>replaces the composite with the blocks it was made of, andremove <composite> --with-partsremoves the parts too, except any part another installed block still needs. -
New
clinical-decision-supportblock (better-supabase/blocks/clinical-decision-support): alerts over a record's medication orders, with a versioned port for external engines.saveRulekeeps built-in rules: dose range, duplicate therapy and interaction.evaluateruns the built-in rules, then each engine passed asengines(aClinicalDecisionSupportwithapiVersion: 1), and stores the alerts.alertslists open alerts, anddecideacknowledges or overrides one with a reason. Every raise and decision is an event and an audit entry.testClinicalDecisionSupportinbetter-supabase/testingchecks an engine.- The permission keys are
clinical_decision_support.read,clinical_decision_support.writeandclinical_decision_support.manage.
Run
better-supabase add clinical-decision-supportand generate a migration. -
The
invoicesblock now collects.recordPartyPayment(organizationId, payment)splits one payment from a customer over several of its invoices and keeps the rest as party credit on the ledger,applyPartyCredit(partyId, invoiceId, amount)pays an invoice from it, andpartyCredits(organizationId, partyId)reads the credit per currency. Dunning levels (setDunningLevels,dunningLevels) set the reminder, fee and final notice for each number of days past due;runDunning()runs as the service role on the manifest's dailydunningschedule, adds the level's fee as a charge, notifies the invoice's creator and recordsinvoice.dunning_escalated.pauseDunning(invoiceId, until, reason?)holds the reminders during a dispute and needs the newinvoices.collectpermission. Invoices returndunning: { level, at, pausedUntil }. The docs add a recurring invoice recipe on template schedules.The new
better-supabase/e-invoicingsubpath writes an issued invoice or credit note as UBL 2.1 per EN 16931 and Peppol BIS Billing 3.0 (toUbl), reads a received one into purchase bill input (fromUbl, which loads the new optional peerfast-xml-parser), and defines theEInvoiceChannelport (apiVersion: 1, checked witheInvoiceChannelOf) for an access point. None is bundled. Apply the new migration withbetter-supabase upgrade. -
Compliance policy acknowledgements move onto the acknowledgements block (ADR 0131).
blocks.compliancenow requiresacknowledgements, contributes thecompliance_policyrecord type with its current version, and assigns a policy that requires acknowledgement to thememberrole when it is saved. The 0.46 to 0.47 guide lists every change.Before (0.46) After (0.47) acknowledge_compliance_policy(policy_id)acknowledge('compliance_policy', policy_id::text)list_compliance_policies(..., pending_only)list_my_acknowledgements(tenant)compliance_policy_acknowledgements(policy_id)acknowledgement_status,acknowledgements_ofpolicy_acknowledgementstableacknowledgementsrows of typecompliance_policycompliance.acknowledgepermissionacknowledgements.acknowledgepolicy.acknowledged,compliance_policy.acknowledgedeventsacknowledgement.createdCOMPLIANCE_POLICY_NOT_PUBLISHEDhintACKNOWLEDGEMENT_NO_VERSION,ACKNOWLEDGEMENT_NOT_ASSIGNEDupgraderenders a data step that copies the stored acknowledgements, assigns the live policies to thememberrole and dropspolicy_acknowledgements.PERMISSION_KEY_RENAMESandEVENT_TYPE_RENAMESmap the old permission and event;codemod 0.47lists the old calls for review.- The compliance client keeps
acknowledgePolicy,acknowledgements(policyId)and thependingOnlyoption as deprecated wrappers over the acknowledgements functions until 0.48.
-
Nineteen composite blocks are available from
better-supabase/blocks/<name>:saas,sales,crm,commerce,procurement,finance,support,projects,service,people,recruiting,scheduling,learning,events,cms,care,filespace,collaborationandgovernance. Each lists the blocks it is made of, carries their defaults, and adds helpers where a flow spans parts (crm.closeWon,finance.closePeriod,filespace.put,recruiting.hire).crmalso declares a named read set. The named presets now list composites, and each resolves to the same set of modules as before, except thathelpdeskalso installs the Chat SDK state tables. -
defineBlocktakescomposesanddefaultsto build a block from other blocks.createBlockshands the composite its parts' clients asoptions.parts,resolvePresetinstalls the parts with the reasonpart of <composite>and returnspartOptions,removeCompositeremoves a composite with or without its parts, and the catalog listscomposes,defaultsandcomposedBy. -
collaborationgainsdiscuss, which posts a comment on a record and attaches tags to it, andschedulinggainsbookWithReminder, which confirms a booking and sets the caller's reminder on it. Each stops at the first failed step and returns that error. -
better-supabase gennow writes ablockConfigentry for a composite block that has no SQL module of its own once all of its parts are installed, and leaves it out while a part is missing. The entry has the schema of its first part and no options. The "Composite blocks" page shows how to build a composite next to its parts withcreateBlocks. -
Add glue helpers to the remaining composites:
blocks.saas.inviteWithinSeats,blocks.commerce.payAndFulfil,blocks.support.openTicket,blocks.projects.approveAndInvoice,blocks.service.completeVisit,blocks.people.onboardandoffboard,blocks.learning.assign,blocks.events.sellTicket,blocks.cms.publishWithVersion,blocks.care.prescribeWithConsentandblocks.governance.exportSubject. Each chains existing part clients, takes one object and returns aResult. -
Commerce and finance blocks gain helpers that replace chains of calls, each taking one object and returning a Result. New:
pipelines.defaultandpipelines.ensure,quotes.draftFromDeal,orders.markPaid,orders.returnAndRefundandorders.fulfilAll,invoices.createAndIssue,invoices.markPaidandinvoices.issueAndSend,banking.reviewQueueandbanking.acceptBestMatch,catalog.createSimpleProduct,shipments.shipCheapest,rfqs.awardBest,accounting.initializeandaccounting.yearToDate,expenses.fileandpromotions.createWithCode. -
Platform blocks gain helpers that replace calls to several methods or raw
$apiand$rpc, each taking one object and returning a Result. New: asessionsclient (listMine,end,endOthers),profiles.setAvatarwith theavatarUploaderandavatarColumnoptions,flags.isEnabledandflags.tenantsWith,webhooks.createEndpoint({ withSecret })andwebhooks.setEnabled,organizations.ownerandorganizations.memberRoles(with theownerRoleoption),teams.setMembersandteams.setArchived,entitlements.seatsLeft, the onboarding step optioncompleteOn,audit.correlated,dataLifecycle.exportNowandbilling.startTrial. Runbetter-supabase upgradeto regenerate the onboarding module. -
Add helpers that compose existing calls:
passes.scan,leave.workingDays,attachments.uploadFile,comments.createWithFiles,reactions.who,templates.variablesandtemplates.preview,imports.run, andmove(id, toIndex)on tags, custom field definitions and saved views. -
Add
approvals.requestAndWait,inbox.inboxes.setup,timeTracking.logOn,switchToandsubmitAndRequest, andtasks.create({ custom }). Thecustom-fieldsblock now provides acustomFieldsport thattasksconsumes. -
Add
enrollments.pauseandenrollments.resume, backed by the newpause_enrollmentandresume_enrollmentSQL functions. Runbetter-supabase upgradeand apply the migration. -
Add the
consentsblock (better-supabase/blocks/consents): consent per record and purpose. An organization saves the purposes it asks consent for withdb.consents.savePurpose, each with a lawful basis, a version, an optional signature requirement and a validity in months; the service role saves system purposes every organization uses.recordstores a granted or refused decision for any subject with who made it (the person or a representative contact), its scope and a signature, form submission or attachment as evidence, and replaces the grant before it.isActive(subject, purposeKey)answers whether processing may go ahead on the current purpose version,listreturns the latest decision per purpose or the full history,withdrawends a grant, and the dailyconsents.expiretimer marks grants past their valid-until date expired.The permissions are
consents.read,consents.recordandconsents.manage; members get none of them by default. A guest records and withdraws their own consent, and a guest whose person represents the record withactauthority does so as a representative. The block writesconsent.granted,consent.refused,consent.withdrawn,consent.expired,consent_purpose.createdandconsent_purpose.updatedto the outbox, and ships theconsent-registerUI recipe. -
New
damblock (better-supabase/blocks/dam): renditions of drive files and usage rights with a territory, a channel and an expiry date.renderRenditionsmakes the kinds you configure through the drive'sPreviewRendererport, stores the page and records the rendition. A renderer that throws leaves afailedrendition and the other kinds go on.recordRenditionandlistRenditionswork with renditions your own job makes.grantRight,revokeRightandlistRightskeep usage rights. A right without a territory or channel covers all of them, and a revoked right stays in the history.checkUsageanswers whether a file may be used on a day in a territory and channel.notifyExpiringnotifies the member who granted each right that ends soon, once per expiry date.- The permission keys are
dam.readanddam.write.
Run
better-supabase add damand generate a migration. CallnotifyExpiringon a schedule. -
createDataImporterinbetter-supabase/blocks/data-lifecyclerestores an organization export. It reads the NDJSON-per-table files, checks table and column names againstdata_lifecycle_tables(), and writes each row through theimportsrecord map in import mode withsource = 'restore', so a second restore of the same files writes nothing.dryRunreturns a per-table report with unknown tables, unknown columns, row counts and conflicts. CSV exports are refused with a typed error because they are lossy. Thedata-lifecyclemodule addsdata_restore_tablesandrestore_data_rowand registers thedata_lifecycle_rowimport target. Runbetter-supabase upgradeand apply the new migrations. -
Modules declare their links to other modules' entities (
names.links): references, relations and conversions such as a quote created from a deal or an invoice from an order. Every conversion records itscreated_fromlink through one helper.resolvePresetaddsrelationswhen a selected pair declares a conversion, and thecrm,helpdesk,erp,manufacturing,marketplace,people,psa,ats,invoicingandfield-servicepresets install it.better-supabase blocks viewprints a Links line, and doctor reports BS353 when installed modules declare a link andrelationsis missing. -
Modules can declare tenant defaults in
BlockSql.seeds, which render into an idempotentseed_<module>_defaultsfunction.db seed --defaultsruns those functions for existing organizations (--tenant,--variant,--locale), anddb seed --sampleapplies generated sample data from the Better Supabase cloud (--demo-org,--size,--seed,--out; needs a Pro plan). The newlogin,logoutandwhoamicommands manage the cloud login.database.seedgainsdefaultsandsamplekeys, andbetter-supabase/sqlexportsseedDefaultsFunctions.The CLI refreshes an expired login through
POST /api/cli/auth/refreshand saves the rotated tokens, sowhoamianddb seed --samplekeep working past the access token's lifetime. -
Development shows how many sequential database round trips a page waits on.
createNexttakesdevRoundTripBudget(default 4,falseturns it off) and warns when a render goes over it, naming read sets as the fix. The OpenTelemetry plugin setsbetter_supabase.db.round_tripson each database span, andbetter-supabase doctorreports BS609 for three or more database reads in onePromise.all. -
The
catalogblock now keeps discount groups for customers and products and a matrix of rules between them, with a validity window, a quantity break, a discount in basis points and an optional fixed price.resolveLineDiscountreturns the most specific rule for a customer, variant, quantity and date. The newoptions.discountMatrixofquotes,ordersandinvoicesprices catalog lines through it; it is off by default, so existing documents price as before. Theinventoryblock gains stock count documents (openStockCount,recordCountLine,postStockCount,cancelStockCount) that post adjustment movements once, andshipmentsgainsintrastat_lineswithprepareIntrastat, which derives arrival and dispatch lines and lists the ones that miss a trade code, country, net mass or value. The catalog and inventory contributediscount_group,discount_ruleandstock_countimport targets. Existing installations get the new tables frombetter-supabase upgrade;catalogmoves to version 6,inventoryto 5 andshipmentsto 3. -
Doctor can accept the findings an existing project already has. Set
tooling.doctor.baselineto a JSON file of{ code, target, reason }entries and rundoctor --update-baselineto write it. Doctor then leaves those findings out and fails on an entry no finding matches, so the file only shrinks.BS351 also reports writes through the typed client's repositories, such as
db.webhookEndpoints.create(), on a table a block creates. The block clients (db.webhooksOut) are not reported.At the root of a pnpm or npm workspace, the default
tooling.doctor.sourcesnow also scanssrc/**/*.{ts,tsx}in each package, so doctor sees the code ofapps/weband the other workspace packages. Asourcesyou set is used as it is. -
New
document-templatesblock (better-supabase/blocks/document-templates): templates per legal entity and language for invoices, credit notes, quotes, orders, dunning letters, delivery notes and statements, with reusable text blocks and a snapshot that keeps an issued document stable.saveTemplate,setTemplateActive,getTemplateandlistTemplateskeep one template per document type, name, legal entity and language. A body that names an unknown variable or filter, or leaves a block open, fails with the hintDOCUMENT_TEMPLATE_UNKNOWN_VARIABLE,DOCUMENT_TEMPLATE_UNKNOWN_FILTERorDOCUMENT_TEMPLATE_SYNTAX.saveTextBlockandlistTextBlockskeep texts a template reads as{{texts.key}}.resolveTemplatepicks the entity and language, the entity, the organization and language, then the organization, likeresolve_setting.renderreturns the typed variables of a document with the chosen template and text blocks, in the buyer's language unless you pass one.renderHtmlandrenderDocumentHtmlrender to HTML in pure TypeScript with every value escaped.- Issuing an invoice or credit note freezes its render in
rendered_documents;freezedoes the same for other documents, andfresh: truerenders with today's templates. contractanddocumentContractpublish the variable contract (version 1). Templates and text blocks are import targets (document_template,document_text_block).- The permission keys are
document_templates.readanddocument_templates.manage; members getread.
Add
"document-templates": {}toblocks, runbetter-supabase add document-templatesand generate a migration. The block needslegal-entities. -
Domain helpers over open standards, all TypeScript with no new table or dependency.
coursesgainsverifyLtiLaunch(LTI 1.3),xapiStatementandsendXapiStatements(xAPI 2.0) andopenBadgeCredential(Open Badges 3.0, unsigned).better-supabase/fhirgainscreateSmartLaunchandcreateCdsHooksServer.bankinggainsberlinGroupFeed,damgainsreadC2paManifestanddamUsageRightsToOdrl,contentgainssitemapXml,robotsTxtandarticleJsonLd, andmaintenancegainscreateTelemetryHandler.SPEC_PINSaddslti,xapi,openBadges,smartAppLaunch,cdsHooks,berlinGroupXs2a,c2pa,odrl,sitemaps,rfc9309andjsonLd. -
Drive nodes take access requests. With
driveSubject({ accessRequests: true })and the access-requests block installed,drive.requestAccess(nodeId, { action, reason, duration })asks for access anddrive.accessRequests(nodeId)lists the requests. The node's owners approve, and an approved request becomes a node grant that ends with the request. The access-requests client gainsrecords(subjectType, subjectId), and reaches the drive through the newrecordAccessport.drive.transferOwnership(organizationId, fromUserId, toUserId)hands a member's owned items to another member and recordsdrive.node_ownership_transferredanddrive.ownership_transferred.driveOffboardingSinkruns it from the outbox when a member leaves.With the settings block installed, the
drive.sharingorganization setting (driveSettings) turns guest grants off and limits share links toorganizationornone, failing withDRIVE_SHARING_DISABLED. Apply the new migration withbetter-supabase upgrade. -
Drive files can be controlled documents with a number, a type, an owner, a release workflow and periodic reviews.
blocks.drive.options.control: { types, reviewMonths?, releaseRole? }turns it on. It needs thenumbering,versions,approvalsandstate-machineblocks, and an approvals policy for thereleaseaction ondrive_node.- The drive client gains
saveDocument,submitDocument,releaseDocument,obsoleteDocument,reviewDocument,documents(the register, withtype,status,ownerId,reviewDueandsearchfilters) andnotifyDueReviews. Each node carriesdocumentwith its number, status, effective version and next review date. - A document moves from
draftthroughin_reviewtoeffectivewhen its release request is approved, and toobsoletewhen withdrawn. Members below the write role download and read only the effective version, and the storage policy refuses the working copy for them. - With acknowledgements on
drive_node, each release asks the assigned members to acknowledge the new version. With relations, documents link through thevariant_ofkind. - New events:
drive.node_document_saved,drive.node_submitted,drive.node_released,drive.node_obsoleted,drive.node_reviewedanddrive.node_review_requested. - The
document-registerrecipe shows the register in a ReUI data grid. Runbetter-supabase upgradeand generate a migration after settingcontrol.
-
Controlled document types in
blocks.drive.options.control.typescan set a number format with{ name, numberFormat }, such asSOP-{n:4}. A type with a format counts from its own sequence, and the other types keep the sharedDOC-{n:5}sequence. Apply the new migration withbetter-supabase upgrade. -
New drive helpers:
drive.folder,drive.can,drive.search,drive.put,drive.shareManyanddrive.grantsWithNames. They use the new SQL functionsdrive_node_accessanddrive_search. Runbetter-supabase upgradeand apply the migration to get them. -
The
driveblock gets retention per label and a changes feed.sweepRetention(service role) moves nodes into the bin when a label on them has a data lifecycle policy of kinddrive_label_<name>and the node was last changed longer ago than the policy keeps it. Drive holds, legal holds and check-outs skip a node.changes(organizationId, { cursor })returns the nodes that changed after a cursor, oldest first, with binned nodes asremoved, for sync clients.- Moving a node into the bin or back now updates its
updated_at.
Run
better-supabase upgradeand generate a migration. -
Drive sync skips unchanged nodes and can mark missing ones instead of deleting them.
- With the
importsblock installed,drive_sync_batchrecords each mirrored node inimport_records(source = 'drive:<connection>',entity = 'drive_node') with a content hash. A node whose hash is unchanged is not written, and the function returns the number of nodes it wrote. The signature is unchanged. Without the imports block it behaves as before. blocks.drive.options.sync.pruneis'delete'(the default, today's behavior) or'mark', which keeps unlisted nodes and setsmissing_sinceon their record. Legal holds keep their node in both modes.'mark'needs the imports block.- Run
better-supabase upgradeto refresh the function.
- With the
-
Drive files are searchable by their content and can be capped by a usage quota.
createDriveText({ transport, storage, extractor, knowledge? })frombetter-supabase/blocks/drivereads each clean upload through aTextExtractorand stores its text in the newdrive_node_textstable, which follows the node's read grants. Run itssink()on the outbox relay. With a knowledge client, the text also becomes a knowledge document scoped to the node.plainTextExtractor()reads text, JSON, XML and YAML;textExtractorOfandtestTextExtractor(frombetter-supabase/testing) check your own extractor.driveSubject()indexes a node's name and the first 100,000 characters of its text through thedrive_node_searchview.blocks.drive.options.quota: { meter }makesdrive_create_fileanddrive_upload_revisioncheckwithin_quotafor the upload's size and fail withDRIVE_QUOTA_EXCEEDED. It needs theusageblock.maxTextBytes(default 1 MB) caps the text kept per file.- The drive and drive-files modules are version 2. Run
better-supabase upgradeand generate a migration.
-
better-supabase/blocks/driveexportscreateWopiHost, a WOPI host for drive files:CheckFileInfo,GetFile,PutFileand the lock calls run on the check-out lock, behind signed access tokens. -
New
e-prescribingblock (better-supabase/blocks/e-prescribing): prescriptions of medication orders with the states draft, signed, sent, dispensed and cancelled, signed only by their prescriber, and delivered through the versionedPrescriptionGatewayport.toFhirPrescriptioninbetter-supabase/fhirbuilds theMedicationRequest, andtestPrescriptionGatewayinbetter-supabase/testingchecks a gateway. Runbetter-supabase upgradeto add theprescriptionstable and itse_prescribing.*permissions. -
Employees and hiring take the options an HR app needs for safe edits and its own application columns.
- Employees:
options.contractOverlap: "deny"keeps the previous contract as it is and failsaddContractandupdateContractwithEMPLOYEE_CONTRACT_OVERLAPwhen the dates overlap another contract. - Employees:
update(changes, { atomic: true })applies a batch as one unit, and a change withexpectedUpdatedAtfails withEMPLOYEE_STALEwhen the employee changed since. Employees now returnupdatedAt. - Employees:
delete(employeeId)(delete_employeein SQL) removes an employee created by mistake, moves the reports, recordsemployee.deletedand fails withEMPLOYEE_IN_USEwhile other rows point at it. It runs thebefore_employee_deleteandafter_employee_deletehooks. - Employees:
options.offboarding: { reports: "keep" }leaves the reports with an offboarded employee instead of moving them to the manager. - Hiring:
options.applicationExtraColumnsadds columns to the applications table.applywrites them fromfields, and applications return them underfields.
- Employees:
-
The composite blocks gain helpers that chain their parts.
crmaddsroute, which picks an owner from the assignment queues using the record's segments, andattainment, which sums target progress per metric and lists the targets behind the period's pace.saasaddsrotateApiKeywith a grace period in hours, andbetter-supabase/blocks/saasexportscreateKeyRotatorfor apps that do not install every part.supportaddsescalate,commerceaddsprocessReturnwith restock, quarantine and reject dispositions and an optional refund, andprojectsaddsutilization,financialsandretainerDrawdown. -
Block entity keys equal the entity's singular, and the subject types, hint codes and functions follow the new nouns (ADR 0130). Run
better-supabase codemod 0.47; the 0.46 to 0.47 guide lists every rename. Old entity keys and subject types keep working until 0.48, with a warning, and doctor reports them (BS423).Before (0.46) After (0.47) blocks.tasks.entities.work_itemblocks.tasks.entities.taskblocks.activities.entities.engagementblocks.activities.entities.activityblocks.automations.entities.ruleblocks.automations.entities.automationblocks.goals.entities.targetblocks.goals.entities.goalblocks.compliance.entities.policyblocks.compliance.entities.compliance_policyblocks.contracts.entities.obligationblocks.contracts.entities.contract_obligationblocks.incidents.entities.postmortemblocks.incidents.entities.incident_postmortemblocks.custom-fields.entities.fieldblocks.custom-fields.entities.field_definitiongeneric keys ( request,entry,document,policy)the block noun first ( leave_request,knowledge_document)subject types work_item,engagement,policytask,activity,compliance_policyWORK_ITEM_*,ENGAGEMENT_*,RULE_*,TARGET_*TASK_*,ACTIVITY_*,AUTOMATION_*,GOAL_*POLICY_*,OBLIGATION_*,POSTMORTEM_*,HIRING_JOB_*COMPLIANCE_POLICY_*,CONTRACT_OBLIGATION_*,INCIDENT_POSTMORTEM_*,JOB_OPENING_*timeline ACTIVITY_FORBIDDENTIMELINE_ENTRY_FORBIDDENcreate_work_item,log_engagement,save_targetcreate_task,log_activity,save_goalpublish_policy,save_obligation,save_postmortempublish_compliance_policy,save_contract_obligation,save_incident_postmortemworkItemChecklistBindingtaskChecklistBindingENTITY_KEY_RENAMES,SUBJECT_TYPE_RENAMES,HINT_RENAMESandlegacyHintOfare exported for code that maps stored names.upgraderenders a data step in the tasks, activities and compliance modules that moves stored subject types to the new ones in every installed subject type column. The subject functions accept the old types until 0.48.- A
@bsb subjecttag that declares a type an installed block registers now fails with an error naming the table, instead of being skipped. An app whose own table is thetasksubject keeps the block onnames: { task: "work_item" }. - The tasks block's events are
task.*(see the event type changeset), and its tables aretasks,task_assigneesandtask_checklist_items(see the module table changeset). An install that renames the entity keeps its own names.
-
With the legal entities block and
options.onlistinginvoices,quotesororders, their numbers are now unique per legal entity, so two entities can both holdINV-0001. An issued invoice's header total now includes the payment-term credit restriction, as its tax lines do. -
The
erpandmanufacturingpresets now installlegal-entities,tax,imports,custom-fields,attachmentsanddocument-templates, so an ERP or bookkeeping migration has its import runs, tax codes and numbering from the firstbetter-supabase upgrade. Generate a migration after it. The new "ERP and bookkeeping imports" concept page walks the flow. -
The
erppreset now installsaccounting,bankingandapprovals, so sales invoices, purchase bills, payments, stock movements, expense reports and depreciation book into the journals, bank statements reconcile against the ledger, and purchase requisitions go through approvals. Each organization runsdb.accounting.setup(organizationId)once before anything books. A project onpreset: "erp"gets the new blocks on its nextbetter-supabase upgrade; generate a migration after it.Add the
manufacturingpreset:erpplusmanufacturing,inspections,casesandqualifications. It setspurchaseSuggestions: "requisition"on manufacturing, so material requirements raise purchase requisitions, andreceiptInspection: "inspection"on inventory, so every receipt of a purchase order schedules an incoming inspection.init --preset manufacturingandadd --preset manufacturingaccept it, and both presets have a docs page that describes the postings, the three-way match and the bank reconciliation. -
Event types now follow one convention:
<entity>.<past verb>, where the prefix is the entity the event is about. Eachsavedevent is nowcreatedorupdated, depending on whether the save inserted the row, andparty.enrichediscompany.enrichedorperson.enriched, depending on the record. Runbetter-supabase codemod 0.47to rename the types in your code, config and SQL; it lists the split types, such asagent.saved, for review.Old New work_item.*task.*engagement.*activity.*rule.*,rule.removedautomation.*,automation.deletedaccess.requested,access.request_approved,access.endedaccess_request.requested,access_request.approved,access_request.endedcustom_field.*field_definition.*drive.node_*drive_node.*forecast.snapshottedforecast_snapshot.createdjob.*(hiring)job_opening.*leave.adjustedleave_balance.adjustedthe other leave.*eventsleave_request.*obligation.*contract_obligation.*organization.domain_added,_removed,_updated,_verifiedsso_domain.created,.deleted,.updated,.verifiedpolicy.*(compliance)compliance_policy.*postmortem.*incident_postmortem.*signature.*signature_request.*support.*support_session.*time.invoicedtime_entry.invoicedvariant.*product_variant.*waitlist.*waitlist_entry.*webhook.*webhook_endpoint.*workflow.publishedworkflow_definition.publishedsegment.removed,hostname.removed,approval_policy.removedsegment.deleted,hostname.deleted,approval_policy.deletedmarketplace_installation.removedmarketplace_installation.deletedcredential.set,ai_tool_policy.setcredential.updated,ai_tool_policy.updatedflag.override_set,hostname.primary_set,incoming_webhook.enabled_setflag.override_changed,hostname.primary_changed,incoming_webhook.enabled_changedmarketplace_invoice.state_changedmarketplace_invoice.status_changed<entity>.saved,marketplace_installation.upserted<entity>.createdor<entity>.updatedparty.enrichedcompany.enrichedorperson.enrichedAn install that renames an entity names its events after the new name, as before: with
blocks.tasks.entities.task.nameset toticket,work_item.createdstaysticket.created.The
sla.*events keep their names: they are about a record's SLA clock, and neither an SLA policy nor a breach table fits them. Relation events such ascollection.entry_removedkeepremoved,field_value.setkeepsset, and notification types don't change.The outbox stores the new types.
upgraderenders a data step that renames the stored types in the outbox events and dead letters, automation triggers and timeline entries, and adds the new types to the type lists of outbox consumers and webhook endpoints while keeping the old ones. The automations rule sink also tests a rule whose trigger is a split type, such asrule.saved, against the events it became. The outbox optionlegacyEventTypes(deprecated, off by default) relays a renamed type under its old name for receivers outside the app, with the new name in thecurrenttypeCloudEvents extension, which the library's sinks read through the neweventTypeOf(better-supabase/events). Doctor reports old types in the app's code (BS424), and BS422 no longer reportsactivity.*, which is now an event pattern.EVENT_TYPE_RENAMES,EVENT_TYPE_SPLITS,isOldEventType,currentEventTypesandlegacyEventType(better-supabase) export the maps. -
The new
better-supabase/fhirsubpath maps the care blocks to base HL7 FHIR R4 (4.0.1) resources.toFhirPatient,toFhirRelatedPerson,toFhirCarePlan,toFhirGoal,toFhirObservation,toFhirMedicationRequest,toFhirMedicationAdministrationandtoFhirConsenteach turn a block row into one resource, andtoFhirBundlewraps them in acollection,searchset,transactionorbatchBundle.fromFhirObservationandfromFhirMedicationRequestread untrusted FHIR JSON into an item fordb.observations.ingestor an order fordb.medications.importOrders, and return avalidationerror with every issue instead of throwing. The functions are pure, with structural types and no FHIR package, and run on every WinterTC runtime.SPEC_PINS.fhirR4pins the version. National profiles are left to a profile layer on top of the base resources. -
Custom field definitions now name a registered subject type.
save_field_definitionfails withFIELD_ENTITY_UNKNOWNfor an entity that is not a key ofconfig.subjectsor a type an installed block registers, andblocks.custom-fields.options.entityMaprenames the entities you stored before. Add field packs withdefineFieldPack, thepacksoption andinstall_field_pack, which installs definitions idempotently by pack and key. With thelegal-entitiesblock,field_valuesgains a nullablelegal_entity_id, andreadValuesandsetValuetake{ legalEntity }. Theimportsblock gets afield_valuetarget, andtestFieldPackchecks a pack. Runbetter-supabase upgrade, map old entities inentityMapand apply the new migrations. -
Assets now carry a book value.
updateAssetsetsacquisitionCost,acquiredOn,usefulLifeMonths,residualValue,depreciationMethod(none,straight_lineordeclining_balance) anddepreciationRateBps.runDepreciation({ organizationId?, until? })books each month once into the newasset_depreciationstable (service role only, so run it from a cron route),depreciations(assetId)lists the months, anddispose(assetId, { on, proceeds? })retires an asset and records its disposal. Withaccountinginstalled, depreciation posts through thedepreciation_expenseandaccumulated_depreciationroles and a disposal posts the gain or loss through the newdisposal_gainanddisposal_lossroles, which fall back to the suspense account until an organization maps them. Depreciating and disposing recordasset.depreciatedandasset.disposed.Projects get costing.
saveProjecttakes abudget(Money) andbudgetHours, and withaccountinginstalled each project becomes a value of theprojectdimension on its next save. Billable-time rates take a cost:setRateacceptscost, so the SQLset_time_ratefunction has a newcost_amountargument and its old signature is dropped.projectCosts(projectId)sums the time logged on the project's work items at cost and as billed, the accounting lines on the project dimension, the margin and the share of the budget used. Apply the new migration withbetter-supabase upgrade. -
The foreign key columns that point at a task or an activity are renamed:
work_item_idistask_idintask_checklist_itemsandtask_assignees, andengagement_idisactivity_idinengagement_subjects,engagement_recordings,engagement_notesandmail_threads.better-supabase upgraderenames them in the block tables, and a column of an entity you renamed or an adopted table keeps its name. Rename the columns in your own SQL, views and policies;codemod 0.47lists the lines that use the old names. -
New
fundingblock (better-supabase/blocks/funding): funding products with a rate per unit, awards that grant a record units per period from a funder, deliveries registered against them, and claims a funder answers line by line.saveProductkeeps the products a funder pays for, each with a unit and a rate asMoney.createAward,updateAwardandendAwardrecord the units a funder (a contacts party with thefunderrole) awards a record inconfig.subjects, per week, per month or in total;usagereturns the units used against the units awarded for each period.registerDeliveryrecords care or service delivered on an active award.registerFromTime(service role) registers the approved time entries of the period on the record's one active award and returns the entries it couldn't match.approveDeliveriesapproves registered deliveries or rejects them.buildClaimcollects a funder's approved deliveries of a period into a draft claim, numbered through numbering when it is installed.sendrenders it with aFundingClaimFormatand sends it through aFundingClaimChannel(bothapiVersion: 1; no format or channel is bundled);markSentrecords a claim sent another way.pollandrecordResponserecord the funder's answer per line, and a rejected line puts its deliveries back toapprovedfor a later claim.invoiceClaimcreates an invoice to the funder when invoices is installed.- Usage above an award records the
funding_award.exceededevent and notifies the members who manage funding. better-supabase/testinggainstestFundingClaimFormatandtestFundingClaimChannelto check a format or channel.- The permission keys are
funding.read,funding.write,funding.register,funding.approve,funding.claimandfunding.manage; members getreadandregister.
Add
funding: {}toblocks, runbetter-supabase add fundingand generate a migration. -
New block client helpers for content and records:
tags.replace,customFields.setMany,comments.replyandreopen,reactions.toggle,relations.walk,shareLinks.rotateandversions.restoreSafely. Each one calls the hooked client, sohookssee every step. -
New block client helpers for people and scheduling:
leave.approve,rejectandpending,shifts.rollout,fillandapproveSwap,qualifications.check,consents.require,courses.createFromOutlineandpublish,medications.prescribeAndPlan,funding.awardsWithUsage,carePlans.createTree,bookings.bookandbookings.public.book. Each one calls the hooked client, sohookssee every step. -
New block client helpers:
entitlements.requireandentitlements.all,usage.canConsume,deals.moveStageandtasks.move. Each one calls the hooked client, sohookssee every step. -
New block client helpers for work and support:
tasks.complete,cancelandreopen,approvals.decideForSubjectandguarded,cases.tryClose,incidents.resolve,meetings.conclude,enrollments.restartandadvance,inbox.conversations.replyandtakeOver,rank.betweenandautomations.installDefaults. Each one calls the hooked client, sohookssee every step. -
New reads:
hiring.jobs,hiring.applications,hiring.pipelineandhiring.close, andbookings.resourcesandbookings.services. They come from the new SQL functionslist_jobs,list_applications,list_booking_resourcesandlist_booking_services, which run as the caller. Runbetter-supabase upgradeand apply the migration to get them. -
Import runs now write in an import mode.
import_upsert_batchbegins an import session for its batch, andbetter_supabase.begin_import_session(run)does it for a transaction you control (service role only, on a running run).better_supabase.import_run()returns the run id inside a session and only to the service role, so a user session can't turn the mode on.In the mode the outbox applies
blocks.imports.options.events(an event type ordefaulttoskip,tagoremit, skipping what is not listed), the audit log tags entries asintegrationwith the correlation idimport:<run>andoptions.audit: "summary"writes one entry per entity instead of one per row, and a state machine accepts any declared status on insert with oneimportedhistory row and no event. Notifications, accounting auto-posting and the stock taken for paid orders and shipped shipments are not run. SQL modules read the condition withctx.importing().An existing app changes behavior only inside an import run. Apply the new migration with
better-supabase upgrade. -
Imports keep an external record map, so a rerun inserts new keys, skips unchanged ones, updates changed ones and leaves a row a user edited alone. This is a breaking change to the import run table and its client.
import_runs.kindis nowsource, and a run has the statuscanceled, the flagsdry_runandfull,input_checksum,correlation_id,scope_aliases,started_atandfinished_at.countsis{ <entity>: { inserted, updated, unchanged, conflicted, missing } }anderrorsis[{ entity, key, code, message }]. Only one run per tenant and source can be pending or running; a secondstartfails withIMPORT_RUN_ACTIVE. The new tableimport_recordsmaps(tenant, source, scope, entity, external key, role)to the subject it imported.The imports client gains
runs.start,runs.get,runs.list,runs.cancel,markRunning,upsertBatch,resolveandfinish.import_upsert_batchwrites each item through an import target, hashesdatato decide between unchanged and changed, reportsconflictedfor a row changed after the last import, reuses a scope alias's record and, for a dry run, rolls back and returns the counts.finishmarks the records a full run did not send as missing and never deletes them, and it emitsimport.entity_completedfor each entity. A block contributes a target through the newimportscontribution kind ({ entity, subjectType, write, updatedAt? }), and an app lists its own inblocks.imports.options.targets. The hint codes areIMPORT_RUN_ACTIVE,IMPORT_RUN_NOT_RUNNING,IMPORT_TARGET_UNKNOWNandIMPORT_ITEM_INVALID.defineImportandappTableImporttakesourceinstead ofkind, anddefineImporttakes an optionaltargetthatrunImportwrites throughhooks.upsertBatch. Runbetter-supabase codemod 0.47to list the code to rename, thenbetter-supabase upgradeand generate a migration. The migration guide from 0.46 to 0.47 has the table of changes. -
Inbox contacts are now people of the contacts block (ADR 0131). The inbox requires
contacts, a conversation'scontactIdis a person id, and the inboxcontactsandcontact_identitiestables and theperson_inbox_contactslink are gone. A person's addresses on channels live in the newperson_identitiestable (person_id,channel,address,verified_at), andpeoplegainsavatar_urlandmetadata.upgraderenders a data step that turns each inbox contact into a person (the linked one, else the active person with the same email, else a new person with the contact's id), copies the identities, points conversations and identity links at the person, then drops the old tables. Runbetter-supabase add contactsbeforeupgrade.The contacts client gains
identities(personId),addIdentity,removeIdentityandfindByIdentity, and dropslinkInboxContact,unlinkInboxContactandpersonForInboxContact:// Before const person = await db.contacts .personForInboxContact(conversation.contactId, { create: true }) .orThrow(); // After const person = await db.contacts .findByIdentity(organizationId, "whatsapp", "+31612345678") .orThrow(); await db.contacts .addIdentity(personId, { channel: "whatsapp", address: "+31612345678" }) .orThrow();inbox.contacts.upsertstill finds or creates the person and is deprecated until 0.48. Deleting a user no longer erases their inbox contact;purgeContact(personId)erases the person and their conversations.codemod 0.47lists the old calls and tables, and doctor reports the removed methods. See the 0.46 to 0.47 guide. -
New
inspectionsblock (better-supabase/blocks/inspections): audit programmes, inspections with a team and a checklist form, and findings that open cases.saveProgram,approveProgramandcloseProgramkeep the programmes of a period.scheduleplans an inspection of one ofoptions.kindsagainst any auditee subject, numberedAUD-2026-001through the numbering block orAUD-and its position without it.- An inspection moves from
plannedthroughstart,completeandclose, or stops withcancel. Its team gives each member the role of lead, auditor, observer or auditee;saveChecklistfills in the checklist form, andcompletefails withINSPECTION_CHECKLIST_INCOMPLETEuntil it is submitted. addFinding,updateFindinganddeleteFindingrecord findings typed byoptions.findingTypes, with a clause and a compliance control the inspectionassessesthrough the relations block.- A finding of a type in
options.caseFindingTypesneeds a case:raiseCaseopens one through the cases block and links it ascreated_from, andclosefails withINSPECTION_FINDINGS_OPENuntil each such finding has one. - The permission keys are
inspections.read,inspections.writeandinspections.manage. A member withinspections.writeacts on the inspections they are on the team of, as their role allows.
Add
inspections: {}toblocks, runbetter-supabase add inspectionsand generate a migration. -
Knowledge collection grants keep their collection's tenant and type
team_idwith the teams id type, andvisibilitymay be an enum on an adoptedknowledge_collectionstable. Memory gains private organization and record memory, personal memory without a tenant, a cap on archival facts and a per-tenant purge.-
knowledge_collection_grantsgainsorganization_id, filled from the collection, so data lifecycle exports and deletes grants with the tenant. With theteamsblock installed,team_idtakes the teams id type (uuidby default) andset_knowledge_collection_granttakes a team id of that type.better-supabase upgradewrites the column change for an existing install:alter table better_supabase.knowledge_collection_grants add column if not exists organization_id uuid; update better_supabase.knowledge_collection_grants x set organization_id = c.organization_id from better_supabase.knowledge_collections c where c.id = x.collection_id; alter table better_supabase.knowledge_collection_grants alter column team_id type uuid using team_id::uuid;An adopted grants table needs the
organization_idcolumn too. -
knowledge_collections.visibilityis listed intyped: an adopted table may declare it as an enum, written and compared through the column's type andblocks.knowledge.values. -
A memory namespace takes
private: truefororganizationandrecordscopes: the memory gets an owner, who reads and changes it without the manage permission, and nobody else reads it. The owner check constraint allows an owner on those scopes. -
blocks.memory.options.tenant: falselets personal memory have no tenant: passnullas the organization.MemoryRecord.organizationIdisstring | null. -
blocks.memory.options.maxItemskeeps at most that many archival facts per owner (or shared namespace pool) in a tenant; saving one more forgets the oldest. -
purge_memoriestakes atenant(archival.purge({ organizationId })) to purge one tenant. The two-argument function is dropped.
-
-
New
legal-entitiesblock (better-supabase/blocks/legal-entities): several companies inside one organization, with one default and a settings fallback. A single-company organization needs no configuration.create,update,setDefault,archive,restore,getandlistkeep each legal entity's code, name, address, VAT number, chamber of commerce number, IBAN, BIC, logo, default currency and fiscal calendar (fiscalYearStartMonth,taxPeriod). The first entity becomes the default, a partial unique index allows one default per organization, and the default can't be archived.of(id?)callslegal_entity_of(tenant, id): a null id resolves to the default entity, and an entity of another organization fails.resolveSetting(key, legalEntityId?)callsresolve_setting(tenant, key, legal_entity)and falls back from the legal entity to the organization to the code default.settings,setSettingandresetSettingkeep the per-entity values inlegal_entity_settings. The settings block's client gainsresolve, which needs the legal-entities block.blocks.legal-entities.options.onadds a nullablelegal_entity_idto the tables ofinvoices,quotes,orders,numbering,accounting,inventory_locationsandsettings. Null means the default entity. Contacts stay shared.- The permission keys are
legal_entities.readandlegal_entities.manage; members getread. Events arelegal_entity.createdandlegal_entity.updated.
Add
"legal-entities": {}toblocks, runbetter-supabase add legal-entitiesand generate a migration. List the modules to extend inoptions.on. -
New
limsblock (better-supabase/blocks/lims): laboratory samples tested with methods that have specification limits.saveMethod,archiveMethodandlistMethodskeep methods with a unit, a lower and an upper limit and an optional form.registerSample,getSampleandlistSampleskeep numbered samples (SMP-1) that move from registered to testing, completed and released or rejected.recordResultcomputes the outcome from the limits. An out of specification result opens a nonconformity case when thecasesblock is installed and emitslims_result.flagged.releaseSamplerefuses while the latest result of a method is out of specification.options.instrumentQualificationrequires every result to name an asset that holds that qualification on the test date.instrumentStatusanswers the same question before the work starts.- The permission keys are
lims.read,lims.writeandlims.manage.
Run
better-supabase add limsand generate a migration. -
New
maintenanceblock (better-supabase/blocks/maintenance): preventive maintenance plans by time or meter that open dispatch work orders with their spare parts, meter readings and calibrations.createPlantakes atimeplan (everyDays) or ameterplan (meterIdandeveryValue) with an optional asset, priority and spare parts.updatePlanpauses or changes it anddeletePlanremoves it.generateWorkOrdersopens a dispatch work order, with the plan's parts, for every due plan that has none open. A work order that is done moves the plan's next due date, and a cancelled one frees the plan.createMeterandrecordReadingkeep meters such as hours run. A reading never goes below the previous one.recordCalibrationandlistCalibrationskeep calibration records with their due dates.- The permission keys are
maintenance.read,maintenance.recordandmaintenance.manage.
Add
maintenance: {}toblocksnext todispatch, runbetter-supabase add maintenanceand generate a migration. CallgenerateWorkOrderson a schedule. -
One dispatcher runs the recurring cleanups. The new
housekeepingSQL module addsbetter_supabase.maintenance(), which runs each due job and records the outcome, themaintenance_jobsview, andmaintenance_schedule(), which registers the dispatcher with pg_cron when it is installed. Theapprovals,trash,webhook-inbox,rate-limit,idempotencyandchat-sdk-statemodules contribute their purge and expiry functions as jobs, and keep the function names. Runbetter-supabase upgradeto install the module. -
maintenanceplans take calendar rules and required qualifications.- A plan of kind
rruletakes an RFC 5545rrule, adtstartand atz, next to thetimeandmeterkinds. A plan falls due at the first occurrence after its last completion. - Plans take
requiredQualificationsand calibrations takequalifications(qualification type keys). Withqualificationsinstalled, assigning a technician who lacks one to the plan's work order, or recording a calibration without them, fails withMAINTENANCE_UNQUALIFIED. - Breaking for adopted tables:
maintenance_plansgainsrrule,dtstart,tzandrequired_qualifications, andmaintenance_calibrationsgainsqualifications. Add them (the generated migration shows the definitions) before you upgrade.
- A plan of kind
-
New
manufacturingblock (better-supabase/blocks/manufacturing): bills of materials, production orders over inventory, lot genealogy and material requirements.saveBomsaves a draft version of a variant's bill of materials with its components and routing, andactivateBommakes it the active version and archives the previous one; a cycle fails withBOM_CYCLE.explodeBomandwhereUsedwalk every level.saveWorkCenterkeeps the work centers, each with a cost rate per hour and, with the assets block, its machine.createOrdercreates a production order numberedMO-2026-0001.releaseallocates the components and fails withPRODUCTION_ORDER_SHORTAGEunlessallowShortage.startOperation,finishOperationandrecordConsumptionrun it, andcompletebackflushes the rest and receives the output at the material cost plus labor.cancelreturns what was consumed.lotGenealogylists the lots a lot was made from or went into, andlotRecallthe lots, stock, documents and orders a recall reaches.requirementssuggests what to produce or buy, andcreateFromRequirementsturns the suggestions into draft production orders and purchase orders.- Inventory gains the movement reasons
consumptionandproduction, andtake_allocation, whichfulfill_allocationnow calls. Accounting gains thework_in_progressrole (account 1350 in the generic chart): stock movements of those reasons book to it, and a completed order's labor books as theproduction_ordersource. - The permission keys are
manufacturing.read,manufacturing.write,manufacturing.produceandmanufacturing.manage; members getreadandproduce.
Add
manufacturing: {}toblocks, runbetter-supabase add manufacturingand generate a migration. Projects with inventory or accounting get the new reasons and role on their nextupgrade. An organization that ran accountingsetupbefore maps the role withsetAccountRole(organizationId, "work_in_progress", accountId); until then those lines book tosuspense. -
Medications gain signatures, extra columns and guest reads.
approveOrderapproves an order with the prescriber's completed signature, andrecordAdministrationtakes asignatureId. The newmedicationExtraColumnsandadministrationExtraColumnsoptions add columns to the catalog and dose tables (fieldsonsaveMedicationandrecordAdministration).guestRead: truelets a guest with a read grant read a record's orders, doses and medications.record_medication_administrationhas a new signature, so apply the new migration withbetter-supabase upgradeand regenerate your bindings. -
Add the
medicationsblock (better-supabase/blocks/medications). An organization keeps a medication list, imported from a drug database through a versionedMedicationCatalogport (testMedicationCataloginbetter-supabase/testingchecks one) or added by hand. Prescribers order a medication for any record with a dose, route and schedule, or as needed with a maximum per day, andimportOrdersbrings in a pharmacy's orders by external id.planAdministrationsplans the doses, members record each one as given, refused or skipped, a high-risk dose needs a second member to check it, andmarkMissedmarks late doses missed and notifies the members who manage medications.chartreads a record's orders and doses, and the example app adds amedication-chartrecipe. -
New
meetingsblock (better-supabase/blocks/meetings): meetings with an agenda, attendees and roles, minutes per agenda item, decisions the attendees vote on, and action items that become tasks.createplans a meeting of one ofoptions.kindswith its attendees and agenda.start,holdandcancelmove it throughplanned,in_progress,heldandcanceled;setAttendee,removeAttendee,saveAgendaItemanddeleteAgendaItemchange the team and the agenda.recordDecisionadds a decision, attendees vote on it with the reactions block, anddecidesettles it from the votes or with a status you pass.addActionItemopens a task through the tasks block and links it to the meeting, an agenda item or a decision.- A meeting has at most one chair. A member with
meetings.writeruns the meetings they created or chair or take the minutes of, and members withoutmeetings.readread only the meetings they are invited to. - The permission keys are
meetings.read,meetings.writeandmeetings.manage. Withoptions.calendarplanned meetings mirror to a calendar, and with notifications an invited attendee is notified. - The
qmsandehspresets include the block, and the recipesmeeting-agendaandmeeting-minutesrender the list and the minutes.
Add
meetings: {}toblocks, runbetter-supabase add meetingsand generate a migration. -
meetingstakes custom fields:blocks.meetings.options.extraColumnsadds columns to themeetingstable,createandupdatetake their values underfields, and reads return them underfields. Pass a Standard Schema asfieldstocreateMeetingsto type and validate them.Meetinggains afieldsproperty (empty without extra columns). Runbetter-supabase upgradeand generate a migration after adding columns. -
Module tables follow the naming convention (ADR 0130): a table is its entity's plural, or starts with its entity's singular. Run
better-supabase upgradeand generate a migration; it renames each table in place with its indexes, policies, triggers, constraints and sequences, so no row moves and no table is dropped. The 0.46 to 0.47 guide lists every table.Before (0.46) After (0.47) work_items,work_item_assignees,work_item_checklist_itemstasks,task_assignees,task_checklist_itemsengagements,targets,policiesactivities,goals,compliance_policiesrules,rule_defaults,rule_versionsautomations,automation_defaults,automation_versionsleases(idempotency),lease_agreementsidempotency_leases,leasesorganization_domains,organization_sso_providerssso_domains,sso_providersstatus_pages,status_componentsincident_status_pages,incident_status_componentsfulfillments,shipping_rates,kitchen_stationsorder_fulfillments,order_shipping_rates,order_kitchen_stationsactivity_entries,ai_message_embeddingstimeline_entries,memory_message_embeddingsTABLE_RENAMESis exported for code that maps stored table names.- Tables you adopted through
blocks.<name>.tables, and the tables of an entity you renamed, keep their names. Foreign key columns such aswork_item_idkeep theirs too. codemod 0.47lists queries on an oldbetter_supabasetable for review.- The rename steps also rename the constraints and owned sequences that carry the old table name, so a schema diff after
upgradefinds no drop and create pairs. compliancemoves to version 3. An install at version 1 first moves its policy acknowledgements onto theacknowledgementsblock, readingpolicies, and then renames the table. An upgrade step that runs before a table rename always reads the table by its old name.
-
Numbering now supports imports and legal entities. Counters are kept per tenant, entity, legal entity scope and period, and
series: "none"lets credit notes share the invoice series. During an import run,issue_invoiceandcredit_invoicetake a historicalfixed_number, other entities takeset_fixed_number(entity, number), and the counters continue above the imported numbers.sync_number_sequences(tenant, entity, scope)now returns{ synced, mismatched }and lists numbers outside the current format as import run warnings, without rejecting them.next_numberandpreview_numbergain a trailingp_scopeargument with a default. Runbetter-supabase upgradeand apply the new migration. On an app's own sequences table it replaces the key with one over tenant, entity, scope and period. -
Block client methods that arrived with the e-invoicing, DSAR, regulatory filing, OSCAL, moderation, evals, guardrails, prompts, e-prescribing and agent checkout work now take one object input, like every other block method. For example
invoices.sendEInvoice({ invoice, format, channel }),dataLifecycle.verifyDataSubjectRequest({ requestId, method })andincidents.submitFiling({ incidentId, regime, stage, input }). -
Breaking: every block client method with two or more positional arguments takes one object. A required argument becomes a property of the same name, a trailing options object is merged into the object when all its fields are optional and moves under
optionsotherwise, and hook arguments become[input]. For examplecatalog.setPrice(variantId, price)is nowcatalog.setPrice({ variantId, input: price }),drive.shareDrive(id, principal, "editor")is nowdrive.shareDrive({ id, principal, role: "editor" }), andonboarding.complete(checklist, step, organizationId)is nowonboarding.complete({ checklist, step, organizationId }). Ports other libraries implement, queue backends and record-bindingloadandrunstay positional. Runbetter-supabase codemod 0.47to rewrite your calls;better-supabase doctorreports the calls it can still rewrite as BS509, and a new test fails on any block client method with two or more parameters. -
New
observationsblock (better-supabase/blocks/observations): coded measurements of any record, such as vital signs.- A definition has a value type (
number,integer,boolean,code,textorcomponents), a UCUM unit, a code and valid, reference and critical ranges.options.defaults: "vitals"installs nine system definitions with their LOINC codes;saveDefinitionadds an organization's own or overrides a system one. recordandrecordManyrefuse a value outside the valid range and flag itnormal,low,high,critical_loworcritical_high. A critical value emitsobservation.critical_recordedand notifies the leads of the record's team.amendrecords a correction and marks the originalamended;markErrormarks oneentered_in_error.ingesttakes device or import readings with the service role and skips anexternalIdit has seen.list,latest,seriesandbuckets(per UTC hour, day, week or month) read a record's values. With the forms block, a field withmeta.observationrecords an observation when a form about a record is submitted, and the forms field schema takesmeta.options.partitionedpartitions the observations table by month. The permission keys areobservations.read,observations.recordandobservations.manage; the default member role reads and records.- The
observation-chartUI recipe renders a record's latest values with their flags and a sparkline.
Add
observations: {}toblocks, runbetter-supabase add observationsand generate a migration. - A definition has a value type (
-
The
invoicesblock now lists open items per customer and supplier with ageing, andallocatePaymentspreads one payment over several documents (partial, over and under payment, and the early-payment discount, posted through accounting).unallocatePaymentreverses it. Purchase bills get approval levels by amount with an approver per legal entity (approvePurchaseInvoice,approvalStatus, theinvoices.approvekey). Thebankingblock builds payment batches from approved open supplier bills, exports them as SEPA credit transfers (pain.001.001.09) and closes them when the bank debit is matched. Theopen_itemimport target loads opening lists with their original dates. Runbetter-supabase upgradeand apply the new migrations. -
New combined reads:
hiring.board,bookings.page,qualifications.matrix,documents.pageandcare.dossier. Each runs the reads a page needs together over the existing SQL functions, so no upgrade or migration is needed. -
Companies and people in the
contactsblock can carry roles, payment terms, a credit limit and a supplier status. The block addsroles text[](checked againstblocks.contacts.options.roles, defaultcustomer,supplier,funderandpartner),payment_terms_days,credit_limitwithcredit_currency(aMoneyvalue in the client) andsupplier_status(approved,conditionalorblocked).set_party_roles(party, roles)replaces a party's roles.set_supplier_status(party, status, reason)needs the newcontacts.approve_supplierpermission, records an audit entry and emitscompany.supplier_status_changedorperson.supplier_status_changedwith the previous status and the reason. When thequalificationsblock is installed,supplier_status_from_qualifications(party)returnsapprovedfor a supplier with no missing or expired qualification andconditionalotherwise; pass the result toset_supplier_statusto keep the approved supplier list of ISO 9001 clause 8.4.list_companiesandlist_peopletakeroleandsupplier_statusfilters. The client addsdb.contacts.setRoles(),setSupplierStatus(),supplierStatusFromQualifications()and theroleandsupplierStatusoptions onlistCompanies()andlistPeople(). Grantcontacts.approve_supplierto the roles that approve suppliers, then runbetter-supabase upgradeand generate a migration to pick up the columns and functions. -
Add payment terms, dunning runs and credit blocks to
contactsandinvoices.savePaymentTermandpaymentTermsmanage terms with due days, an early-payment discount and a credit restriction whose tax is computed on the reduced amount. Invoices copy the party's terms and storediscount_due_onanddiscount_amount_earlywhen issued. Customers getcreditBlock(none,softorhard), alanguageandsetDeliveryPreferences. Dunning levels take atextKey,runDunningrecords runs you read withdunningRuns,dunningRunItemsanddunningHistory, andhandOverToCollectionhands invoices to a collection agency (invoice.collection_started). Payment terms and delivery preferences are import targets.Breaking:
payment_terms_daysandpaymentTermsDayson companies and people are replaced bycustomer_terms_idandsupplier_terms_id. The 0.46 to 0.47 guide has the data step, and the codemod lists the old names. -
payroll-exportnow counts only the time entries of weeks with an approved timesheet. A week that is open, submitted or rejected adds no line, and approving it adds its hours the next time the draft run is refreshed.time-trackinggains thetime_week_approvedfunction. Runbetter-supabase upgradeand generate a migration; it replacescollect_payroll_linesand adds that function. -
New
payroll-exportblock (better-supabase/blocks/payroll-export): payroll runs that add up the approved time, leave and scheduled shifts of a period per person and hand them to the payroll provider.createcollects a draft run for a period fromoptions.sources(the installed ones oftime-trackingandleaveby default,shiftson request),refreshcollects it again, andget,listanddeleteread and remove runs.exportRunrenders the run through aPayrollExportFormat, a versioned port (apiVersion: 1), keeps the SHA-256 of the file on the run and locks it.csvPayrollFormatis the reference format; a provider's layout implements the port.- A new run for a period that overlaps an exported run fails with
PAYROLL_PERIOD_EXPORTED, and a locked run refuses a refresh, a delete or a different file (PAYROLL_RUN_EXPORTED). - The permission keys are
payroll_export.readandpayroll_export.export; admins hold both. Thepayroll-runsrecipe lists the runs.
Add
"payroll-export": {}toblocks, runbetter-supabase add payroll-exportand generate a migration. -
Peppol support in the invoices block, with one channel port.
better-supabase/e-invoicingnow ownsEInvoiceFormat,EInvoiceChannelandEInvoiceDocument, and addspeppolBis3Format. The channel's optionallookup,statusandreceivemethods check a participant, ask the network and poll for documents.testEInvoiceChannelinbetter-supabase/testingis its conformance kit.- The invoices block adds
invoice_e_endpoints(participant ids of an organization, legal entity or company) andinvoice_e_deliveries(the delivery log), theinvoices.sendpermission, fourinvoice.e_invoice_*events, and the methodssendEInvoice,recordEInvoiceDelivery,syncEInvoices,receiveEInvoices,setEInvoiceEndpoint,eInvoiceEndpointsandeInvoiceDeliveries. - Breaking: the
better-supabase/blocks/invoicesexportssendEInvoice(as a function),EInvoiceChannel,EInvoiceFormat,EInvoiceContext,EInvoiceDocument,EInvoiceStatus,eInvoiceChannelOfandeInvoiceFormatOfare gone. Import the types and theoffunctions frombetter-supabase/e-invoicingand callinvoices.sendEInvoiceinstead.
Before After sendEInvoice({ invoice, format, channel })invoices.sendEInvoice({ invoice, format, channel })channel namechannel keysend(document, context)returning{ externalRef }send(document, { recipient, invoice })returning{ messageId }status(externalRef, context)status(messageId, context)document { body, filename, contentType }document { type, id, xml }Run the new migration (or
better-supabase db diff) to add the two tables and grantinvoices.sendto the roles that send invoices. -
New
periodsblock (better-supabase/blocks/periods): dated periods per kind with a close protocol that other blocks take part in.createPeriod,periodFor,isOpen,lock,close,reopenandlistPeriodskeep ranges with anopen,lockedorclosedstatus.periodForcreates a missing calendar period for kinds that have a cadence.- A block adds a kind through
contributes.periodswith a blockers function and an on-close function.closeruns every blocker check first and fails with thePERIOD_CLOSE_BLOCKEDhint, then runs each closing step in one transaction. - Accounting contributes
fiscal_periodand leave contributesleave_year. The existingclose_accounting_periodandclose_leave_yearkeep their names and behavior. - The permission keys are
periods.read,periods.writeandperiods.manage.
Run
better-supabase add periodsand generate a migration. -
Postgres features are now opt-in.
searchColumnoncontacts,deals,tasks,invoicesanddrive, and the@bsb searchtable tag, add a storedsearch_tsvcolumn with a GIN index.noOverlaponleases,calendarandpassesadds exclusion constraints.partitionedonfield-historypartitionsfield_changesby month.better-supabase doctorgains BS360 for secret-named columns outside Vault. -
Postmortem
actionItemsand theaction_itemscolumn are removed from theincidentsblock. Write action items withaddPostmortemAction(thetasksblock) and read a postmortem'sactions. Runbetter-supabase upgradebefore you diff: its new step copies the items of an existing database into tasks and then drops the column, and it stops with an error instead of dropping items it can't copy.codemod 0.47lists the lines that useactionItems. -
The
people,projectsandfield-servicepresets list composite blocks (recruiting,collaborationandservice).peopleandprojectsinstall the same blocks as before.field-servicenow also installs maintenance plans, cases and SLAs, which theservicecomposite brings with the dispatch board. -
Activities takes progress notes. An engagement has an
audience:teamkeeps today's read rule,subjectalso lets guests with a read grant on a linked record read it, andrestrictedneeds one ofrestrictedRoleson a linked record's team, the newactivities.read_restrictedpermission, or to be its author or owner. Engagements also take acategory(checked againstoptions.noteCategories) and agoalId.Engagements of a
options.lockTypestype (defaultnoteandreport) lockoptions.lockAfterHoursafter they are logged (default 24). After that,update,completeandremovefail withACTIVITY_LOCKED. Notes logged before this release keep no lock.amend(id, body)adds a linked addendum (amend_activity, eventengagement.amended), andmarkError(id, reason)flags an engagement as entered in error and locks it (mark_activity_error, eventengagement.marked_error).The subjects block adds
has_subject_role(subject_type, subject_id, roles), which checks the caller's record team roles.Upgrade: re-run
better-supabase add activitiesandbetter-supabase add subjects, then generate a migration. On your own engagements table, map the new columns tonullinblocks.activities.columns.engagementsto leave them out. To keep every engagement editable, setblocks.activities.options.lockTypes: []. -
New
promptsblock (better-supabase/blocks/prompts) for versioned prompt templates.createsaves the next immutable version of a named prompt, per tenant or for the whole system, andsetLabelpoints a label such asproductionat a version.getreads a label or an exact version, andrenderfills{{name}}placeholders and throws on a missing or unused variable. Only the service role reads or writes the tables. Runbetter-supabase add promptsto install it. -
Three new named presets:
psa(professional services: clients, tasks, time tracked against rate cards, a staffing roster, expenses, quotes, contracts and invoices),ats(applicant tracking: hiring pipelines, application forms, interview scheduling, offers with signatures) andintranet(announcements, knowledge base, drive, channels, staff directory and policy acknowledgements).Use them with
npx better-supabase init --preset psaordefineConfig({ preset: "psa" }). HR operations stay thepeoplepreset and the help desk stayshelpdesk. -
Purchase bill lines and expense lines carry
dimensions, so one bill or expense report can split its cost over several projects. A line of a purchase bill (LineInput.dimensions) overrides the bill's owndimensionsper key, and an approved expense report books one expense line per distinct dimension set.billableTime.projectCosts(projectId)then counts each part on its project.add_expense_lineandupdate_expense_linetake adimensionsargument; a line table of yours without the column refuses it withEXPENSE_DIMENSIONS_UNSUPPORTED.Run
better-supabase upgradeand generate a migration.invoice_linesandexpense_linesgain adimensions jsonb not null default '{}'column, also over your own tables, and the twoadd_expense_lineandupdate_expense_linefunctions get an eighth argument. -
The
invoicesblock keeps purchase bills next to sales invoices. An invoice created withdirection: "purchase"is a bill from a supplier, withsupplierReference, apurchaseOrderIdanddimensions; bills number from their own sequence (BILL-1, credit notesBCN-1), every write on one needs the newinvoices.purchasepermission, and a bill books in the purchase journal (the payable against expense and deductible tax, or against the payable a stock receipt booked for product lines of a purchase order).db.invoices.match(billId)(purchase_bill_match) runs a three-way match of the bill against its purchase order and received quantities withinoptions.matchTolerance(default{ bps: 100, amount: 500 }) and emitsinvoice.match_checked; paying a bill that doesn't match fails withINVOICE_MATCH_FAILEDunless the caller holdsinvoices.override_match.aging()takes adirection.The
inventoryblock adds purchase requisitions (requestPurchase,decidePurchaseRequisition,purchaseOrderFromRequisitions, decided through theapprovalsblock when installed, with thepurchase_requisition.createdandpurchase_requisition.approvedevents) and receipts:receivePurchaseOrderwrites aninventory_receiptsrow with its lines, returnsreceiptIdand emitsinventory_receipt.created. Withoptions.receiptInspectionset to an inspections kind, each receipt schedules an incoming inspection. Withcontactsinstalled, a blocked supplier can't get a purchase order (PURCHASE_ORDER_SUPPLIER_BLOCKED).The
ordersblock addspurchaseOrderFromOrder(orderId, supplier)for drop ship, with the order's shipping address as the purchase order'sship_to. Withcontactsinstalled, placing an order and issuing a sales invoice check the party's credit limit (ORDER_CREDIT_LIMIT_EXCEEDED,INVOICE_CREDIT_LIMIT_EXCEEDED) unless the caller holds the neworders.override_creditpermission.manufacturingtakespurchaseSuggestions: "requisition"to turn purchase suggestions into requisitions.Grant
invoices.purchase,invoices.override_matchandorders.override_creditto the roles that need them, then runbetter-supabase upgradeand generate a migration. The invoices table gainsdirection,supplier_reference,purchase_order_idanddimensions, also over your own invoices table, and its unique number index now includesdirection. -
Add the
qms,ehsandismspresets.qmsinstalls SaaS with the quality blocks (controlled documents in the drive, cases, inspections, risks, qualifications, acknowledgements, courses, assets and metrics) and releases drive documents through an approvals policy.ehsinstalls the same blocks without posts or document control, andismsinstalls SaaS with compliance, risks, inspections, cases, acknowledgements and the drive. Each preset has a docs page, andinit --presetandadd --presetaccept the new names.codemod 0.47now names the policy acknowledgement and sequence run items in its description, and the 0.46 to 0.47 guide gains before and after code for AI document versions and postmortem action items, plus a list of what 0.48 removes. -
Quotes take
options.holds, which needs the inventory block. Sending a quote allocates stock for each tracked catalog line of the published version throughallocate_stock(document typequote_version), keeping what isn't in stock on backorder. The holds end when the quote is revised to draft, withdrawn, expires or is rejected, and whenorder_from_quotemakes its order, which allocates its own lines. Sending the next revision releases the earlier versions' holds.release_quote_holds(quoteId)releases them for the service role. -
Block reads in a read set know their tables and schema.
blockReadtakes the tables the function reads and the block's API schema, sos.blocks.deals.board(...)compiles against the right function without it being in your schema metadata, andbsb.tags(readSet)tags a"use cache"scope with those tables.bsb.blockActiontakesinvalidates(for examplereads.deals.board.tables) to drop the tagged entries after a successful write.readSetTablesincludes the tables of a block read. -
Read sets accept database functions through
s.$fn.<function>(args). The function runs as the caller inside the singlers_<name>round trip, must be stable or immutable, and falls back to one$rpccall when the read set runs without the generated function. -
Access requests can name one record instead of a role. With the
subjectsblock installed and a type that declaresteam,request_record_access(subject_type, subject_id, action, reason, duration)(the client'srequestRecord) files a request for one action,readby default, for 7 days unless it names a duration. The record's team leads approve it, or the holders ofsubjects.managewhen the record has no lead. The final approval adds asubject_membersrow whose newends_atcolumn is the end of the grant, andendorexpire_access_grants()closes it without touching access the member already had. A block can contribute anaccess-requestsgrant for its own subject type, and the module calls its grant function instead. Invalid requests fail withACCESS_REQUEST_RECORD_INVALID.Emergency access opens a record at once and is reviewed afterwards.
open_emergency_access(openEmergency) needs the newaccess_requests.emergencykey and a reason of at least 10 characters (ACCESS_REQUEST_REASON_REQUIRED), grants an emergency team row foroptions.emergency.maxHours(8 by default), notifies the record's leads and the holders of the newaccess_requests.reviewkey, and emitsaccess_request.emergency_opened.review_emergency_access(reviewEmergency) records ajustifiedorunjustifiedverdict once, never on your own access (ACCESS_REQUEST_REVIEW_INVALID), and emitsaccess_request.emergency_reviewed;list_emergency_access(emergencies) lists the grants, unreviewed ones by default.Breaking for TypeScript:
AccessRequestis nowRoleAccessRequest | RecordAccessRequest, told apart bytarget, andAccessRequestEventData.roleisstring | null. Code that readsrequest.rolenarrows ontarget === "role"first;request()still returns aRoleAccessRequest. Theaccess.*events carrytarget,subjectType,subjectIdandaction, so an authorization provider's adapter that grants roles fromaccess.request_approvedcheckstarget. With an authorization provider, listaccess_requests.emergencyandaccess_requests.reviewamong its permissions. Runbetter-supabase upgradeand generate a migration to pick up the columns and functions. -
New
bsb.recordAt(type, id)withcan,copyTo,trashandrestore, acopyhook on record bindings, andcopyBindings. Thecustom-fields,field-history,reactions,driveandsignaturesblocks now bind to a record, and the signatures client takes the request tenant. -
Five blocks gain regulatory workflows (ADR 0187).
moderationrecords DSA statements of reasons, notices from trusted flaggers and appeals, and exports a transparency report as CSV.incidentskeeps a regulatory profile per incident and one filing per NIS2, DORA or CRA deadline, with aremindersrule for each when that block is installed.consentsrecords Sec-GPC as an opt-out, stores parsed IAB TCF v2.2 and GPP strings as evidence, and issues consent receipts.data-lifecycletracks GDPR data subject requests with identity verification, a 30 day due date and one extension.complianceimports OSCAL catalogs and profiles and exports assessment results. Each module gets an upgrade step, so runbetter-supabase db diffto pick up the new tables and functions. -
Removed
acknowledgePolicy,acknowledgements(policyId), thependingOnlylist option andpolicySubjectTypefrom the compliance client, andinbox.contacts.upsertwith theupsert_contactfunction from the inbox. Usedb.acknowledgements.acknowledge,mineandstatus, andcontacts.savePersonwithcontacts.addIdentity. Runbetter-supabase upgradeto drop the function. -
New
rfqsblock (better-supabase/blocks/rfqs): requests for quotation sent to suppliers, their quotes side by side, and an award that creates a purchase order.createRfq,updateRfq,getRfqandlistRfqskeep numbered requests (RFQ-1) with lines that move from draft to open, closed and awarded or cancelled.inviteSupplieranddeclineInvitationname suppliers by party type and id. With the contacts block the party must be an active supplier.recordQuotestores a supplier's unit prices and revises them in place.withdrawQuotetakes a quote out of the comparison.comparelists the live quotes cheapest first and marks the best unit price per line.awardrejects the other quotes and, with the inventory block and alocation, creates a draft purchase order at the quoted prices.- The permission keys are
rfqs.read,rfqs.writeandrfqs.manage.
Run
better-supabase add rfqsand generate a migration. -
better-supabase/blocks/dispatchorders route stops through a new versioned port,RouteOptimizer(apiVersion: 1).dispatch.optimizeRoute(technicianId, day, { locate, optimizer?, start?, end? })orders a technician's day and plans it as their route.nearestNeighbourOptimizeris the fallback,fetchRouteOptimizerposts the stops to a routing service, andoptimizeStopsnever throws: a failing optimizer or an invalid order falls back and reportssource: "fallback".planVisitsorders the bookings of one shift for home care and flags visits that end after the shift.
No migration is needed.
-
Block tables write audit row entries through deferred row triggers, and a row that a block function already recorded in the same transaction appears once.
blocks.audit.options.blockTables("entities","all"or"none") sets the scope, andbetter-supabase table enable auditwrites the registration into your schema file. Runbetter-supabase upgradeand generate a migration. -
Invoices, credit notes, quotes and orders can be imported as historical documents through the
importsblock. Each keeps its number, original dates, final status, buyer snapshot and stored totals, and writes no events, stock movement or accounting posting. A tax or total that differs from the computed one is reported as an item warning, andupsertBatchnow returnswarnings. Document lines gaindiscountAmount,costSource,locationId,binIdand a billing party, anddocument_totals_by_billing_partyreports totals and cost per billing party. -
Quotes and orders can have variants, and invoices can be built from several sources at once.
quotes.createVariant,listVariantsandselectVariant(withforward: "order" | "invoice") manage alternative versions of one quote, and an unselected variant can't become an order or invoice.orders.setVariant,listVariantsandselectVariantdo the same for orders. New columns onquotesandorders:variant_of,variant_labelandis_selected; existing databases get them from the migrationsales_variants_collective_invoices.invoices.invoiceFromSourcesbills delivered orders, shipments and unbilled time for one party, one invoice per billing party and currency, keeps each line's origin in the newinvoice_line_sourcestable, invoices every source once, and supports partial quantities of order lines.invoices.sourcesReadyToInvoicelists what is left to bill. -
Sequence runs are now enrollments (ADR 0131). Each run is a row in
enrollmentswhoseprogramissequence:<sequence id>, and thesequence_enrollmentstable is gone. The run's own columns move ontoenrollmentswith asequence_prefix (sequence_id,sequence_address,sequence_mail_thread_idand the rest), the next step is the run's openenrollment_stepsrow withdue_at, a paused run has the newpaused_atcolumn, and an exited run iscancelledwith the reason in the newcancel_reasoncolumn.upgraderenders a data step that copies eachsequence_enrollmentsrow onto its enrollment and next step, then drops the table. The sequences client keeps its methods and the run shape it returns.-- Before select address, status, step, next_run_at from better_supabase.sequence_enrollments where sequence_id = $1; -- After select x.sequence_address, x.status, x.paused_at, x.cancel_reason, s.step, s.due_at from better_supabase.enrollments x left join better_supabase.enrollment_steps s on s.enrollment_id = x.id and s.completed_at is null where x.sequence_id = $1;Run events are the enrollment events, with
programin the payload. The enrollments block addsenrollment.pausedandenrollment.resumed, andenrollment.cancelledcarries an optionalreason.Before After sequence_enrollment.created,.step_completedenrollment.created,.step_completedsequence_enrollment.paused,.resumed,.completedenrollment.paused,.resumed,.completedsequence_enrollment.exitedenrollment.cancelled, with the exit reason inreason// Before await outbox.register("crm", { types: ["sequence_enrollment.completed"] }); // After: other programs emit enrollment.completed too, so check data.program await outbox.register("crm", { types: ["enrollment.completed"] });better-supabase codemod 0.47lists the old types for review, doctor reports them (BS424) andsequence_enrollmentsin your code, and the stored-type data step renames them in the outbox, automations and timeline. Until 0.48, the outboxlegacyEventTypesoption relays a sequence run event under its old name,legacyEventType(type, data)returns it for a payload whoseprogramstarts withsequence:, andSequenceEnrollmentEventDatais a deprecated alias ofEnrollmentEventData.PROGRAM_EVENT_MOVES(better-supabase) lists the moves. -
Recurrence rules expand in one place. The new
better-supabase/recurrenceentry exportsexpandRuleandrruleOccurrences, and the newrecurrenceSQL module addsbetter_supabase.rrule_occurrencesandrrule_next, which return the same instants. The calendar block'scalendar_rule_startsnow wraps it, and the templates block gainsdue_template_occurrences. Runbetter-supabase upgradeto install the module. -
SLA policies take an escalation ladder.
savePolicyacceptsescalations, a list of steps withat(the share of the clock's time),action(notify,reassignorpage) and atargetforreassign.check()fires each step once per clock, records it insla_escalationsand emitssla.escalated. A type'sonbinding takes anownercolumn thatreassignwrites.Run
better-supabase upgradeand generate a migration: it addssla_policies.escalationsand thesla_escalationstable. -
The
comments,inbox,workflows,enrollments,automationsandsequencesSQL modules now callbefore_andafter_hooks around their write functions:create_comment,assign_comment, the inbox start, send, assign and status change functions,create_workflow_schedule,request_workflow_start,enroll,cancel_enrollment,save_rule,remove_rule,save_sequenceandenroll_in_sequence. Define a function named after the hook (for examplebefore_comment_create) and the module calls it. Runbetter-supabase upgradeto regenerate the module files. -
deals.updatetakes{ changes, strict }instead of the changes array. Bothdeals.updateandtasks.updateacceptstrict: true, which returns the first refused change as araisederror that keeps its hint as the code, instead of listing it inrejected. Wrap an existing call asupdate({ changes }). -
Reads of a record can be logged. Set
subjects.<type>.auditReads: true(it needs theauditblock and a tenant column) and the block read functions for that type,record_summary,list_comments,list_activity,list_status_historyandread_field_values, callrecord_subject_read, which writes one audit entry in thereadcategory with{ subjectType, subjectId, purpose, emergency, block, function }and emitssubject.accessed. Repeated reads by the same person with the same purpose collapse withinblocks.subjects.options.reads.collapseSeconds(60 by default; 0 logs every read), and a read made during emergency access is flaggedemergency.subject_access_log(subject_type, subject_id, since, max_rows)lists the reads to the record's team leads,audit.readholders, and through guests the client or a representative withactauthority; anyone else getsSUBJECT_READ_FORBIDDEN. The client addsdb.subjects.reads.log()andreads.list(). Plain PostgREST selects are not logged, so revokeselecton the table when every read must go through a function. Block SQL gainsctx.read()andctx.readVolatility()to log reads from its own functions. Runbetter-supabase upgradeand generate a migration to pick up the functions. -
subjects.can,subjects.viewandsubjects.record(subject)check a batch of actions throughcan_subjectand read a record's header with them in one call. Thesubjectsmodule now exposescan_subjectto members. -
The
@bsbtable tags gainhistory,lifecycleand a realaudit-reads:history title bodykeeps the old and new value of those columns throughfield-history,lifecycle stage=status pipeline=dealsbinds the table topipelines, andaudit-readsturns onauditReadsfor the table's record type.better-supabase table enable exposewrites the Data API grant into your schema file. Block entities can setsubject.realtimeto track their table for Realtime. -
New
tasks.assignToMe({ workItemId, userId }): it adds the user to the assignees and keeps the others. The caller passes the user id because the client has no signed-in user. -
The new
taxblock (better-supabase/blocks/tax, category commerce) keeps tax codes per organization and legal entity, with a type (sales,purchase,exempt,zero,reverse_charge,intra_eu_goods,intra_eu_services,exportormargin), the accounts a code posts to and its return boxes. Rates are dated:saveRateadds one,rateOn(codeId, date)reads the one valid on a day, and a document uses the rate of its date.computeDocumentTaxreturns the totals per code; the margin scheme taxes the margin (price less cost) and shows no tax amount, andcreditRestrictionBpstaxes a reduced base. Issuing an invoice resolves its lines to codes (tax_code_id, or thetax_codetext) and writesinvoice_tax_lines.prepareReturnbuilds a tax return with box totals and the intra-EU sales list per customer VAT number, andfileReturnfreezes it. Imports gain thetax_codeandtax_ratetargets, eventstax_code.created,tax_code.updatedandtax_return.prepared, and permissionstax.readandtax.manage.Breaking: tax codes moved out of
accounting. Theaccounting_tax_codestable, thesaveTaxCodeandtaxCodesmethods and thesave_accounting_tax_codeandlist_accounting_tax_codesfunctions are gone,accountingnow requirestax, andaccounting.taxReportreads fromtax_codes. Calltax.saveCodeandtax.codesinstead, and runbetter-supabase upgradeanddb diff. The migration guide has the SQL that copies the rows with their ids.better-supabase codemod 0.47lists the old names. -
New
tillsblock (better-supabase/blocks/tills): till sessions, cash movements, end-of-day counts and bank deposits for a point of sale. Thepospreset installs it.createTillandupdateTillkeep cash drawers with a currency and an optional accounting cash account.openSessionstarts a shift with an opening float, and a till has one open session at a time.recordMovementrecords cash sales, refunds, cash in and cash out. A refund or cash out cannot take more than the drawer holds.closeSessioncounts the drawer from denominations or a total and books the variance in accounting.deposittakes counted cash to the bank, andreconcileDepositmatches it to a banking transaction.- The permission keys are
tills.read,tills.writeandtills.manage.
Run
better-supabase add tillsand generate a migration. -
The
usageblock turns its history into invoices. Withoptions.historyand theinvoicesblock,usage.setPricestores a unit price and an included quantity per meter and currency, andusage.billPeriod({ organizationId, periodStart, periodEnd })rates the period's usage into one draft invoice, once per tenant and period. The module adds theusage_meter_pricesandusage_billed_periodstables and the service-only functionsset_usage_priceandbill_usage_period, so runbetter-supabase upgradeto regenerate it. -
New subpath
better-supabase/verifiable-credentialsissues SD-JWT VC and W3C VC 2.0 credentials through the OpenID4VCI 1.0 pre-authorized code flow and verifies OpenID4VP 1.0 presentations (SPEC_PINS.openid4vci,SPEC_PINS.openid4vp,SPEC_PINS.sdJwt,SPEC_PINS.sdJwtVc,SPEC_PINS.vcDataModel).createCredentialIssuertakes sources (qualificationSource,courseCompletionSource,passSource) and anIssuanceStore;signerFromSigningKeyssigns with thesigning-keysblock.StatusListrevokes credentials as a Token Status List or a Bitstring Status List. Themfacontrollers gainregisterPasskeyandverifyPasskeyover Supabase Auth's WebAuthn support, and thecontactsblock gains vCard 4.0 import and export with.vcfdownload helpers (SPEC_PINS.rfc6350,SPEC_PINS.webauthn). -
New
warehouseblock (better-supabase/blocks/warehouse): pick waves and pick lists made frominventoryallocations, picking work items, and cycle count plans.createPickListmakes a line per open allocation of a document at a location, starting with the bin and lot that hold the most stock.recordPickconfirms the bin, lot and serial numbers and the quantity found, andcompletePickListmarks lines with less picked than asked for asshort. Stock moves when the document ships, not when it is picked.createPickWave,releasePickWaveandcancelPickWavegroup lists. With thetasksblock each list gets a work item for the picker.createCountPlan,runDueCountPlansandrunCountPlanopeninventorystock counts on a schedule.postCycleCountposts a count through inventory and holds one with a line over the plan's variance limit (5 percent by default) until it is called withapprove: true.- The permission keys are
warehouse.read,warehouse.pickandwarehouse.manage.
Add
warehouse: {}toblocks, runbetter-supabase add warehouseand generate a migration. -
The warehouse block suggests putaway (rules, bins that hold the variant, free bins by walking rank, also per goods receipt) and slotting (fast movers into the closest bins), saves walking routes on pick lists and orders them through the
RouteOptimizerport with its nearest-neighbour fallback (optimizePickRoute), andcompletePickListnow moves the picker's work item to done. New tables:putaway_rules,bin_slots,variant_sizes; new columnpick_lines.route_position. See ADR 0181. -
The
accountingblock now books invoice charges and write-offs. Adding a charge books receivable against revenue, removing it or voiding the invoice reverses the entry, andwriteOffbooks the open balance as an expense. Named block instances book too when theirusesbinds an accounting instance.project_costsleaves billed time out of the total when its revenue is already booked to the project dimension. Two data steps backfill project dimension values for existing projects and seed the missingdisposal_gainanddisposal_lossaccounts. Runbetter-supabase upgradeand apply the new migrations. -
Doctor rule BS425 reports a
memberstable adopted for sequence runs inblocks.sequences.tables, which the 0.47 upgrade does not move, andcodemod 0.47lists the key for review. The migration guide states that event subscriptions can't filter on a program. -
The
audit.revealedentry an export writes lists the revealed entry ids in the order they occurred, instead of the order Postgres happened to scan them. -
- Seven blocks change manifest category to match their docs group:
incidentsandassignmenttowork,enrollmentstopeople,lead-scoringtocrm, andtrash,versionsandimportstodatabase. Block page URLs do not change.
- Seven blocks change manifest category to match their docs group:
-
A compliance policy that requires acknowledgement now reaches every member, owners and admins included. It is assigned to the new every-member principal (a
roleassignment with the id*) instead of thememberrole.assign_acknowledgementanddb.acknowledgements.assignaccept{ type: "role", id: "*" }, and the data step moves existing policy assignments of thememberrole onto it. Runbetter-supabase add --adoptafter upgrading. -
Fixes in
better-supabase/create/lite:verifyQueryreports a policyto publicwith the rolepublic. It tested the joinedpg_rolesrow, which role 0 doesn't have, so the policy applied to no role and the matrix marked itdenied.accessMatrixTeststries a select asselect 1 from <table>. Thecount(*)query always returned one row, so a select that row level security denies failed asrows:1.verifyFilesreturns the files Postgres rejects assql_errorissues and the modules PGlite skips inskipped, asvalidateDesigndoes. Before, a rejected file dropped its tables from the catalog without an issue.
-
doctorno longer reports BS509 for a call on$blocks.<block>that names another block, or for a file that never reaches a block client. -
Doctor reports BS508 when an installed block declares timers and no source calls
blockTickHandler. -
enrollment_ensurenow emitsenrollment.completedwhen a resync removes the steps that were left and completes the enrollment. Runbetter-supabase upgradeto update the function. -
Four gaps of the ERP import work are closed. A document with no legal entity and a document of the default entity now share one number series, so they can't hold the same number (
LEGAL_ENTITY_NUMBER_TAKEN), andset_default_legal_entityrefuses a switch that would create a duplicate.legalEntities.disableCheck()lists the numbers that block turning a kind ofoptions.onoff, and the restore raisesLEGAL_ENTITIES_DISABLE_COLLISIONinstead of a unique violation.invoices.recomputeTotals()repairs the stored totals of invoices issued before the credit restriction, as a dry run by default, audit logged and without touching posted ledger entries.prepareIntrastatderives arrival lines from purchase receipts that name a member state, lets a manual line win, and the Intrastat functions join theapischema without anapi.functionsentry. Receipt lines ofreceivePurchaseOrderacceptcountryandnetMassKg. The new optionblocks.invoices.options.correctionEventssendsinvoice.totals_correctedto the outbox. Runbetter-supabase upgradeand apply the new migration. -
Index the foreign keys of the moderation DSA tables:
moderation_notices.item_id,moderation_flaggers.user_idandmoderation_appeals.appellant_id. Runbetter-supabase upgradeand add the generated migration. -
The
moderationblock indexes the foreign keys of its DSA notices, flaggers and appeals tables, so joins and cascading deletes no longer scan them. Runbetter-supabase upgradeto regenerate the module. The MT940 parser also drops theNOTPROVIDEDend-to-end id that German banks write when a payment has none. -
The incidents module copies existing postmortem
action_itemsinto tasks. Withtasksinstalled,better-supabase add --adoptwrites a data step that callsadd_incident_postmortem_actionfor each item, keeps theaction_itemscolumn readable and skips a postmortem that already has linked actions, so it is safe to run again. -
A preset's block options now merge key by key with the options you set on the same block in
defineConfig, soblocks: { attachments: { options: { requireScan: true } } }keeps the preset'spublicBucketsinstead of replacing the wholeoptionsobject. -
activities_of,list_attachmentsandread_field_valuesnow log a read of the record they return when its subject type setsauditReads. Nothing is logged for an empty result or a list that names no single record. Apply the new migration withbetter-supabase upgrade. -
The risk heatmap recipe shows an empty state instead of an error when the organization has no risk matrix yet.
-
The app table seal trigger no longer seals a value that already carries the
bsf1:prefix, so an upsert stores its encrypted values once instead of wrapping theexcludedciphertext a second time. A row that moves to another owner with the value unchanged is still sealed again with the new owner's key, and a lookup hash is rewritten when its ciphertext changes. Runbetter-supabase upgradeandsupabase:diffto pick up the new trigger.Doctor's BS352 (plain secret column) now also reports columns that end in
header_value, such asauth_header_value. It skips columns marked in an@bsb encryptedtable tag, and columns that abeforerow trigger seals when its function is listed in the newtooling.doctor.sealTriggersoption. -
checkProjectnow reports aseeds.variantsentry that names an unknown block or a variant the block doesn't declare, asunknown_seed_blockandunknown_seed_variantissues.
0.46.0 (2026-10-30)
-
Fixes from an app built on better-supabase: quote lines with checks across columns, answer keys, invoices from quotes and platform approval policies.
- Line items:
setLineson quotes, deals and invoices, and the quote restore on acceptance, write each line's own columns and itslineExtraColumnsin one statement, so a check across both holds (such ascheck (pricing_mode <> 'fixed' or quantity = 1)). A key a line'sfieldsleaves out takes the column's default on a new line and keeps the stored value on an existing one. - Extra columns: an insert that writes
extraColumnswithout a key falls back to the column's default at run time when the configured type names none, so an app columnnot null default falseworks with the type"boolean". - Quotes:
permissions.accept,permissions.rejectandpermissions.requestChangesgive each answer ofdecideits own key, each falling back todecide. - Quotes:
decidewith anactoron a quote past its valid-until date returns the expired quote instead of{ status: "expired" }, which the client could not read. - Invoices:
fromQuotekeeps a line's product when the quote's line table has only a product id column, takes each issued deposit off per tax rate of its lines, and leaves out a copied line value the invoice column can't take.options.depositLine(descriptionwith{identifier},fields) andoptions.quoteLineValuesconfigure them, andfromQuote(id, { depositDescription })translates the description per call. - Line items:
setLinesand the quote restore on acceptance also work when the app's line table keepspositionasnumeric. - Invoices:
fromQuotededucts a deposit on the final invoice's tax basis when the two differ inpricesIncludeTax, and leaves out deposits that credit notes fully credited. - Invoices:
fromQuotemakes a new final invoice when the previous one was fully credited or archived. The opt-incolumns.invoices.archivedAtnames the app's archive column; archived deposits are not deducted either. - Server:
bootstrap()in a support session ("view as user") runs the bootstrap wrapper as the target and reports the session active, keyed on the support session; an ended support session no longer evicts the target's sessions. - Tasks:
assignrecordswork_item.assignedonly when the call adds someone, with the newaddedIdsnext toassigneeIds, so a call with the same assignees no longer runs the assignment automations again. - Approvals:
permissions.platformis the platform key for reading and editing platform policies; an organization's managers and platform staff without it are refused.
SQL signature:
invoice_from_quote(uuid, integer, bigint)becomesinvoice_from_quote(uuid, integer, bigint, text default null); the old overload is dropped. Callers with the old arguments are unaffected. - Line items:
-
Fixes from an app built on better-supabase: tenant scope exemptions, PowerSync streams on edition 3, multi-limit rate limits, formatter-stable generated code, and block controllers that share a data engine. The 0.45 to 0.46 guide lists what to check.
Import paths, old to new:
Before Now createRateLimitfrombetter-supabase/blocks/queuecreateRateLimitfrombetter-supabase/rate-limitrateLimitedfrombetter-supabase/blocks/queuerateLimitedfrombetter-supabase/rate-limitThe old exports stay as deprecated aliases.
- Tenant scope:
database.sql.tenantScope.exemptRoleslets roles such assupabase_auth_adminthrough the restrictivebsb_tenant_scopepolicies. Doctor reports asecurity invokeraccess token hook behind the scope as BS421. - Roles: with the provider or custom access model,
membership_rolestakes roles outsideblocks.permissions.roles,on_accept.roleschecks onlycan_assign, and a direct write ofmemberships.roleswaps the previous primary role and keeps the others. - PowerSync:
better-supabase powersync streamswrites Sync Streams edition 3, skips disabled memberships, syncs every team in the user's organizations and adds amembership_rolesstream withroles.many. The publication migration starts withcreate publication ... for tableand later adds only new tables. - Attachments:
object_pathis a plain column a trigger fills, so logical replication sends it. Atopicoption (defaultattachments) broadcastschangedto<topic>:<tenant>;attachmentsTopic()names it andcreateAttachmentListControllerlists a record's files again when they change. Runbetter-supabase upgradeand generate a migration. - Notifications: preferences sync and change offline through
notificationPreferencesRoute,send()returnseventId, andlist()items carryrecipientId.AUTHZ_EVENTandauthzUserTopicare exported from the client entries. - Rate limits: oRPC and Hono
rateLimittake severalhits, and oRPC throws a declaredTOO_MANY_REQUESTS.createMcpAuthreads context from aRequestorHeadersand takes aclientId. - CLI:
addrenders new modules withsql.schemaandsql.api, so doctor reports no BS304 right after it.db seedno longer loads the chat SDK. Provider function names can contain{resource}. - Gen:
records/andhooks.tscome out the way oxfmt prints them.createdAtandupdatedAtare optional onInsertfor tables the updated-at extension stamps.gen.hooks.selectwraps every generated select in the app's own function. - Testing:
TestUser,asUser,withRollbackand the seed helpers keep the definition's block map, sodb.$blocksis typed. - Block controllers:
createBlockQuery,createBlockMutationand the framework hooks take{ engine, instance }, andblockControllerEngine(queryClient)frombetter-supabase/queryshares cache entries withblockQueries. - Errors:
BlockHint<B>,isBlockHintandblockHintfrombetter-supabase/blockstype each block's hint codes.
- Tenant scope:
-
The drive has an upload-only role and file requests. Set the new
uploadRoleoption (for example"contributor") and grant it on a folder: the holder adds files withdrive.contribute(organizationId, { parentId, name, mimeType, size })and confirms them withcommitContribution(id, attachmentId), but can't list, open or download the folder or anything in it, their own files included. A contribution takes a free name and returns the new file's id and its upload, not the node. The contributor may upload a revision of a file they added, and nothing else.drive_can_upload(folder)is the SQL check. The role needs the node table'screatedBycolumn, works on node grants only, and granting it on a file fails withDRIVE_ROLE_UNKNOWN.drive.createFileRequest(folderId, { expiresAt, maxUses, password })creates an upload share link on a folder; it needs the share role, and the token comes back once.uploadToRequest(token, file, { name, mimeType, password }), on a client made with the service transport and storage, sends a file through the link: it creates the file under a free name, uploads it and commits it, and returns{ passwordRequired: true }when the password is missing or wrong. Each file counts one use of the link, and withrate-limitinstalled a link takes 20 files an hour (scopedrive_link_upload,DRIVE_LINK_RATE_LIMITED). Request files have the newsourcerequestand no creator, anddrive.node_creatednow carriessource. Over your own tables, addrequestand the upload role to enumsourceandrolecolumns to use them. Runbetter-supabase upgradeand generate a migration to pick up the functions and the widened checks. -
The drive checks files out, blocks downloads and serves rendered previews.
drive.lock(id, { until, note })checks a file out for the caller (8 hours by default, at most 30 days) andunlock(id, { force })ends it; while a lock applies, nobody else may upload, commit, restore a revision, rename, move, trash or delete the file, or trash or delete a folder above it (DRIVE_LOCKED, code55P03). The share role breaks someone else's lock withforce, and the service role ignores locks. Nodes carrylockedBy,lockedUntilandlockNote.drive.blockDownloads(id)keeps the original of a node and everything under it from callers below the write role, andblockDriveDownloads(driveId)does the same for a drive. Blocked callers still open the node and read its previews;downloadfails withDRIVE_DOWNLOAD_BLOCKED, and the storage policy refuses the original. Nodes carrydownloadBlockedanddownloadable, anddrive_can_download(node)is the SQL check.createDrivePreviews({ transport, storage, renderer })renders a file's pages through a versionedPreviewRenderer(apiVersion: 1) and stores them under the newpreviewPrefixoption (default_previews), which readers may open even when downloads are blocked. Itssink()renders onattachment.uploadedandattachment.scanned, and itsjobruns from a queue.drive.previews(id)andpreviewUrls(id)read the pages.A
commenterrole inrolesbecomes the newcommentRole, checked bydrive_can_comment(node), whichdriveSubject()now uses for thecommentaction, so a node's record discussion in messaging follows the node's grants: whoever holds the comment role may post there without the tenant-widemessages.sendkey. Drive share links take theview,downloadanduploadroles; creating one now needs the drive's share role on the node, anuploadlink must name a folder, anddrive.link(token)honors the link'sdownloadAllowedand any download block, refuses upload links withDRIVE_LINK_ROLE_INVALIDand returns the node'spreviews.The drive records
drive.node_locked,drive.node_unlocked,drive.node_download_blocked_changedanddrive.download_blocked_changed. The node table gainslocked_by,locked_until,lock_note,download_blockedandpreview_pages, and withdriveson the drive table gainsdownload_blocked. Over your own tables, map these columns or set them tonullto leave the feature out. Runbetter-supabase upgradeand generate a migration to pick up the columns and functions. -
Knowledge documents can belong to a record. With the
subjectsblock installed,ingest.text(org, { ..., scope: "subject", subject: { type, id } })anddocuments.createstore the record in the new optionalsubject_typeandsubject_idcolumns, and a member reads, lists and searches the document only whilecan_subject(subject_type, subject_id, 'read')is true, so a drive folder's knowledge follows the folder's grants. The owner and the manage permission get no exception, the document's collection must still be readable, and system documents stay readable by every organization.create_knowledge_documentandlist_knowledge_documentstakesubject_type text default null, subject_id text default nullat the end. Scopesubjectwithout both, or a type or id with another scope, fails withKNOWLEDGE_DOCUMENT_INVALID; a record the caller can't read fails withKNOWLEDGE_DOCUMENT_SUBJECT_NOT_FOUND.documents.listtakessubject, a search scope{ scope: "subject", type, id }matches one record, andKnowledgeDocument.subjectreturns it.KnowledgeSubjectis exported frombetter-supabase/blocks/knowledge.- The knowledge module is version 4. Run
better-supabase upgradeand generate a migration to add the columns and constraints.
-
Permission keys now follow one convention:
<area>.<verb>, where the area is the block name in snake_case and the verb isread,write,delete,manageor a verb of the domain. A block installed as a named instance checks its own area (tickets.readfor aticketsinstance oftasks). Runbetter-supabase codemod 0.46to rename the keys in your code, config and SQL; it also renamescreateOAuthServerand the oauth-server block'sOAuthtypes.Old New parties.*contacts.*engagements.*activities.*rules.read,rules.editautomations.read,automations.writerules.publish,rules.adminautomations.publish,automations.managecontrols.*compliance.*support.start,.read,.revokeimpersonation.start,.read,.revokework_items.*tasks.*targets.*goals.*views.*saved_views.*history.readfield_history.readmail.*mail_sync.*number_sequences.assignnumbering.assignservice_principals.*service_accounts.*activity.readtimeline.readsegments.editsegments.writeai_chat.adminai_chat.managecustom_fields.sensitive.readcustom_fields.read_sensitiveemployees.view_sensitiveemployees.read_sensitiveworkflow.edit,workflow.publishworkflow_editor.write,workflow_editor.publishworkflow.read,.run,.adminworkflows.*andworkflow_editor.*ai.*,ai.read,ai.create, ...one area per AI block ( agents,knowledge, ...)organization.exportdata_lifecycle.exportmembers.invitefor waitlist codeswaitlist.inviteOld keys keep working until the next minor: roles that list one get the new keys,
permissionMatchesaccepts both with a warning, and doctor reports them (BS422). With the catalog access model,upgraderenders a data step that renames the stored permission rows and copies their role and override links.PERMISSION_KEY_RENAMESandPERMISSION_KEY_SPLITS(better-supabase/blocks/permissions) andEVENT_TYPE_RENAMES,HINT_RENAMES,SUBJECT_TYPE_RENAMESandrenamed(better-supabase) export the maps. -
Add the
qualificationsblock (better-supabase/blocks/qualifications) for certifications, licences and skills that members, companies and assets hold:- Qualification types with a validity in months and optional evidence, and requirements that name who must hold them: a role, a team, a job title, an asset kind, a segment or one holder.
- Holdings that expire, granted by hand or from a course certificate when the type names the course. Revoking keeps the holding with its reason.
gaps(organizationId, { holderType, holderId, teamId, typeKey, status })lists the required qualifications holders lack, have let lapse or are about to lose (better_supabase.qualification_gaps). A member may read their own gaps withoutqualifications.read.qualifiedHolders(organizationId, typeKey, { holderType, on })returns the holders with a valid holding on a day (better_supabase.qualified_holders).notifyExpiring()reports each holding once when it enters the renewal window (qualification.expiry_warned) and once when it expires (qualification.expired).- The
qualification-matrixandmy-qualificationsUI recipes.
Admins get
qualifications.read,qualifications.grantandqualifications.manage. Addqualifications: {}toblocks, runbetter-supabase upgradeand generate a migration. A permission catalog lists each key per role, so add the three keys to the roles that should hold them. -
Records can have a team. Add
team: { actions: ["read", "write"] }to a type inconfig.subjects, andcan_subjectandcan_subject_forgrant those actions to the users and teams on that record whose dates include today, next to the permission keys. Thesubjectsblock installssubject_members(a user or a team from theteamsblock, a role,starts_onandends_on) withadd_subject_member,end_subject_member,list_subject_membersandmy_subjects, and emitssubject_member.addedandsubject_member.ended. Adding and ending a membership needs the newsubjects.managekey (theadminrole getssubjects.*) ormanageon the record. Roles default toleadandmember;blocks.subjects.options.recordTeam.roleschanges them.The client gets
subjects.members.add,end,listandmine. When a type declares a team, therepresentsrelation kind accepts only targets of such a type. With an authorization provider, listsubjects.manageamong its permissions or pointblocks.subjects.permissions.manageat a key it has, orupgradestops. Runbetter-supabase upgradeand generate a migration to pick up the table and functions. -
New
risksblock (better-supabase/blocks/risks): a risk register per organization.- Risks are numbered (
RSK-0001), belong to a category fromoptions.categoriesand are scored on a likelihood by impact matrix. Each organization gets a 5 by 5 default matrix with low, medium, high and critical bands;saveMatrixadds your own, andoptions.defaultMatrixreplaces the default. assessscores a risk before and after controls (inherent and residual) and keeps every assessment, each frozen as a version.setTreatmentrecords mitigate, transfer, accept (needsrisks.manage) or avoid,reviewmoves the next review date ahead by the risk's interval, andclosecloses it with a reason.heatmapcounts the open risks per matrix cell.getreturns the barriers, the controls and other records linked with themitigated_byrelation kind.- The daily
review-dueschedule runsnotifyDueReviews, which notifies the owner once when a review date comes and emitsrisk.review_date_reached. - The permission keys are
risks.read,risks.write,risks.assessandrisks.manage; the default member role reads the register.
Add
risks: {}toblocks, runbetter-supabase add risksand generate a migration. - Risks are numbered (
-
Share links take a password and a download flag.
shareLinks.create(subject, { password, downloadAllowed })stores a bcrypt hash of the password (at least 8 characters,SHARE_LINK_PASSWORD_INVALIDotherwise) in the newshare_links.password_hashcolumn and the flag indownload_allowed(defaulttrue).shareLinks.resolve(token, { password })fails withSHARE_LINK_PASSWORD_REQUIRED(code28P01) until the password matches, andresolveandlistreturndownloadAllowedandpasswordRequired. With the rate-limit block installed, 10 wrong passwords per link in 15 minutes lock it withSHARE_LINK_RATE_LIMITED; theshare_link_passwordrule changes the limit.resolve_share_linknow takes(token text, password text default null), andcreate_share_linktakespasswordanddownload_allowedbefore the extra fields argument. The functions other blocks serve links through (calendar feeds, booking pages, public forms, drive links, shared AI chats and leave feeds) don't open a link that has a password.A block's share link contribution lists the roles its links may carry (
roles,["view"]unless set), andcreate_share_linkrefuses any other withSHARE_LINK_ROLE_INVALID. Public form links takerespond. Types fromconfig.subjectsandblocks["share-links"].onkeep taking any role. Runbetter-supabase upgradeand generate a migration to pick up the columns and signatures. -
Add the
shiftsblock (better-supabase/blocks/shifts). Shift templates generate draft shifts on weekdays, planners publish them per team and location, and every assignment is checked for overlapping shifts, approved leave (leave block), required qualifications (qualifications block) and the minimum rest between shifts. Members ask for open shifts, offer a shift to a colleague and set their availability.roster,myShiftsandhoursread the plan, andtoTimeEntriesturns worked shifts into time entries (time-tracking block). The example app adds aroster-boardrecipe. -
Data lifecycle: export one record with
requestSubjectExport(subjectType, subjectId, { format }), which calls the newrequest_subject_exportfunction. It collects the record and every installed block's rows attached to it, decrypts encrypted columns and custom field values through the reveal functions as the caller (soauditReadstables audit the read), and writes the files through the same exporter. The caller needsorganization.exportor the record'smanageaction. Runbetter-supabase upgradeand generate a migration.data_exportsgainssubject_type,subject_idandformat, andsubjectacceptsrecord.DataExporthassubjectType,subjectIdandformat.data_export.requested,data_export.completedanddata_export.failedcarrysubjectTypeandsubjectId(null for user and organization exports).- A record export's own format wins over the exporter's
formatoption.
-
A subject permission entry takes
check, the schema-qualified name of a SQL function(subject_id <idType>) returns booleanthat decides the action for the caller. Alone it decides the action; next tokey,rowsorownerit must return true as well.can_subjectand the blocks that check record reads (tags, attachments, relations and the others that takeon) call it, andcan_subject_forreturns false for such an action, because it can't run the function for another user.A subject type also takes
readAccess: "record":custom-fieldsthen shows that type's values only to members who can read the record, in every layout, while the other types keepcustom_fields.read.driveSubject()uses both. Itsreadaction asksdrive.readand the newdrive_node_readable(node), itsfieldsaction asksdrive_node_writable(node), and it setsreadAccess: "record". A member withdrive.readbut no grant on a node can no longer tag it, attach to it or read its custom field values. Runbetter-supabase upgradeand generate a migration to pick up the new SQL.
0.45.0 (2026-10-29)
-
Adopter gaps, round 45: quotes over an app table with a fixed customer column and no list or discount totals, product ids of the column's own type, reasons on quote and payment status changes, a switch for the quote owner notification, and a text or inet IP column in an app's state machine history.
- Quotes: with
columns.quotes.companyType: null(orcontactType: null), the id column holds one fixed type,options.company(orcontact).createandupdatewrite the id in the column's own type and refuse another type (QUOTE_COMPANY_UNSUPPORTED), reads return the type, and invoices'fromQuotecarries the customer to the invoice. - Quotes:
listTotalanddiscountTotalmay map tonull, as on invoices; reads return the subtotal and a zero discount. - Quotes:
withdraw(quoteId, { reason })(SQL:withdraw_quote(quote, actor, reason)) and the note ofdecidego to the state machine's history as the reason. - Quotes:
decidewithoutbyor an actor leavesdecidedByempty instead of the caller's user id. - Quotes:
options.notifications: falseturns off thequote.decidedowner notification; when sent, it carries the quote as itssubject_label. - Quotes and other line tables: a line table without a product type column keeps the product id when a version is restored, and
setLineswrites the id in the column's own type, such asuuid. - Invoices:
recordPayment(invoiceId, { reason })(SQL: a trailingreasononrecord_invoice_payment) is the history's reason for the status change a payment or refund causes. - State machine: an app history table's
ipcolumn may betextorinet; a mappedipno longer makes every transition fail.
- Quotes: with
-
Small block additions for quality management:
settings:better_supabase.organization_setting(tenant, key)returns one organization setting to other modules' security definer functions. Onlyservice_roleand the module schema's owner may execute it.employees: every employee event carriesuserId(null for an employee without an account),employee.offboardedincluded.EmployeeEventData.userIdis nowstring | nullinstead of optional.courses: a course takesvalidForMonths(1 to 240), and its certificates getexpiresAt.verifyCertificatereturnsexpiredandexpiresAt, and an expired certificate is no longervalid.course_certificate.issuedcarriesexpiresAt.signatures:requesttakes ameaning, one ofblocks.signatures.options.meanings(defaultauthored,reviewed,approved,released,acknowledged). Requests return it andsignature.completedcarries it; another value fails withSIGNATURE_REQUEST_MEANING_UNKNOWN.compliance: a framework has akind(standard,legal,internalorcontract), and a control takes asourceand ajurisdiction, for legal registers.
Run
better-supabase upgradeand generate a migration to add the columns and the new function signatures. -
Encrypted app table columns can be searched by an exact value, and the
bsn,ibanandphone_e164formats check identifiers as they are written. Runbetter-supabase upgradeand generate a migration.- Lookups:
lookup: trueon an encrypted column (or the@bsb lookup <column>tag) adds a<column>_lookup byteacolumn with an index. The seal trigger fills it with an HMAC-SHA256 of the value, trimmed of spaces and lowercased, under a per-owner lookup key kept in Vault next to the data key.public.<table>_find(column, value)returns the ids of the rows the caller reaches whose value matches, andbetter_supabase.field_lookup(owner, value)gives the service role the hash to compare itself. - Crypto-shredding:
drop_field_key(owner)deletes the owner's lookup key with the data key, so no lookup finds the shredded values. - Formats:
bsn(9 digits that pass the elfproef),iban(ISO 13616, mod 97) andphone_e164join the format registry for app table columns and custom fields. App tables check them in the column check or the seal trigger;set_field_valueraisesFIELD_VALUE_INVALIDfor a custom field value that fails. The SQL functionsbsb_valid_bsn(text)andbsb_valid_iban(text)are created where they are used. SPEC_PINS.iso13616pins the ISO 13616-1 edition the IBAN check follows.
- Lookups:
-
With
relationsinstalled, thecontactsblock contributes the relation kindrepresents(inverserepresented_by) from a person to any record: a guardian, parent, mentor or emergency contact. Each link carries aroleand anauthority(informoract) in its data, with optionalvalid_fromandvalid_untildates, andlinkrefuses other data withRELATION_DATA_INVALID.db.contacts.representativesOf(type, id)lists a record's representatives, andrepresentedByMe(organizationId)lists the records a guest's person represents.The
guestsblock takesoptions.representation: { subjects: ["client"] }. A guest who acts for a person then reaches the records of those types that the person actively represents:readwithauthority: "inform", pluscommentanduploadwithauthority: "act". The access follows the links live, so a link that ends closes the record without touching your grants.Blocks that contribute a relation kind can now attach a check on the link's data; declaring a kind of the same name in
kindsreplaces the check too. -
Block docs pages and catalog entries now use the block names. The
service-principals-tableUI recipe is nowservice-accounts-table, and the old docs and recipe URLs redirect. Theidempotency,rate-limitandwebhook-inboxblocks move from the developer category to automation, next toqueue, which ships them. Every block now has a docs page, includinggrants,mfa,subjects,reserved-slugs,jsonb-schemas,pgtap,realtime-tables,rls-guard,permissions,sessions,impersonation,read-setsandcredentials.
0.44.0 (2026-10-29)
-
The
oauth-serverblock's creator is nowcreateOauthServer, so it follows thecreate<Name>rule every other block uses, and its types writeOauththe same way. The old names keep working as deprecated aliases until the next minor release.Old New createOAuthServercreateOauthServerOAuthServerOauthServerOAuthServerOptionsOauthServerOptionsOAuthServerEventsOauthServerEventsOAuthClientOauthClientOAuthClientAuthMethodOauthClientAuthMethodOAuthClientMetadataOauthClientMetadataOAuthClientEventDataOauthClientEventDataRegisteredOAuthClientRegisteredOauthClientOAuthAuthorizationOauthAuthorizationOAuthGrantOauthGrantOAuthGrantTypeOauthGrantTypeOAuthGrantEventDataOauthGrantEventDataThese names come from
better-supabase/blocks/oauth-server. TheOAuthClienttype inbetter-supabase/client/nativeandOAuthGrantinbetter-supabase/blocks/sessionskeep their names. -
Native apps follow role changes, PowerSync reconnects on them, and bootstrap reports the live authorization version. The 0.43 to 0.44 guide lists what to check.
Bootstrap version fields, old to new:
0.43 0.44 boot.authzVersion(the token's version)boot.tokenAuthzVersionno field boot.authzVersion(the live version)no field boot.stale(the live version is ahead)- Bootstrap: the
bootstrap_<rpc>wrappers readbetter_supabase.caller_authz_version()and return the live version next to the token's.getAccess(boot)seeds the version cache with the live version, so a role taken away since sign-in is gone on the next render. Runbetter-supabase upgradeand generate a migration. - Servers:
bootstrapForandaccessForon every server, and abootstrapSchemaoption.createNextbuilds on them. - Expo:
bsb.bootstrap(request, { rpc }),bsb.getAccess(request, { bootstrap }), andbsb.cached(request, { tables })with the tags an app cache stores the result under (sessionTagand the tag helpers are exported frombetter-supabase/server). - Native:
SessionProviderfrombetter-supabase/react/nativetakes React Native'sAppState, resubscribes when the app becomes active, catches up on a missed change, and reconnects PowerSync after the refresh.startNativeAuthzRefreshfrombetter-supabase/client/nativedoes the same without React. - PowerSync:
syncWithAuthreconnects when a new token for the same user carries another tenant orauthz_ver, and returns anAuthSyncwithreconnect(), queued behind sign-in and sign-out.tenantClaimandfingerprintadjust what counts as a change. - CLI:
better-supabase powersync streamswrites streams for blocks over the app's own tables, reading their columns from the saved snapshot. - Authorization providers:
versions: { function }names the provider's version function; the sessions module then creates no version table. - Auth: for a local project URL the default issuer check accepts the loopback and emulator hosts, and
auth.loopbackAliasesadds more, such as a phone's LAN address. - Approvals: a tenant step that names only users rejects a numeric
requiredabove the number of users, as the config does, and saves"all"as that number. - Timeline: messages in a record's comment thread have the type
comment.posted, and a stored entry that a read-time source also returns appears once.
- Bootstrap: the
-
Relation kinds can name the subject types each end accepts, and other blocks can contribute kinds.
blocks.relations.options.kinds.<kind>.typestakes{ source, target }, lists of subject types in the stored direction.linkrefuses other types with the hintRELATION_TYPE_NOT_ALLOWED(sqlstate22023); a symmetric kind accepts either order. Thekindsoption is now typed in the config.- Blocks contribute kinds to
relationsthroughcontributes.relations. A contributed kind is added next to the app's kinds, and an app kind with the same name replaces it.
-
Approvals: the authorization provider's
isApprovertemplate can use{approvers}, and a manager step reads the employees block's status mapping.authorization.functions.isApprovertakes{approvers}, ajsonbvalue with the approvers the request waits on now.approval_eligiblepasses the current step'sapproverswith itsrequiredcount, or the step'sescalateTowhile the step is escalated, for example{"users": ["<uuid>"], "manager": true, "required": 1}. AI tool calls and support sessions passnull. A provider that keeps covers uses it to let an out-of-office cover decide for the approvers a policy names.- A
manager: truestep no longer lets a manager decide whose employee row holds the app's mappedoffboardedvalue (values.employees.status); it compared against the literaloffboardedbefore.
0.43.0 (2026-10-29)
-
Adopter gaps, round 43: quotes whose totals the app keeps, app columns on version lines, fixed deposits and header discounts on invoices from quotes, finer quote keys, sending a declined quote again in one call, and actors on every quote status change.
- Quotes:
options.totals: "app"leaves the totals to the app (fixed line discounts, VAT regimes such as reverse charge): no recount,depositDuefollows the app's total, and a trigger refuses a totals change once a quote is answered, expired or withdrawn (QUOTE_TOTALS_FROZEN). - Quotes:
options.versionLineExtraColumnsadds columns toquote_version_lines, which each publish copies from the line columns of the same name. - Quotes:
permissions.send,decideandwithdrawtake their own keys, each falling back towrite. - Quotes:
options.resendletssendandpublishtake a rejected, withdrawn or expired quote and send it as the next revision in one call.withdrawalso takes an expired quote. - Quotes: opening a quote by link or portal passes the viewer to the state machine's history,
portalViewtakes anactorfrom the service role (SQL:portal_quote(quote, actor)), andexpire_quotesclears the actor. - Invoices:
fromQuote(quoteId, { depositAmount })makes a fixed deposit invoice (SQL:invoice_from_quote(quote, deposit_bps, deposit_amount)), and both invoices copy the line and header extra columns the quote shares. - Invoices: opt-in
depositAmount,discountBpsanddiscountAmountcolumns; with the discount columns the final invoice keeps the quote's document discount on its header.options.depositKindmarks deposit invoices by a kind value and finds them by it and the quote link.
- Quotes:
0.42.0 (2026-10-29)
-
Adopter gaps, round 42: approval requests under the app's own policy and for a named requester, floors for dotted actions and every subject type, switchable and enriched approval notifications, extra columns on tenant policies, approvals for leave by employee, per-employee timesheets and expenses without reports, and actors and reasons on the invoice status changes the block writes.
- Approvals: the service role passes
policy(steps, mode, self-approval, expiry,managerOf) torequest, which only tightens the floor and the matching tenant and platform policies, or stands alone where none matches.requestedBynames the user it files for, who then can't approve the request. A signed-in caller passing either fails withAPPROVAL_FORBIDDEN. In SQL,request_approvaltakes trailingpolicyandrequested_byarguments, andopen_approvaltakesrequested_by. - Approvals: floor action names take dotted segments (
quote.send), and a floor under subject type"*"covers an action for every subject type. - Approvals:
options.notifications: falseturns the block's approval notifications off; anapproval_notification(request_id, kind, notification)hook adds to a notification or skips it. - Approvals:
options.policyExtraColumnsadds columns toapproval_policies, written fromsavePolicy({ fields })and returned underfields. - Approvals: a policy's
managerOfpoints a manager step at an employee's manager instead of the requester's. - Leave:
options.approvalOwner: "employee"makes the request's employee the approval's requester and their manager the manager step. - Time tracking:
owner: "employee"no longer needsapprovals: false; each submitted week files a request with the approvals block, whose decision sets the week's status. - Expenses:
options.standaloneApprovals(without reports) files each submitted expense with the approvals block underoptions.policy, whose decision approves or rejects it. - Invoices:
void,writeOff,reversePayment,chargeandremoveChargetake anactor, and the void, write-off and reversal reasons go to the state machine's history, so a machine over invoices can write its own history. Their SQL functions take a trailingactor jsonb.
- Approvals: the service role passes
0.41.0 (2026-10-29)
-
Adopter gaps, round 41: approval policies by effect, catch-all and platform rows, payload conditions, tenantless requests, every holder of a permission, escalation and service-role deciders; quote working copies, version lines, fixed and pay-first deposits, subscription periods, withdrawals and app portal answers; and actors on block-written status changes.
- Approvals: floors take
effectsand an"*"action; tenant policies matchsubjectType: "*",action: "*"and aneffect.options.platformPolicieskeeps runtime-edited platform policies (no organization) that apply everywhere and stand in for a missing floor.options.conditions: "payload"matches conditions against the request payload without automations. - Approvals:
options.tenantlesslists subject types whose requests may have no organization (request(..., { tenantless: true }));organizationIdisnullon them. - Approvals:
required: "all"with onlyapprovers.permissionasks every holder;escalateAfterandescalateTowithescalate_approvals()let fallback approvers decide a step that waited;approveandrejecttake{ decidedBy }for the service role. - Leave and expenses:
decideanddecideExpensetakedecidedBy, which the service role passes so the decider is kept. - Quotes:
options.workingCopyedits sent quotes while the customer sees the last published version (publishon the same link);options.versionLineskeeps published lines as rows with ids inquote_version_lines, andselectedtakes those ids.depositAmount,depositRequired, lineperiods,withdraw,decidewith anactor, andportalViewfor the service role. - State machine:
actor.idnames the user the service role acts for; quotes (send,publish,revise,withdraw,decide, customer answers) and invoices (issue,recordPayment) pass their actor to the history. - Invoices:
fromQuotecopies a subscription line as quantity times periods.
Configs that set none of the new options behave as before.
ApprovalRequest.organizationIdandApprovalTenantPolicy.organizationIdare typedstring | null. - Approvals: floors take
0.40.0 (2026-10-29)
-
Ledger and invoice gaps: organization purges with a ledger, the tenant column of block subjects, payments after a write-off, and actors on ledger and invoice payment reads.
- Data lifecycle:
purge_organizationnow deletes a tenant's ledger entries and transactions. It sets the transaction-localbetter_supabase.purge_tenantsetting, and the ledger's append-only guard lets a delete through only for the service role, only for that tenant and only while its deletion is due. Updates, and deletes by anyone else, still fail withLEDGER_APPEND_ONLY. Before, purging any organization with a ledger transaction failed. - Subjects: the subjects blocks register (
ledger_account,work_item,productand the others) name the tenant columndatabase.sql.tenantColumngives, as the block's tables do. Before, they kepttenant_id, so comments and other subject checks failed once such a block was installed. - Invoices:
options.paymentsAfterWriteOff: truelets a written-off invoice take payments, such as a provider payment that arrives after the write-off. The invoice staysuncollectiblewhile a balance is left and moves topaidonce nothing is owed. The default still refuses them withINVOICE_NOT_PAYABLE. - Invoices:
payments(invoiceId)(list_invoice_payments) reads an invoice's payments withrecordedBy, and needs the read key. - Ledger:
entries(accountId)returns the transaction'sactorIdon each entry.
- Data lifecycle:
-
The
better-supabaseskill covers 0.36 to 0.39:codemod 0.37after upgrading from 0.35, doctor's BS607 version check,bsb.contextClient(ctx.auth)for a supabase-js client on the server, writing block tables through the block client with your own columns infields(BS351), and encrypting secret columns (BS352). BS352 now names thetables.<name>.columnsconfig key instead ofappTables, and the migration guides say that 0.38 and 0.39 only add options.
0.39.0 (2026-10-29)
-
Adopter gaps, round 40: column defaults and unique errors in the catalog, integer rank helpers, team feeds by an employees column, dated leave adjustments, withdrawing approved expenses, and per-year invoice numbering.
- Catalog: a new product, variant or category takes the column default for a value the call leaves out, instead of an explicit
null, soset_product_optionsandcreateVariantwork over atitle text not null default ''column. - Catalog:
CATALOG_SLUG_TAKENandCATALOG_SKU_TAKENare raised only for an index on the slug or SKU column. Any other unique violation, such as an app index on a barcode, is raised unchanged with its constraint name. - Catalog: with
options.rankType: "integer"(now passed to the client throughblockConfig),reorderVariant,moveCategoryandaddToCollectiontake{ position }or whole-number neighbors. - Leave:
options.feed.teamColumnshares a team feed by an employees column instead of team members,feed.teamNameandfeed.organizationNameadd the names, andfeed.confidential: "busy"lists hidden confidential leave underbusywithout the type. - Leave:
adjustandaccruetakeeffectiveOn. - Expenses:
options.withdrawApprovedlets the owner, orpermissions.withdraw, take an approved expense back to draft, andpermissions.deleteSubmittedlets its holders delete a submitted or approved expense. - Invoices:
options.uniqueNumber("number","identifier"orfalse) chooses the unique number index, so numbering that restarts each year works, andoptions.linePositionKey: falseleaves out the unique line position index on your own line table.
Configs that set none of the new options or keys behave as before.
- Catalog: a new product, variant or category takes the column default for a value the call leaves out, instead of an explicit
0.38.0 (2026-10-29)
-
Adopter gaps, round 39: variant status, category keys, expense categories without a key or currency, reapproval of changed leave, and draft invoice edits and deletes.
- Catalog:
setVariantStatus(variantId, status)(set_variant_status) moves a variant toactive,archivedor a labelvalues.variants.statusnames, with the update key. It needs a mappedcolumns.variants.statusand refuses without one (CATALOG_VARIANT_STATUS_UNSUPPORTED). A variant that goes live again needs a free combination of option values. - Catalog: optional
permissions.categoryCreate,categoryUpdateandcategoryDeleteforsave_category,move_categoryanddelete_category, each falling back tomanage. - Expenses: the categories table's
keyandcurrencycolumns may map tonull. Without a key, a category's key is its id, and the ledger names its account by the id.options.categoryExtraColumnsadds columns thatsaveCategory({ fields })writes and category reads return underfields. - Expenses without reports no longer register the ledger's
ledger_accountsubject, so comments, messaging, hiring and search render without the ledger tables. - Leave:
options.reapprove: truelets the requester change their own approved leave, which goes back to approval: the taken leave returns to the balance and a new approval opens.permissions.reapprovenames a key whose holders may change anyone's leave the same way. - Invoices:
update(invoiceId, patch)(update_invoice) changes a draft's header and extra columns in one statement with theupdatekey, anddelete(invoiceId)(delete_invoice) deletes a draft with its lines and charges, with the new optionaldeletekey (falling back toupdate, thenwrite). Both refuse an issued invoice and recordinvoice.updatedandinvoice.deleted.
Configs that set none of the new keys, columns or options behave as before.
- Catalog:
0.37.0 (2026-10-28)
-
Adopter gaps, round 38: one-statement updates, a whole option matrix, finer keys for invoices and expenses, and confidential leave.
- Updates write the extra columns in the same
updateas the block's own columns:save_product(withkindand the price settings),save_variant,save_category,update_expense,update_leave_requestandsave_calendar_event. A table check across a block column and an extra column, such as(kind = 'digital') = (delivery is not null), now holds when a product changes kind. - Catalog:
setOptions(productId, options, { titleSeparator? })(set_product_options) replaces a product's options by name and makes its variants the full matrix in one transaction. Variants of a surviving combination keep their id, duplicates and variants of removed values are deleted or archived, missing combinations get a new variant, and titles become the values joined by" / ".options.maxVariants(default 100) caps the matrix. - Invoices: optional
permissions.create,update,issue,payment,creditandcharge(falling back towrite) andvoid,writeOffandreverse(falling back tomanage). - Expenses without reports: optional
permissions.create,update,delete(for someone else's expenses),reimburseandcategories, each falling back tomanage.reimbursealso coversreimburse_expense_report, andcategoriesthe category functions with reports. - Leave:
columns.types.confidentialmaps a boolean column of your own types table. Leave of a confidential type is left out oflist,balances,ledger, the feeds and the read policy for anyone but the employee, their manager and holders ofpermissions.readConfidential(managewhen unset). - Leave feed:
options.feed.namesreads first and last name when the employees block usesname: "split", andoptions.feed.typeKeynames the types columnhideTypesmatches, such ascategory.
Configs that set none of the new keys or columns behave as before.
- Updates write the extra columns in the same
-
Inventory counts fractional units with lots, serials, expiry, bins and average cost; orders come from lines or a quote; and shipments carry stock (ADR 0127).
setStockItem(variantId, { unit, scale, tracking, tracksExpiry, costing, currency })gives a variant a unit with up to 6 decimals, lot or serial tracking and weighted average cost. The ledger posts base units (the quantity times ten to the scale).- Every movement takes a
detailwithbinId,lotIdorlotandserials.saveBin(withholdbins),saveLot,stockDetail,expiringLots,expireLotsandstockValuationread and age the stock. Stock leaves first-expiry-first-out, and sales skip hold bins and expired lots. allocate,fulfillAllocation,restoreAllocation,releaseAllocationsandlistAllocationshold stock for a document line instock_allocations, with backorders that fill as stock arrives. Events:allocation.created,allocation.filled,allocation.released.orders.fromLines(organizationId, input)andorders.fromQuote(quoteId)make aconfirmedorder, once per origin or quote, and allocate its lines.orderFromQuoteActioncallsorders.fromQuotewhen you pass nocreate.shipments.setLines(id, lines)andshipments.receiveReturn(id, lines)with the newshipment_linestable: the label takes the lines out of inventory, cancelling puts them back, and returns are restocked, held or scrapped (shipment.return_received).
Breaking changes:
Before After integer stock columns and functions numeric(20, 6);availableis on hand minus reserved and heldbefore_stock_adjust(uuid, uuid, integer, text)before_stock_adjust(uuid, uuid, numeric, text)before_stock_reserve(uuid, uuid, integer, text, text)before_stock_reserve(uuid, uuid, numeric, text, text)move_stock(..., quantity integer, ...)move_stock(..., quantity numeric, ..., detail jsonb)OrderStatuswithoutconfirmedconfirmed, the first status of an order from a documentorderFromQuoteAction({ create })withcreaterequiredcreateoptionalShipmentwithoutlinesShipment.linesRaw SQL reads of the stock columns now return decimal strings such as
"7.000000", and stock event payloads carry them the same way (available,reorderPoint).better-supabase codemod 0.37lists the stock hooks declared with anintegerquantity, the order status switches andorderFromQuoteActioncalls for review. -
Templates take brand starters: with
blocks.templates.options.brandset to the table and column that hold a tenant's brand, a startersyncsaves with abrandreaches every organization of that brand.templates.recurringapplies a template at each occurrence of a recurrence rule kept in reminders:upsert,listandremovemanage schedules,recurring.schedule()(a manifest schedule every five minutes) enqueues onetemplates.recurjob per occurrence on thejobsclient, andrecurring.jobapplies it once. A state-machine machine withworkflow: "<slug>"reads its stages and edges from the published workflow-editor version and pins that version per record. Timelines addtransitionentries from the status history andmessageentries from the record's conversation.Breaking:
TemplateScopeadds"brand",ActivitySourceadds"transition"and"message", andStatusStateaddsworkflowandworkflowVersionId, so exhaustive switches over them need the new cases. Nothing is renamed. Runbetter-supabase upgradeanddb diffto add thebrandcolumn, the schedule tables (withreminders) and the lifecycle'sworkflow_version_id. -
better-supabase codemod 0.37makes every rewrite from 0.35 to 0.37 and lists the rest for review: the session, cache and block changes of 0.36.0 and the stock and order changes of 0.37.0. The new From 0.35 to 0.37 guide covers upgrading from 0.35 to 0.36 or 0.37 and says which release brought each change. The 0.34 to 0.35 guide now lists only what 0.35.0 shipped.codemod 0.35, which 0.36.0 shipped, keeps its rewrites and review lines.
0.36.0 (2026-10-28)
-
Leave, expenses, the drive, the catalog, invoices and calendar feeds run over more of an app's own tables.
- Leave:
options.owner: "employee"keys requests and balances by an employee of the employees block, so an employee without an account has leave too. The client takesemployeeIdonrequest,list,balances,ledgerandadjust, andemployeeIdsonaccrue. Reads returnemployeeId, anduserIdis now optional on requests, balances, ledger entries and feed entries. - Leave: mapped
columns.requests.startPartandendPartbook half a day at either end of a request (startPartandendPartonrequest), combined with hours for an hours type, and overlaps are checked by half day. - Leave:
tables.balancesmaps the app's table of signed amounts (with an optionalexpiresOn) instead of the ledger block. The block sums it, adds taken and adjustment rows, and deletes the taken row when approved leave is cancelled.adjusttakesexpiresOn. - Expenses: mapping
tables.reportsandtables.linestonullkeeps each expense as one row oftables.expenses, without the approvals block or the ledger. The client addscreateExpense,updateExpense,submitExpense,decideExpense,reimburseExpense,getExpenseandlistExpenses, andoptions.owner: "employee"keys expenses by employee. Report mode is unchanged. - Drive: node kind and source, node and drive grant roles, drive kind, and connection provider and status may be enums in the app's tables.
add --adoptandapply --adoptrender the proposal with the authorization provider, so calendaraccessFunctionsin the{ rows, key }form and driveroleFunctionsin the{ rows, roles }form no longer fail with therowsWitherror.- Catalog:
updateProductwithprice: nullclears the price (save_producttakesclear).setProductStatuswrites the canonical app value of a label even when another mapped value reads as it, accepts an app value itself, and moves an archived product back toactivewhen there is no draft status. A product with variants can gain an option, each variant taking its first value.updateVariantkeeps what it isn't given, andskuis optional.permissions.create,updateanddeletename separate keys for products, options and variants. - Invoices:
issue(id, issuedOn, { dueOn })sets the due date, andtermsDays: nullleaves none.removeCharge(chargeId)removes a charge.writeOff(id, reason)keeps the reason in a mappedwriteOffReasoncolumn.reversePayment(paymentId, reason)posts the opposite ledger transaction for a payment recorded by hand and refuses one whose method is inoptions.providerPaymentMethods(defaultstripeandorder). A credit note is now capped at the invoice's total and charges less earlier credits instead of the open balance, so a paid invoice can be credited and refunded. - Calendar:
calendar_feedreturns the link's creator ascreatedBy, and the feed writes the creator's reminders as VALARMs.
- Leave:
-
Calendar feed data, extra columns in inserts, catalog patches and option removal, payment notes, leave edits and team feeds, and more of standalone expenses.
- Calendar:
feedData(token)anduserFeedData(token)return the parsed feed (the calendar with its colour, the organization with the organizations block, the link's creator, and the events with reminders, attendees and extra columns) for an app that writes the iCalendar itself.feedanduserFeedserialize the same data withtoIcs.calendar_feedandcalendar_user_feedreturncolorandorganization. - Extra columns are written in the insert itself instead of an update after it, so a
not nullcolumn without a default or a check across columns holds from the first write: catalog products, standalone expenses, expense reports, leave requests, calendar events, time entries, invoices, quotes and flags. - Catalog:
updateProductandupdateVariantpatch. A key left out keeps its value;nullclears a product'sdescription, derives itsslugfrom the title again, and clears a variant'ssku,title,barcodeorweightGrams.save_productalways takesclear, andsave_varianttakesclearbeforefields, so a positionalfieldsargument moves one place.reorderOptions(productId, optionIds)orders a product's options. A valuesaveOptionleaves out is removed with the variants that use it; a variant still referenced (a foreign key, stock movements oroptions.variantInUse) is archived through a mappedcolumns.variants.statusinstead. Removing them needs the update permission. - Invoices:
recordPaymenttakes anote, and each payment returnsnoteandrecordedBy.record_invoice_paymenttakesnoteas its last argument. - Leave:
update(requestId, change)changes a pending request (which goes back to approval) or, for a manager, approved leave, which is booked again.split(requestId, { gapStarts, gapEnds })takes a gap out of approved leave. A type withautoApprove(the block's table, or a mappedcolumns.types.autoApprove) is approved when it is requested;saveTypetakesautoApprove.options.feedtakesteams(aleave_team_feedlink per team),names,hideTypesandfields, and feed entries carrystartPartandendPart. New eventsleave.updatedandleave.split. - Expenses without reports:
updateExpensetakesfieldsand clearscategoryId,descriptionormerchantwithnull.withdrawExpensemoves a submitted expense back to draft anddeleteExpensedeletes a draft.options.companyExpensesletscreateExpense({ company: true })record an expense without a member or employee. New eventsexpense.withdrawnandexpense.deleted.
- Calendar:
-
The
ai-chatblock runs without a tenant, shares chats with participants, can store a linear list of native AI SDK parts keyed by uuid, and takes extra columns on every table (ADR 0122).better-supabase upgrademoves the module to version 5.blocks["ai-chat"].options.tenant: falselets chats and projects live outside a tenant:chats.create(null, input)andprojects.create(null, input). Such a chat stays private to its owner and its participants, and the AI SDK adapter skips the quota and theorg:gateway tag for it.participants.add(chatId, userId, { role }),removeandlistshare a chat with viewers and editors, stored in the newai_chat_participantstable. In a tenant chat a participant must be able to read the tenant's chats and counts only while a member.chats.listreturns the chats the caller owns or takes part in, and user messages record their writer (authorId).blocks["ai-chat"].options.messages: { key: "uuid", tree: false, parts: "native" }keys messages by uuid, keeps one list per chat instead of a tree, and stores the SDK's own parts. Choose it before installing; a uuid key needs uuid message ids (AI_MESSAGE_INVALIDotherwise), andswitchBranchon a linear chat fails withAI_CHAT_LINEAR.- Every ai-chat table takes extra columns:
projectExtraColumns,participantExtraColumns,messageExtraColumns,moderationExtraColumnsand one key per other table.appendUser,saveAssistant,projects.create,projects.update,participants.addandmoderation.recordtakefieldsfor them.
Breaking changes:
0.34 0.35 organizationId: stringon chats, projects and moderation eventsorganizationId: string | undefinedAssistantContext.organizationId: stringAssistantContext.organizationId: string | nullchats.create(organizationId: string, ...)chats.create(organizationId: string | null, ...)projects.list(organizationId: string)projects.list(organizationId: string | null)private chats: readable by the owner only readable by the owner and the chat's participants -
Approvals: tenant policies, confirm or authorize modes, manager approvers and single-use approvals.
blocks.approvals.options.tenantPolicies: trueadds anapproval_policiestable per organization. A tenant policy tightens the configured policy for the same subject type and action: its steps run after the configured ones, the stricter mode wins,selfApprovalholds only when every policy allows it and the shortest expiry wins.conditionsis a rules filter tree over the subject type's rule fields, matched against the request payload (needs the automations block). The client addslistPolicies,savePolicyandremovePolicy, and the module recordsapproval_policy.savedandapproval_policy.removed.- A configured policy with
steps: []asks for nothing until a tenant policy adds a step or a mode; it needstenantPolicies. - A policy's
modeis"authorize"(the default) or"confirm", where the requester may approve their own request and that approval finishes it. Requests returnmode. steps[].approvers.manager: truelets the requester's manager from the employees block decide the step.requirement(subjectType, action, payload)returns what a request would need, ornullwhen nothing is required;requestthen fails withAPPROVAL_NOT_REQUIRED.request(subject, { fingerprint })binds the approval to an operation, andconsume(id, fingerprint)uses an approved request once (APPROVAL_CONSUMED,APPROVAL_NOT_APPROVED,APPROVAL_FINGERPRINT_MISMATCH), recordingapproval.consumed.approvalFingerprint(value)builds the fingerprint as the SHA-256 of sorted-key JSON. Requests returnfingerprintandconsumedAt.- The SQL
request_approvaltakes a trailingfingerprintargument, so calls with positional arguments keep working. In managed mode, runbetter-supabase upgradeand generate a migration to add thefingerprintandconsumed_atcolumns; over your own table, mapfingerprintandconsumedAtto use fingerprints andconsume.
-
The proxy and every adapter's middleware refresh sessions through
createServerClientfrom@supabase/ssr, on every request they match, prefetches included. Parallel requests with the same refresh token share one call to Auth. Runbetter-supabase codemod 0.35to rewrite the options and list the rest for review.Breaking changes:
refresh: "navigation"is gone. Refresh istrueby default, or a function of the request.verifySession: "navigation"is nowverifySession: "document", and checks document loads only (isDocumentLoadfrombetter-supabase/server).onExpiredPrefetchis removed frombsb.proxy(): a prefetch now refreshes, so it never reachesprotectwith an expired session.shouldRefreshis removed frombetter-supabase/nextandbetter-supabase/server.shouldCheckSessionstays inbetter-supabase/nextonly.clearSessionCookiesreturns a promise. Await it before returning the response.- The cookie writers are removed from
better-supabase/ssrandbetter-supabase/server:writeSession,refreshSession,pruneSessionChunks,sessionEncoding,clearSessionAtScopes,AUTH_CACHE_HEADERSand their types.@supabase/ssrwrites the cookies and their cache headers;readSessionandparseCookiesstay.
Other changes:
- A token whose
issnames another project is rejected withINVALID_ISSUER. Setauth.issuerto enforce an exact issuer, orfalseto skip the check. - The JWKS is fetched with
auth.fetchand cached once per process, so every module graph (proxy, render, route handlers) shares one copy. - When Auth can't be reached, a refresh fails within
timeoutMswithout auth-js's retries and keeps the cookies as they are. - A response that
afterreturns inbsb.proxy()keeps the refreshed session cookies and cache headers.
-
Open pages pick up a role or grant change without waiting for the token to rotate. Run
better-supabase codemod 0.35to rename theSessionProviderprop and list the lines to review.blocks.sessions.options.authzVersionsaddsbetter_supabase.user_authz_versions, thebump_authz_version()trigger function (it reads the user column from its argument, defaultuser_id),bump_authz_versions(uuid[]),authz_version(uid)for the access token hook, and a broadcast onAUTHZ_TOPICfor servers and on the privateauthz:<uid>topic, which only that user may read.SessionProviderholds the session in a store. Withclient(a browser Supabase client) it listens onauthz:<uid>: the visible tab refreshes the token and callsonAuthzChange, then tells the other tabs over thebetter-supabase:sessionBroadcastChannel, and they callonAuthzChangewithout a second refresh.bsb.refreshSessionCache()is a Server Action that drops the caller's ownbsb.cached()entries; re-export it from a"use server"file and call it fromonAuthzChange.AuthorizationHooks.sessionTags(userId)adds a provider's own cache tags tobsb.cached()entries, andevictSession, sign-out andrefreshSessionCacheclear them. The hook is optional, soapiVersion: 1stays.subscribeAuthzVersionsdefaultstopic,eventanduserIdKeyto whatauthzVersionssends, and a per-userauthz:<uid>topic evicts that user.AUTHZ_TOPIC,AUTHZ_EVENTandauthzUserTopicare exported frombetter-supabase/server.
Breaking changes:
SessionProvidertakessessioninstead ofsessionPromise. It accepts a resolvedAuthSessionor a promise.sessionStatusRoutedefaults toverifySession: false: it reads the verified claims only. PassverifySession: trueto ask Auth on every check.
-
Status history records who made a change, memory scopes to records and expires, knowledge gets collections and system documents, the inbox keeps reply drafts, and workflows take the app's own node kinds and a default lifecycle workflow (ADRs 0123 to 0126).
- State machine:
transition(subject, to, { reason, actor })records the actor'sname,email,ipanduserAgentinstatus_history(actor_name,actor_email,ip,user_agent), andhistory()returns them. An app history table maps them withhistory.actorName,actorEmail,ipanduserAgent.history: "app"leaves the history to the app: the block checks edges and recordsstatus.changedbut writes no history, andhistory()fails withSTATE_HISTORY_APP. - Memory:
{ scope: "record", subject }keeps facts about one record that every member reads and admins change.archival.upsertandsaveExtractedtakecategory,confidence(weighs search scores) andexpiresAt. Searches countuseCountandlastUsedAt.archival.restore(id)undoes a forget, andarchival.purge({ retentionDays, batch })(service role) removes deleted and expired facts. - Knowledge:
knowledge.collectionscreates collections with a visibility (automatic,restricted,disabled) and a priority, and grants restricted ones to users or teams. Documents takecollectionId;documents.listandsearchfilter by collection, and search ranks higher priority collections first.documents.create(null, ...)andingest.text(null, ...)(service role) create system documents every organization reads. - Inbox:
inbox.draftskeeps a staff member's reply draft per conversation (upsert,list,send,discard), andsuggest(service role) files an AI draft every staff member who can reply sees. - Workflow editor:
defineNodeKinddefines the app's own node kinds (apiVersion: 1),createWorkflowEditor({ nodes })andnodeKinds.sync()register them inworkflow_node_kinds, andnodeKinds.list()returns them.executeGraphruns custom nodes throughruntime.node, andgraphStarter({ nodeKinds, nodes })binds one step per kind. Definitions take apurpose(automationorlifecycle) andisDefault;definitions.setPurposesets them anddefinitions.resolve(tenant, { subjectType })returns the default lifecycle workflow's published version.
Run
better-supabase upgradeand generate a migration: state-machine moves to version 3, memory to 3, knowledge to 3, inbox to 6 and workflow-editor to 4.better-supabase codemod 0.35rewrites the call sites marked below.Breaking changes:
transition(subject, to, reason)takes{ reason, actor }as its third argument; the codemod rewrites a string literal reason and lists the rest. The SQLtransitiontakes a trailingactor jsonb.memory.archival.forgetsoft deletes: the fact leaves lists and searches but stays untilpurgeremoves it. Schedulepurge.KnowledgeDocument.organizationIdandownerIdarestring | undefined, undefined for a system document.validateGraph(graph, steps)isvalidateGraph(graph, { steps, nodes }); the codemod rewrites it.WorkflowNodeKindaccepts any kind name, so a map over every kind keys by the newWorkflowBuiltinNodeKindand falls back for custom kinds. A graph with a kind that is neither built in nor registered failsvalidate_workflow_graph.WorkflowDefinitionhaspurposeandisDefault.
- State machine:
-
Calendar events keep their alarms, and reminders work on any subject.
- Calendar: a new
calendar_event_alarmstable holds each event'sVALARMs in the feed's reminder shape (amethod, anoffsetMinutesbefore the event or an absoluteat, a repeat, and an optionaluserfor a member's own alarm).upserttakesalarms, reads return them,importIcsreads them andexportIcsand the feeds write them. Maptables.alarmsto your own table or set it tonull. - Calendar:
options.feed.remindersis replaced bytables.alarms. Map your alarm table there, with its columns undercolumns.alarms; the table needs a tenant column. The feed'sremindersnow carry the event's alarms and the link creator's reminders together;CalendarAlarmextendsCalendarReminder. - Reminders:
upsert(subject, { at })sets a one-time reminder (a newremind_atcolumn), andon.<type>.atnames a subject's time column, such as a task'sdue_at, for subjects without a recurrence rule. - Reminders:
schedule()enqueues onereminders.deliverjob per occurrence due in the next day on the newjobsoption, once per reminder and occurrence. The block declares it as thereminders.scheduletimer, andreminderJobSchematypes the delivery queue. save_remindernow refuses a subject of a registered type that doesn't exist in the organization or that the caller can't read (REMINDER_SUBJECT_NOT_FOUND), and withonset, a typeondoesn't list (REMINDER_SUBJECT_UNSUPPORTED). Runbetter-supabase upgradeand generate a migration.
- Calendar: a new
-
The server builds its Supabase clients with
createContextClientandcreateAdminClientfrom@supabase/server, and keeps one memo of verified tokens. A user's client sends the token to PostgREST, Storage and Realtime (throughrealtime.accessToken). The secret-key client is created on first use and shared. Runbetter-supabase codemod 0.35to rename the calls and list the rest for review.Breaking changes:
0.34 0.35 bsb.supabaseFor(auth, headers?)bsb.contextClient(auth, headers?)sessions: falseskips the session memosessions: falseverifies every token on every callaccessTokenResolverremembers tokensit verifies each request; put it behind createServer- The 256-entry verified-token memos inside
resolveAuthandaccessTokenResolverare removed.createServerpasses its session memo to the resolver, so the proxy,bsb.context(),getClaims()andbsb.snapshot()verify a token once while it is valid, andbsb.sessions.evict(userId)reaches every path.
Other changes:
- The memo is keyed by the token instead of its SHA-256, which keeps a hit at about 14 us under load.
- Loaders of one request share one
bsb.snapshot(request)resolution.
- The 256-entry verified-token memos inside
-
Doctor adds three checks.
- BS351 warns when app code writes a block's table directly with
.from("x").insert(),.update(),.upsert()or.delete(), which skips the block's functions. Write through the APIcreateBlocksreturns. - BS352 warns when one of your tables keeps a plain
credentials,tokenorsecretcolumn whilefield-encryptionor thecredentialsmodule is installed. Mark the columnencrypted: true, or store it in Vault and keep acredential_ref. - BS607 warns when the installed
better-supabaseis not the version your lockfile resolves, or when a block file or abetter_supabase.blocksrow records a block version newer than the installed release ships.
- BS351 warns when app code writes a block's table directly with
-
Enrollment program steps take an
assignee({ role }or{ userId }) and aduedate ({ days, from: "start" | "end" }). Enrollments gainstartsAtandendsAt, set throughenroll(program, subject, dates)or the newsetDates, and each scheduled step gets an openenrollment_stepsrow with its rendereddue_at.openSteps()lists the open steps by due date, an assigned user can complete their step, and an enrollment'sschedulelists its scheduled steps. Runbetter-supabase upgradeanddb diffto add the columns; rows inenrollment_stepswith a nullcompleted_atare open steps, so filter oncompleted_atin your own queries over the table. -
toNextRoute(entries, handler)andtoNextAction(entries, action)frombetter-supabase/nextrun@supabase/middlewareentries (withRequiredClaims,withSupabaseClient,withCors) around a Next.js route handler or Server Action. A route handler returns aResponseor a value and gets the routeparams. An action reads the request fromheaders(), writes the entries' cookies throughcookies().set, and throwsNextActionRejectedwhen an entry answers first. -
Pages can read the session, the authorization version and their data in one database call, and keep it in the App Shell. Run
better-supabase codemod 0.35to list the lines to review.bsb.cached()setsstaleto 300 seconds, so private entries ride in the App Shell. The token's lifetime no longer caps it, since the proxy refreshes every request;life: { capToToken: true }brings the cap back. In development astalebelow 300 seconds warns once.bsb.remote(fn, { share, tenant })andbsb.cached({ scope: "remote", key })read user-scoped data in"use cache: remote". The key carries the user, Auth session, tenant and authorization version, never the token. Support sessions get no remote token. Remote entries default torevalidate300 andexpire3600.bsb.bootstrap({ rpc, args, tenant, redirect })calls thebetter_supabase.bootstrap_<rpc>wrapper thatblocks.sessions.options.bootstrapgenerates. It checkssession_active(), returns the token'sauthz_verand the app function's data, seeds the authorization version cache, and calls once per request for the same arguments. An ended session is not cached, its tags are evicted, and withredirectthe caller goes to?reason=session_not_found.bsb.bootstrap()calls the wrappers where the sessions block puts them:genrecords its API schema (blocks.sessions.api, thensql.api) or its ownschemain the schema metadata, andbootstrapSchemaor the call'sschemastill override it.proxy({ verifySession: "bootstrap" })skips the proxy's Auth call for apps whose pages check the session inbsb.bootstrap().bsb.getAccess(source?)returns the caller's context, session, tenant, authorization version andcan(permission)from the request, aSessionSnapshotor a bootstrap result.createNext({ rootParams: { locale, brand, tenant } })addsbsb.locale(),bsb.brand()andbsb.tenant(), and contexts fall back to thetenantroot param.postAuthPath(source, fallback)reads a safe?next=path from a request, search params or page props.AuthzVersionCachegains an optionalseed(userId, version).- Doctor BS608 warns when a remote cache scope runs outside Vercel without
cacheHandlers.remote.
Breaking changes:
sessionStaleandSessionStaleOptionsare removed frombetter-supabase/next. Callbsb.cached()in the scope instead ofcacheLife({ stale: sessionStale(session) }).life.minandlife.maxare removed frombsb.cached(). Uselife.staleandcapToToken.bsb.contextFromSession(session, { token })is removed. Pass theSessionSnapshotfrombsb.getClaims(); the context is built without verifying the token again.
-
Quotes publish versions and price like European offers: VAT-inclusive prices, document discounts, deposits, sections and optional lines, and tax per rate (ADR 0120).
- Each
sendpublishes the quote toquote_versions, a snapshot that never changes.versions(quoteId)lists them andversion(quoteId, revision)returns the quote as it was sent. pricesIncludeTax,discountBps,discountAmountanddepositBpsoncreateandupdate. The database spreads the document discount over the tax rates and writesquote.taxLines(net, tax, gross and discount per rate), which add up exactly to the totals.quote.pricing.depositDueis the deposit asked.- Lines take a
sectionand can beoptional. The customer picks optional lines when they accept (selectedonrespond,decideandportalRespond). portalViewandportalRespondlet a signed-in guest read and answer a quote shared with them, with no token. Answers record the user id, IP address and user agent (decidedUserId,decidedIp,decidedUserAgent).- Invoices take
pricesIncludeTax, andfromQuoteinvoices the lines the customer accepted with oneDiscountline per tax rate, so the invoice totals match the quote.
Breaking changes:
revisekeeps the same quote at the next revision instead of creating a new one, and refuses an accepted quote (QUOTE_ACCEPTED).Quote.supersedesId, thesupersedes_idcolumn andQUOTE_ALREADY_REVISEDare removed; the migration drops the column.- The
quote.revisedevent carriesrevisioninstead ofrevisionId;quote.sentandquote.acceptedcarryrevisiontoo. PublicQuotereturnstotals,pricingandtaxLinesinstead of top-levelsubtotal,discountTotal,taxTotalandtotal.respondresolves to{ status, identifier, revision }.decide_quoteandrespond_to_quotetake a trailingselected jsonbargument; SQL callers that named the old signatures must use the new ones.
- Each
-
The
better-supabase-authskill covers the 0.35 session APIs:bsb.bootstrap(),bsb.getAccess(), the remote scope, the 300-second stale time ofbsb.cached(), theSessionProvidersessionprop andauthzVersionsfor open pages. -
dev stack prunepasses--yestosupabase stack destroyonce it has the user's consent, so the destroy no longer fails withExperimentalStackDestroyError. A--confirmtoken now ignores the presentation flags--yes,--json,--color,--debugand--agent, so adding one of them to the run the user agreed to keeps the token valid.
0.35.0 (2026-10-28)
-
Blocks run over more of an app's own tables.
upgrade,syncand doctor render adopted tables with the authorization provider, so calendaraccessFunctionsin the{ rows, key }form and driveroleFunctionsin the{ rows, roles }form no longer fail with "needs an authorization provider with functions.rowsWith".- Drive: a node under a held folder counts as held, so it can't be trashed, deleted or pruned by a sync. With
roleFunctions.node, a new top-level node no longer gets an owner grant for its creator. - Time tracking: a submitted or approved week refuses only changes to logged time (start, end or duration, subject, owner and rate). The billable flag, the note and app columns stay writable, and
options.lockedColumnslists other columns. - Invoices:
options.chargeExtraColumnsadds app columns to charges, set throughcharge(id, { fields }).options.lineRates: "percent"keeps line discount and tax rates as percentages in the app's line table (invoices, quotes and deals). - Catalog:
save_productwrites the product's ownprice,currencyandtrackInventorywithout a prices table.options.variantExtraColumnsandoptions.categoryExtraColumnsletsaveVariantandsaveCategorywrite app columns fromfields. - Leave:
columns.types.keyandcolumns.requests.partialcan map tonull.
0.34.0 (2026-10-28)
-
Drive access runs over an app's own tables and authorization rules.
options.roleFunctions.nodeandoptions.roleFunctions.drivename schema-qualified functions that return the caller's role on a node or a drive, replacing the block's own grants at that level.options.readPolicy: falseleaves the read policies to the app.- Drive grants accept
userandteamcolumns as well asprincipalTypeandprincipalId, and node grants accept user and team columns too. Managed node and drive grant tables can be created with user and team columns. - A mapped node drive column stays in use when
options.drivesis off, so an adopted table keeps its drive relationship while the block's drive features stay off.
-
Calendar and drive access can come from the authorization provider's per-row grants, without a hand-written function.
blocks.calendar.options.accessFunctionsentries of the form{ rows, key }check the signed-in caller through the provider'srowsWithtemplate, with their own claims, and anyone else, such as the creator of a share link fetched with nobody signed in, throughrowsWithFor.blocks.drive.options.roleFunctions.nodeand.drivetake{ rows, roles }: the provider's resource and the permission key for each role. The caller gets the highest role whose key they hold.calendar_accessandcalendar_event_accessanswer for the caller only and return false for another user unless the service role asks. The calendar feeds check the link's creator through the newcalendar_access_forandcalendar_event_access_for, which no client role can execute.
-
Update Ultracite to 8.1.0 and extend its Playwright and React Native Oxlint presets in the Next.js and Expo examples. Repo tooling only, so no package release.
0.33.0 (2026-10-27)
- Resume an
approval-requireddecision.approval: { header: "x-approval-id" }on the server options names the header the client sends the approval id in; it reachesctx.approvaland the authorizer'scontext.approval, never the subject. MCP reads it from the header orparams._meta.approval, returns the id instructuredContent.approval, and keeps tools that need an approval intools/list. - Add
blockTables(config)tobetter-supabase/sql. It returns the memberships, membership roles and organizations tables with their configured schema, table and column names, plus every installed block's tables, so an authorization library's SQL follows the app's renames. - Add
better-supabase/claims. It exports the claim names (PERMISSIONS_CLAIM,MEMBERSHIPS_CLAIM,FEATURES_CLAIM,AUTHZ_VERSION_CLAIM,PERMISSION_CAP_CLAIM,PERMISSIONS_TRUNCATED_CLAIM),permissionsOf,isTruncated,tenantOf,decodeEntitlementClaim,permissionCapOfand theisUserSession,isApiKeySessionandisSessionSnapshotguards, so client code and authorization adapters read the token without importing the server. - Each codemod publishes its renames as JSON:
better-supabase/codemods/0.32.jsonlists the 0.32 imports, members, config keys and option keys, each mapped from the old name to the new one, for tools that check or apply them. - Add
better-supabase/contract, a types-only entry that re-exports every type an authorization library implements or reads (the provider, token hook, authorizer, request, hooks, bucket and topic policies, credential provider, session snapshot and block tables) withContractApiVersion. - Doctor BS407 reports a custom hook that calls
better_supabase.permission_claimswhen the authorization provider owns thepermissionsclaim. The new BS419 warns when app code callspermissionsAuthorizerwhile some provider keys lacksqlComplete, since the token leaves those keys out. - The
permissionsclaim carries only the keys the authorization provider markssqlComplete: true:better_supabase.member_permissionsandpermission_claimsdrop the others, because a key in the token is a grant in the whole tenant. A provider whosetokenHook.ownedClaimslistspermissionsgets no permissions lines in the generated hook template, andtokenHook.truncatedClaimnames the hook's truncated marker forpermissionsOfandpermissionsAuthorizer. Runbetter-supabase gento regenerate the functions. - Authorizers get more context on each request.
contextgainsintent(readorwrite),operation(get,list,create,update,delete,action,routeortool),requestIdandapproval, typed asAuthorizationContext.resource.sourcesays whether the properties wereloadedfrom the database or are callerinput, and writes carryresource.changewith the stored row (current) and the new values (next).resource.propertiesis unchanged. Resources pass the request scope's memo asruntime.memo. better-supabase/testingaddsauthorizationRequestandsessionSnapshot, which build the request and snapshot shapes the server builds.testAuthorizeralso checks write requests withsource: "input"and achange.testAuthorizationProviderchecks that the token hook names one truncated marker and that a hook writingpermissionshassqlCompletekeys.versionsis typed throughcreateServer,createNext,createHono,createEdgeandcreateMcp, soAuthorizerRuntime<V>andbsb.versionsare the authorization library's own cache type instead ofAuthzVersionCache. Edge and MCP decisions now get the server'sversionstoo.
0.32.0 (2026-10-27)
-
Invoices, catalog, leave, expenses and time tracking run over more of an app's own tables, and
createNext().signUptells the app about an existing account.- Invoices:
options.totals: "app"leaves the totals to the app: no totals trigger and no recount, and the block readssubtotal,taxTotalandtotalas the app keeps them (listTotalanddiscountTotalcan map tonull). A company, contact or origin can be one foreign key column: map its type column tonull, and the id takes the fixed typeoptions.company,options.contactorquote, cast to the column's type. A newinvoice_chargestable (tables.charges, which can be the app's table ornull) holds charges on top of the total, such as collection costs;charge(invoiceId, { amount, description })adds one, the balance and aging include them, andinvoice.chargedis recorded. An invoice's number takes the period of its issue date, so a back-dated invoice is numbered in its own year's sequence. - Catalog:
options.rankType: "integer"orders options, option values, variants, categories and collection products by whole-number positions. Withtables.prices: null, a variant's price iscolumns.variants.price, falling back tocolumns.products.price, incolumns.products.currency.columns.variants.trackInventorycan benullwith the flag on the product, which inventory and orders then read. - Leave:
options.approvals: false(or no approval column) runs leave without the approvals block;decide(requestId, { approved, note })approves or rejects a request, and a rejection recordsleave.rejected. With share-links, aleave_feedlink to the organization serves its approved leave throughfeed(token)while the link's creator can still read everyone's leave. - Expenses:
options.approvals: false(or no approval column) runs expenses without the approvals block;decide(reportId, { approved, note })approves or rejects a submitted report, and a rejection recordsexpense_report.rejected.ExpenseReportSubmittedEventData.approvalIdisstring | null. - Next.js:
signUpreturns{ existingAccount: true }(typeExistingAccount) when Auth answers with the stand-in user it gives for an email that already has an account, so the app can send its own email. Nothing about it reaches an error message. - Time tracking:
options.overlap: "allow"lets a member's entries overlap, andoptions.timers: "many"runs several timers at once (stop_timertakes an entry,running_timersand the client'srunningAll()list them). Over a duration column, stopping adds the running segment andresume_timer(resume(entryId)) runs a stopped entry again. A rate needs a currency, but a currency without a rate is allowed (currencyon the client); the managed table'srate_pair_checkbecomesrate_needs_currency_check.stop_timertakes an optional entry id. - Calendar: an organization purge deletes calendar events itself, so an app's restricting foreign key from events to calendars no longer blocks it.
- Drive:
options.drives: trueadds several drives per organization, drive-level grants, connected drives and mirror nodes. A drive has a kind and an owner,drives()lists them with the caller's role and read-only state,createDrive,renameDrive,deleteDrive,shareDriveandunshareDrivemanage them, andconnections()lists the connected drives.drive_sync_batchmirrors a provider tree into a connected drive as service role: it upserts by external id, links parents, and prunes nodes missing from the run. The tree functions take an optional drive, and roots and sibling names are scoped per drive.drive.connection_created,drive.connection_removed,drive.created,drive.renamed,drive.deleted,drive.sharedanddrive.unsharedare recorded. - Drive legal holds: a
heldsubject column, oroptions.driveswithlegalHoldUntil, marks a node as held, anddrive_node_heldreports a node when it or a descendant is held.holdNodeandreleaseHoldset and clear a hold, a held subtree refusesdrive_deleteanddrive_trashwithDRIVE_HELD, and mirror nodes are read-only.drive.node_hold_placedanddrive.node_hold_releasedare recorded. - Trash: version 3 refuses to purge a held batch with
TRASH_HELD, andpurge_expired_trashskips held batches instead of failing the whole run. - Tasks:
set_work_item_assigneesdeclares its notification variables only when it notifies, which clears the plpgsql_check warnings withoptions.notify: false.
- Invoices:
-
The AI SDK integration follows
ai7.createAssistantreadsstream,usageandfinalStepfrom whatrunreturns and builds the UI message stream with the standalonetoUIMessageStream; a result with only the 0.31 members (toUIMessageStream(),totalUsage,providerMetadata) still works until 0.33, and a result without a stream answers500 AI_CHAT_RUN_FAILED.usageOftakesusageandfinalStep(the old names still work), and the agent runtime stops onisStepCount.validUIMessageschecks a stored history against the app's tools and schemas throughsafeValidateUIMessages.connectToolstakesredirectandprotocolVersionDiscovery, andconnectAllsets them per server throughserverOptions.aiBatchesgainslist()over the provider's batches.0.31 0.32 usageOf({ totalUsage, providerMetadata })usageOf({ usage, finalStep })AssistantRunResult.toUIMessageStream()AssistantRunResult.stream -
The AI SDK integration covers more of the AI SDK UI.
createAssistanttakesstream(thetoUIMessageStreamoptions, such asassistantMetadata,sendReasoningandsendSources) andvalidate, which checks the user's message withsafeValidateUIMessagesand answers422 AI_MESSAGE_INVALID.aiErrorToDbErrormaps AI SDK and AI Gateway errors toDbErrors with a fixed message per kind. A provider error when the answer starts now answers with its own status (a provider 429 answers 429);aiErrorMessageis the defaultonErrorfor stream errors, so the provider's message no longer reaches the client.createCompletionRouteandcreateObjectRouteserveuseCompletionanduseObjectwith the quota check, gateway tags and usage inonFinish;useAssistantCompletionanduseAssistantObjectare the client hooks.useAssistanttakes a message type and passesonToolCall,onData,messageMetadataSchemaanddataPartSchemastouseChat;assistantTransportis exported, and the fields ofAssistantTransportConfigother thanapiare optional.
-
Chat SDK:
stateSchedulerandscheduledAdaptergive any adapterscheduleMessage, holding the messages in a Chat SDK state adapter untilpublishDue(ormaintain({ scheduled })) posts them.inboxAdaptergainsopenDM(with the newdmInboxoption),reply,fetchChannelInfoandlistThreads, and keeps a posted card inmetadata.card.better-supabase/testingaddstestChatAdapter, a conformance kit for Chat SDK adapters. -
The Chat SDK integration follows
chat4.42. Inbox thread ids name the inbox (inbox:<inboxId>:<conversationId>), sochannelIdFromThreadIdreturnsinbox:<inboxId>; build and read them withinboxThreadIdanddecodeInboxThreadId. The inbox module's upgrade (version 4 to 5) rewrites stored thread ids, subscriptions and thread state.inboxAdapteris anAdapter<InboxThread, InboxMessage>, forwardsWebhookOptions(waitUntil,propagateHandlerErrors) fromdispatchandhandleWebhook, takesconcurrencyScope, implementsmarkAsReadandfetchMessageswithdirection: "forward"(through the newafterargument oflist_inbox_messages), and resolves reaction names to unicode. Adapter calls throwChatErrorwith the Chat SDK code (RateLimitErrorforrate_limitedandquota_exceeded,NotImplementedErrorforunsupported) and theDbErrorascause;chatErrorOfdoes the mapping.inboundHandlertakespropagateHandlerErrors,handler.mirrorrecords messages from other bots and skips only the bot's own, anddeliverretries a platformRATE_LIMITEDreply afterretryAfterMs(rateLimitRetries,maxRetryWaitMs).0.31 0.32 inbox:<conversationId>inbox:<inboxId>:<conversationId>Adapter<string, InboxMessage>Adapter<InboxThread, InboxMessage>adapter errors are DbErrorsChatErrorwith theDbErrorascause -
Vercel Connect support covers the rest of
@vercel/connect.vercelConnectCredentialspasses a ref'saudience,resources,authorizationDetailsandvalidityBufferMsthrough to the token request, takes aregion, and maps Connect's error codes to hintedDbErrors (CREDENTIAL_CONNECTOR_NOT_FOUND,CREDENTIAL_CONNECTOR_NOT_LINKED,CREDENTIAL_CONNECTOR_NOT_ENABLED,CREDENTIAL_RATE_LIMITED).getTokentakesfresh: trueto skip the token cache.startAuthorizationreturns the request, verifier, expiry and device code next to the URL, and takesdeviceCodeandprompt.CredentialSubjectaddsjwt-bearerandtokensubjects for token exchange. Vercel Connect accepts them and Vault refuses them.- A ref with
inbound: trueverifies webhooks Connect forwards, through@vercel/connect/chat. - MCP servers whose grant is a Vercel Connect ref connect through
connectAuthProviderfrom@vercel/connect/mcp; a consent request fails withCONNECTOR_AUTHORIZATION_REQUIREDand the URL indetails. - eve's
credentialAuthruns the interactive flow for providers withoutcompleteAuthorizationand shows a device code. channelAdapterpasses aresolvefunction tocreate, so adapters read a rotated token per call.- Mail sync accounts and the sync report set
reconnectwhen the member's grant is gone.
The Next.js example adds an Integrations settings tab that connects Gmail and Outlook through Vercel Connect.
-
vercelConnectCredentials()now returnsVercelConnectCredentials, a credential provider with the calls only Vercel Connect has:tokenDetails(the whole token response),invalidateToken(drops a cached token the provider rejected),connectorMetadata,startInstallation(a connector installation for a tenant) andchannelConfig(a Chat SDK adapter config from@vercel/connect/chat).installationRef(ref, installationId)lets the app subject read a tenant's own installation; the adapter checks the token'stenantIdagainst the ref's tenant.connectSubject(user, { supabaseUrl })builds the Connect subject for a Supabase Auth user with the project's Auth issuer, andwithConnectorTokenruns a function with a user's token or returns the consent URL when the user hasn't authorized the connector. -
better-supabase/everuns eve tools as the session's user.supabaseToolwraps a tool for eve'sdefineTooland gives itsexecutethe repositories fromserver.forContext(), with the agent'sactclaim and the permission keys named inscopes.eveContextbuilds that context, andtenantToolApprovalapplies the tenants'auto,askanddenytool policies.approvalPolicyis a toolapprovalbacked by the approvals block: each call files one request undereve_tool_call, with the steps fromblocks.approvals.options.policies.eve_tool_call.<tool>, and an answer in eve approves or rejects as the person who gave it.queueSchedulesruns the queue block's schedules from one every-minute eve schedule and starts a session for eachevejob as its user.scheduleAgent,agentJobHandler,jobAuthand theeveAgentJobschema go with it.openApiAuthgivesdefineOpenAPIConnectionits token from a credential provider, andtenantArgumentfills an argument with the session's organization. -
Feature flags keep a history and roll out on a schedule (breaking). Every
save_flagrecords a revision with an optional message, andcreateFlags()gainshistory(key)andrestore(key, revision).rolloutVariantbecomesrolloutVariants, a weighted split drawn from a second bucket so growing a rollout never moves a target between variants;better-supabase upgrademoves a stored variant over with weight 100.rolloutScheduleraises the percentage in steps, and rules can name shared segments (saveSegment,segments,removeSegment). The provider takesonEvaluate.better-supabase/flags-sdkaddsflagsDiscoveryHandlerfor discovery routes outside Next.js,explorerOverridesandwithExplorerOverridesfor toolbar overrides on the OpenFeature path,toFlagsSdkDefinition,flagDriftandvercelEnvironmentContext.better-supabase/testingaddsflagOverrideCookie.0.31 0.32 rolloutVariant: "on"rolloutVariants: [{ variant: "on", weight: 100 }]rollout_variantcolumnrollout_variantssave_flag(key, definition)save_flag(key, definition, message) -
better-supabase/flags-sdkfollows the Flags SDK's adapter conventions (breaking).betterSupabaseAdapteris now a ready adapter that readsSUPABASE_URLandSUPABASE_SECRET_KEYon first use; pass it toflag()asadapter: betterSupabaseAdapter. The old factory iscreateBetterSupabaseAdapter, which also takesurlandsecretKeyand anidentifyevery flag on it shares.createIdentify({ server })reads the session from the request without refreshing it, andvisitorgives signed-out requests a stable rollout bucket.getProviderData(adapter, { flags })joins the declared flags for Flags Explorer.pnpm better-supabase codemod 0.32renames the calls.0.31 0.32 betterSupabaseAdapter(options)createBetterSupabaseAdapter(options)adapter: bsFlags()adapter: bsFlagscreateIdentify({ claims })createIdentify({ server: bsb }) -
The access token can carry the caller's permission keys. The permissions block adds
better_supabase.permission_claims(user_id, tenant)for the access token hook, which writes them under thepermissionsclaim (claims.permissionsrenames it) for the active tenant, withpermissions_truncatedwhen they don't fit.permissionsOf(session, tenant)reads them back, andpermissionsAuthorizer({ permissions, load })frombetter-supabase/blocks/permissionsdecides route, action and resource checks from the claim, callingloadonce per request only when the token can't answer. -
Run jobs that Vercel Queues pushes to a route.
vercelQueueRoute(jobs, { client, handlers })frombetter-supabase/blocks/queuewraps the@vercel/queueclient'shandleCallback: it checks each payload against the queue's schema, runs the handler with the same tenant context asdrain, retries a failed delivery afterretryAfterand acknowledges the one that reachesmaxAttempts.vercelQueueNodeRoutedoes the same for(req, res)frameworks overhandleNodeCallback.jobs.runJob(queue, delivery, handler)runs one pushed job for other push backends.vercelQueueProvidernow accepts aQueueClient, which only sends (itsreadrejects), and setsretentionSecondson a delayed message so a delay longer than a day is kept until it runs. Delays past 7 days throw, since Vercel Queues keeps a message at most that long. TheonReceiveoption reports eachreceiveresult, with the reason a poll found nothing. -
Vercel Queues:
vercelQueueProvidertakesretention,headersand aconsumerGroupfunction per queue, hashes idempotency keys longer than 256 characters, and itsstatspoints to the Vercel dashboard. NewvercelQueueTriggerswrites thevercel.jsontriggers for a push route,vercelSendOptionsOf,vercelIdempotencyKeyandvercelTopicOfexpose the send rules, andwithDeadLettershands jobs past their last attempt to a sink. -
Breaking: the public auth names follow supabase-js and Next.js, and tenant is the public word again. Run
npx better-supabase@latest codemod 0.32, then read the 0.31 to 0.32 guide.0.31 0.32 auth.organization,requireOrganizationauth.tenant,requireTenantOrganizationConfigTenantConfigbsb.session(),bsb.getRequestSession()bsb.claims(),bsb.getClaims()bsb.contextForSession()bsb.contextFromSession()(a snapshot, or a session with{ token })AuthState.profile,AuthSession.profileuserMetadatacaller kinds and allowvaluesanon,servicenone,secretbsb.signIn()removed: bsb.signInWithPassword()bsb.authorizeUrl(),OAuthStartbsb.signInWithOAuth(),SignInWithOAuthParamsbsb.exchangeCode(),CodeExchangebsb.exchangeCodeForSession(),ExchangeCodeParamsendedSession,checkSession,EndedSessionOptionsverifySession,VerifySessionOptionssessionEnded,sessionEndedReasonsessionVerified: false,reason(session_not_found,user_banned)refreshSkewSecondsleewayexpiredPrefetch: "protect"onExpiredPrefetch: "redirect"bsb.invalidateSession(),bsb.forgetSession()bsb.evictSession(), which returns a promisebsb.cacheTag(),bsb.cacheTags()bsb.tag(),bsb.tags()The actor kinds (
ctx.actor.kind), event subscribers and the Postgres roles keepanonandservice. -
Add
better-supabase/vercel-sandbox.vercelSandboxes({ sandboxes })gives each chat its own Vercel sandbox:forChatregisters it in the AI chat block'sai_sandboxes, creates or resumes it by name, and returns an AI SDK sandbox session that marks the row used.stopis the stopper for the block's idle-stop job. Theuntrusted,gatewayOnlyandbrokeredpresets set the sandbox's network policy;gatewayOnlyandbrokeredadd tokens at the firewall, so code in the sandbox never holds them.@vercel/sandbox(>=3 <4) and@ai-sdk/sandbox-vercel(>=1 <2) are new optional peers.better-supabase/ai-sdkaddscodeTool(), a tool that runs a Python, Node or Bash snippet in the call'sexperimental_sandboxwith a timeout and an output cap. Hold each run for approval withtoolApprovalon the model call. -
Workflow SDK runs start once per idempotency key, even when two starts race. The Supabase World claims the key in
workflow.workflow_run_keysbefore it starts the run, andstartOnce(ctx, workflow, args, { key })isstartForwith a required key.better-supabase/workflow-sdkaddscancelRunswith a reason,resumeStreamResponsefor streams a client reconnects to by chunk index, andresumeHookFromWebhook, which verifies a Stripe or Standard Webhooks callback and resumes the hook. The World gainsopenHooks(the hooks open runs wait on, without tokens) andpurgeRuns.Ended runs no longer have to stay forever: the
workflow-sdkblock'sretentionoption ("30 days") deletes them every hour with pg_cron, andbetter-supabase db prune-workflows --older-than 30ddoes it on demand. Runbetter-supabase upgradeand generate a migration for the new table and functions. -
The Workflow SDK integration follows
workflow5.2 (breaking for graph approvals). An approval node always files an approvals request through the runtime'srequestApproval, which is now required, andgraphStarterrefuses a live run of a graph with an approval node unless you passapproval.approvalTokenis removed, because a token derived from the run key could be guessed; resume the node withwakeOnApproval. The Supabase World speaks protocol 5.0.4, readsWORKFLOW_POSTGRES_MAX_POOL_SIZE(withWORKFLOW_POSTGRES_MAX_CONNECTIONSas an alias), and addsregisterRouteandregisterHandlerso a queue prefix can go to its own route or run in-process.approvalWaiterand the durable chat resume use the SDK'sHookNotFoundError, anddurableTurntakes an optionalsetAttributesthat records the turn'sbsb.phase.0.31 0.32 approvalToken(runKey, node)the approvals request id requestApprovalreturnsgraphStarter({ ... })graphStarter({ ..., approval })for approval graphs -
gencounts a row-levelbefore inserttrigger as filling a column a CHECK makes not null only when its PL/pgSQL body assigns that column (new.col := …,new.col = …orselect … into new.col). A trigger that only validates no longer makes the column optional on insert. Snapshots record the assigned columns asfillson the trigger.
0.31.0 (2026-10-27)
-
Security: block functions no longer let a caller through when a guard compares a null user column with
auth.uid(). In the employees block anyone in the tenant could read an unlinked employee's contracts and private details and save their private details; the same pattern is fixed in every block that checked an owner, assignee, creator or holder this way.- Calendar:
permissions.create,permissions.updateandpermissions.deletegate event writes on top ofcalendar.write, andoptions.readOnly: { column, values }locks events (such as synced ones) against changes, deletes, cancels and splits (CALENDAR_EVENT_READ_ONLY). Eventkindandtransparencyand attendeeroleandresponsecan be enum columns of the app's tables.cancelOccurrencealso takes{ seriesId, originalStart }. - Employees:
create_employeereads only the extra column keys fromattrs, so a block key such asstatusno longer fails on an adopted enum column, and an omittednot null defaultextra column gets its default.updateContract({ salary: null })keeps an app table's currency. - Tasks:
options.notify: falseleaves assignment notifications to the app, and thework_item.assignednotification carries the item's title as its subject label and an action path fromoptions.actionPath({id},{identifier}). - Share links:
blocks["share-links"].onlimits sharing to the listed subject types, including the types other blocks share. - Data lifecycle: exports leave out
share_links.token_hash. - Custom fields: in the keyed layout with an integer rank, a field without a rank goes after the record's last one instead of writing
NULL.
- Calendar:
-
The permissions block's catalog model gains
list_roles(tenant)andset_permission_override(tenant, role, permission, granted), and the permissions client gainsroles()andsetOverride(). They list the tenant roles with their default and effective keys, and grant, deny or clear one key for a role in one tenant. Listing needsmembers.read, changing needs the newroles.managekey; a member changes only roles they could assign and keys they hold. -
better-supabase codemod 0.29renames therecordsconfig key back tosubjects, which reverses thesubjectstorecordsrename thatcodemod 0.15made. It renames the key inside$env.*and$<environment>blocks too, and merges the entries into an existingsubjectskey (those entries win) with a line to review. It also renames the@bsb recordtag in the table comments ofsupabase/schemas/*.sqlto@bsb subject, and leaves migrations alone. -
Doctor's BS239 warns when a Supabase project runs the pg-delta workflow but
@supabase/pg-deltaor@supabase/pg-topois not installed, sincedb diffstops without them. The finding names the missing packages and thepnpm add -D @supabase/pg-delta @supabase/pg-topocommand.Doctor's peer checks (BS239 and BS601) now also find a peer installed next to the better-supabase package, where the CLI loads it from, so a pnpm workspace that installs it there no longer reports it missing.
-
createNextstarts the flows that email a link:signInWithOtp,resetPasswordForEmail,signUpandresendcall Auth with a PKCE challenge and write the same verifier cookie asauthorizeUrl, soexchangeCodesigns the user in from the link's?code=with the default email templates. A flow started with supabase-js stores its verifier in another format thatexchangeCodecan't read.signInWithOtp,resetPasswordForEmailandresendreturn anActionResult<null>;signUpreturnsnulluntil the user confirms, or commits the session likesignInwhen email confirmation is off.SignedInnow carriesuser(the verified claims'UserClaims,nullafter sign-out), so an action needs nogetUser()call after signing in. -
better-supabase powersync streamsaccepts thememberships,teamsandprofilesinstances. Memberships syncs the user's own memberships and the organizations they belong to, teams syncs the user's teams and their members, and profiles syncs the user's own profile.better-supabase/powersyncaddspowersyncMembershipsTransport,powersyncTeamsTransportandpowersyncProfilesTransport, which answer the list and update functions from SQLite, andmembershipsRoute,teamsRoute,teamMembersRouteandprofilesRouteforcreateUploadConnector({ tables }), which replay local writes through the block functions. -
devices.checkReceipts()emits thenotification.deliveredandnotification.bouncedblock events for the receipts it records, with the same datarecordDeliveryEventemits (provider: "expo",providerEventId: "expo-receipt:<ticket id>"). Before, a push receipt reached the delivery history but nobetterSupabase.onhandler.createPushtakesevents,actorIdandcontextfor it. The push module moves to version 3:complete_push_receiptsreturns{ updated, events }instead of the ticket count, so runbetter-supabase upgradeand generate a migration. -
teams.list()returns each team'sdescription,status(activeorarchived, typedTeamStatus) andmemberIds, sorted by name, so an app can tell archived teams apart and show who is on a team without readingteam_membersitself.teams.update()returns the stored row, including a description it kept. Runbetter-supabase upgradeand generate a migration to pick up the newlist_teamsandupdate_team. -
InviteRequest,Organizations,OrganizationsOptionsandcreateOrganizationstake the role union as a type parameter (RoleNamefrom the generated blocks file, orRoleNames<typeof config>), soinvite({ role })andonAccept.rolesreject an unknown role at compile time.InvitationDraftandcreateInvitationsControllertake it too. The default staysstring, andonAccept.teamsstaysstring[]. -
Fixes three block SQL bugs found by running the Next.js example on the
catalogpermissions model.- Approval steps that name an approver role (
approvers: { role: "admin" }) now work underpermissions.model: "catalog". The approvals block compared the role key to the membership's role id, which raisedoperator does not exist: uuid = textwhen it notified approvers or checked who may decide. - Removing a member from an organization now also removes them from its teams. The teams block's
team_membersforeign key to the memberships table had noon delete, so deleting a membership of someone on a team failed. Runbetter-supabase upgradeand generate a migration to pick upon delete cascade. - Turning the teams
patchoption off again drops thecreate_teamoverload that takes aslug, as turning it on already dropped the one without. Before, a database could end up with both, and calls tocreate_teamfailed as ambiguous.
- Approval steps that name an approver role (
-
Ignore Next.js segment and middleware prefetches in
expectDbBudget, and count only visible matches forexpectInstant'sabsentlocators. -
better-supabase/testingno longer pulls@supabase/liteor@next/playwrightinto a Turbopack bundle. Both loaded through a specifier held in aconst, which Turbopack folds and resolves, so an app that importedseedTenantOnCreatefrominstrumentation.tsfailed to compile on@supabase/pg-delta. They now load through the same bundler-ignored import as the other optional peers.
0.30.0 (2026-10-26)
-
Blocks laid over your own tables now behave as they do on their own tables.
- Numbering: a block that numbers its own row (tasks, deals, quotes, invoices, donations) marks the number it took from
next_numberfor the transaction, so anumberingentity with atableaccepts it instead of refusing it withNUMBER_MANUAL, and the number is assigned once. - Rows: read functions of tasks, employees, hiring, pipelines, quotes and invoices return a row of your table keyed as on the block's table. A renamed column also comes back under the block's name (
tenant_idwhen the tenant column isorganization_id), and a mapped value as its label, so the TypeScript clients parse it. Bug fix:organizationIdand renamed fields used to read as missing. - Extra columns:
insertExtraColumnswrites every extra column in the insert, with the type'sdefaultfor a key the call leaves out, so a check across extra columns holds when the row is created. Tasks, quote, invoice and deal lines, employee contracts and private details, teams, tags, saved views, hiring jobs and calendars use it. add_employee_contractkeeps your contract table's currency default whenattrshas nocurrency.- Value maps:
blocks.<name>.valuesnow applies in the catalog, quotes, invoices, inventory, orders and shipments modules: status and kind literals in functions, policies and reads, with list values andnullfor a label your app lacks.products.kindand the status of stock reservations and transfers are typed columns. A quote whose map setsviewed: nullkeeps its status when the link is opened. - Calendar:
columns.rules.idmay benullfor a rules table keyed by its event, andoptions.ruleDialect(weekdays: "lower",monthDay: "scalar",ordinal: { weekday, position }) reads and writes structured rules in your table's shape.
Generated SQL changes only where these apply: blocks over your tables, a renamed tenant column, extra columns and numbered entities with a table.
- Numbering: a block that numbers its own row (tasks, deals, quotes, invoices, donations) marks the number it took from
-
createNextsigns users in and out on the server for every flow that starts or ends a session.verifyOtpverifies an email link'stoken_hashor an emailed code,authorizeUrlandexchangeCoderun OAuth with a PKCE verifier cookie (httpOnly,SameSite=Lax, 10 minutes, deleted on exchange),verifyMfacommits theaal2session, andsignOutends the session in Auth before it clears the cookies, forgets the verified session and expires the user's cache tags.signInWithPasswordis the same assignIn. Each returnsredirectTo(a same-originnextor the fallback) andmfa, plain data a Server Action can return to the client; the committed session is ongetRequestSession()andcontext()for the rest of the request.After a sign-in or sign-out,
getRequestSession(),session(),context()andcached()return the new session for the rest of the request. Reads rebuild the request from the cookie jar, so a Server Action sees its own writes, and a render that never commits still verifies its token once. Auth errors keep theirerror_codeascodeand no longer carry Auth's message, so a form can't reveal whether an account exists.cookieScopesoncreateNextalso expires the session cookie at old scopes on sign-out.Doctor's BS506 warns when an env file sets
SUPABASE_URLand a browser spelling such asNEXT_PUBLIC_SUPABASE_URLto different URLs, since the session cookie name comes from the URL and the server and the browser would then read different cookies. Setauth.cookie.nameon both clients when the split is intended.
0.29.0 (2026-10-26)
migrate schema-first,init --presetandadd --presettype a format column (email,url,rating,percent) as a domain in thebsbschema, such asbsb.email, and write the domains as files undersupabase/schemas/bsb. A column with its ownmin,maxoroptionskeeps its inline check. Rollups and lookups are written assecurity_invokerviews inpublic/views.gentypes a domain column as its base type.- Breaking: the config has no
tableskey, andrecordsis nowsubjects. Tables are SQL files you own undersupabase/schemas, with features as@bsbtags in the table comment. Runbetter-supabase migrate schema-firstonce to write the files from your oldtables, then deletetablesand renamerecordstosubjects; every other command refuses the old keys and says so.init --presetandadd --presetwrite a design's tables as SQL files and keep a file that exists, so the breaking-change report, rename statements and--allow-breakingflag (and theallow_breakingMCP argument) ofadd --presetare gone (db diffplans them).AppTableNames,TypedReferenceandhasFlatTablesare removed frombetter-supabase/config, andpresetConfigSourcereturns a config without the design's tables. Create's design format andbetter-supabase/create/litekeepappTables. See the 0.28 to 0.29 migration guide. - The App tables docs page describes tables as SQL in
supabase/schemaswith@bsbtags, and the Record grid recipe sets a field through the typed repository instead of theappTables.setbulk action. The CentraKit validation project declares its record types assubjecttags. - Repo tooling: an oxlint rule replaces the raw-policy test. No published change.
0.28.0 (2026-10-26)
better-supabase add <block> --over <schema.table>installs one block over a table you already have. It proposes thetablesandcolumnsmapping, reports what cannot map and writesblocks.<block>to the config, likeadd --adopt <block> --tables, and refuses to combine with those two flags.better-supabase db diffplans with pg-delta's library on a local pg-delta project. A rename becomes a rename only when a migration records-- bsb: rename old -> new, and a diff that drops tables or columns stops with acheck_failederror until you pass--allow-data-loss. The shadow database comes fromprovisionCoLocatedShadow, sopg_dump,psqlandBSB_PG_BINare no longer used. Install@supabase/pg-deltaand@supabase/pg-topo(optional peers) to use it. The Supabase CLI still runs for the migra workflow and remote databases.better-supabase initrecognizes a project that already has asupabasefolder: it prints the migrations, schema files and snapshot tables it found, says that the database is unchanged, and points atdoctorandtableas next steps. The new--fromflag starts a project from apostgres://URL, which writes the database's schema tosupabase/snapshot.json, or from a preset, design code, URL or file like--preset.- Tenant topics of
realtime-tables(bsb:t:<table>:<tenant>) are now received by members of that tenant at the time of the message, checked withmember_organization_ids(), instead of by whoever carries the tenant id in their token. A removed member stops receiving at once. Without themembershipsmodule tenant topics stay closed; unscoped and own-user topics are unchanged. The preset catalog is regenerated with it. migrate schema-firstkeeps the grants, comment and policies of a view in the view's own file, and leaves out adrop viewfor a view it writes.gennames the events of a table with aneventstag after itssubjecttag type, as the table's trigger does.
0.27.1 (2026-10-26)
- Block modules now emit every row level security policy as a typed
Policyvalue, so the installed SQL is laid out one clause per line. The policies, their names and their drops are unchanged, and a module that writescreate policyby hand now fails the test suite.
0.27.0 (2026-10-26)
-
Blocks over the app's own tables take more of their shapes, all opt-in:
pipelines: withstatus.follow, an insert that sets the status and no stage lands on the first active stage whose category maps to that status, instead of the first open stage overwriting the status.- A
mappablecolumn with avaluesentry, even{}, no longer counts as a text column the module writes, so an enum there passes the adoption check.employeesmapsemploymentTypethis way. hiringsaveJobwritesnot nullextra columns in the insert that creates the job.- Per-action keys with fallbacks:
taskspermissions.createandpermissions.delete, andoptions.authorCanDelete: false;employeespermissions.create,contractsRead,contractsWriteandprivateDetailsWrite;hiringpermissions.create,score,jobsCreateandjobsUpdate. employeescontracts:salaryandcurrencycan map tonull,options.salaryUnits: "major"reads and writes a major-unit salary column, andoptions.contractOverlap: "allow"adds an editable contract without the overlap check.employeesupdateaccepts the app statuses a value map lists after a label's first value, such asoffboarding.hiringwithoptions.stages: a move to an unmarked stage keeps a state that no stage marks, such as a rejection.- Entity rename errors name
blocks.<name>.names, the key the config takes.
-
gennow also reads thejson,encryptedandeventstable tags, andmigrate schema-firstwrites them.json meta=Typetypes a jsonb column (meta=import:module#Nameimports the type),encrypted ssn=bigintmarks a sealed column, andevents on="created, updated"lists the outbox events. A config key still wins over a tag. -
The CLI now reads
@bsbtable comments fromsupabase/schemasfor every command, soupgradeand doctor see the samesubject,realtime,vector-searchandjsonentries asgen. Thesubjecttag takesid,id-type,tenant,scope,cascade,deleted-at,search,search-title,search-body,search-description,search-exclude,rank,rank-group,versions,versions-autoandcan-<action>, andmigrate schema-firstwrites them.migrate schema-firstalso works whensupabase/sits above the project folder. A config key still wins over a tag.A new
servertable tag lists the columns signed-in users can't read (server notes), sogentypes them as not selectable once a table lives in your schema files;migrate schema-firstwrites it foraccess: "server"columns. -
Authorization templates are now checked by a tokenizer instead of regular expressions. A
;or--inside a string or quoted identifier no longer counts, and a tagged dollar quote ($tag$), a block comment, an unterminated string or a stray{is refused.genrefuses an unsafe template before it fills the placeholders.
0.26.0 (2026-10-26)
- Add
accessMatrixTeststobetter-supabase/create/lite. It turns the access matrix into one pgTAP file per persona, which you can write tosupabase/tests/databaseand run withsupabase test db. better-supabase/sqladdsparseBsbComment,formatBsbComment,setBsbTagandcommentOnTableSql, which read and write the@bsbfeature tags in a table comment (ADR 0102). Nothing reads them yet;genand thetablecommand follow.- A block over your own table no longer creates a plain index that one of your indexes, primary keys or unique constraints already covers with the same leading columns.
addandupgraderead those indexes from your schema files and the saved snapshot (ownIndexesin the module layout), andbetter-supabase/sqlexportsdeclaredIndexes. - The custom-fields keyed layout takes
options.rankType: "integer", which keepsrankin an integer column (or casts it to the type of the app's own rank column), andoptions.readAccess: "record", which makesread_field_valuescheck each record throughcan_subject(type, id, 'read')instead ofpermissions.readin the tenant. The keyed layout no longer reportspermissions.sensitiveto the authorization provider, since it keeps no sensitive values. A module can now name the actions a config never checks withunusedPermissions. - The
nonescope refuses anonymous sign-ins: its read checks andcanconditions require a user whoseis_anonymousclaim is not true. Runbetter-supabase upgradeand generate a migration (ADR 0104). better-supabase/createaddsgatePlanandparseRenameHints, which decide renames and block destructive actions in a migration plan shaped like pg-delta's (ADR 0106). Thedb diffwiring follows.blocks.messaging.onandblocks.comments.onkeep record conversations and comments to the record types they list.open_conversationrefuses another type withMESSAGING_SUBJECT_UNSUPPORTEDandcreate_commentwithCOMMENT_SUBJECT_UNSUPPORTED, so registering a type inconfig.recordsfor another block no longer opens conversations on it. Withouton, every registered type is allowed as before.- A
config.records.<type>.permissions.<action>entry takesalso, a permission key the caller must hold as well, in the row's tenant or on the record's scope:{ key, rows, also }asks for a row grant (or the key) and the tenant key both.can_subject,can_subject_forand the blocks' record read checks honour it. - Every table and sequence a block creates now revokes its privileges from
PUBLICas well asanonandauthenticated, and a block instance schema revokes default privileges for objects created later. Existing databases need no migration: the revokes are no-ops wherePUBLICholds no grant. genreads@bsbtable comment tags (ADR 0102):subject,realtimeandvector-searchon a table behave likesubjects,database.realtimeandvectorSearchentries, and a key the config sets itself wins.better-supabase migrate schema-firstwrites the tables thattables(the oldappTables) renders as files you own undersupabase/schemas, with the config's per-table features as tags. The config keys keep working in this release step; deletetablesafter running the command.config.records.<type>.search.watch[]takesthrough: [{ table, from, to }], which follows the watched row'skeyacross further tables, such as a junction table, before it reaches the record's id (or the record'sviacolumn). Renaming a tag can now re-index every record it is linked to.better-supabase table <table> enable|disable <feature>turns a per-table feature on or off by editing the@bsbtag in the table comment, in the schema file that creates the table (ADR 0102). It takes--dry-runand--check.better-supabase/sqlexportsTABLE_FEATURES,setTableFeatureand the helpers behind it.- The restrictive tenant scope is now one policy per command (
bsb_tenant_scope_select,_insert,_updateand_delete), eachto publicinstead ofto authenticated(ADR 0104). A permissive policy that reachesanonorpubliccan no longer read across organizations, and a branch one command grants no longer satisfies another. Policies that grantanonorpublicon a tenant table keep working because their conditions stay inside the matching scope policy.upgradedrops the oldfor allpolicy and writes the four new ones; runsupabase db schema declarative syncfor the migration. Breaking for apps that relied on an openanonorpublicpolicy on a tenant table without a condition the block knows about. better-supabase/create/liteaddsverifyFiles,verifyCatalog,verifyQuery,readSecurityCatalogandaccessMatrix. They check row level security, write policies that are onlytrue,anonandPUBLICgrants andsearch_pathon security definer functions, and report how faranonandauthenticatedreach per table and command (ADR 0105).- Billable time works with time tracking's per-type record columns (
blocks.time-tracking.on.<type>.column) and duration entries (endedAtmapped tonull): it reads an entry's record from its column, computes the end from the start andseconds, leaves running timers out, and locks the duration and running mark of a billed entry. employee_from_applicationworks over a hiring jobs table of your own: it compares an enum employment type by its text, maps it back throughblocks.hiring.values, and leaves the team or employment type empty when the jobs table has no column for it instead of failing to render.better-supabase/create/litenow exportscatalogQueryandreadCatalog, which the 0.22.0 notes forimportProjectalready named. Run the query yourself, pass its rows toreadCatalog, then pass the result todesignFromCatalog.- A block's
on.<type>entry for a typeconfig.recordsregisters inheritstableandidTypeeverywhere:add,upgrade,gen,sql --adoptand doctor now readconfig.recordstoo, so they no longer fail with "needs a table" where rendering already merged the entry. - Blocks that check a record's read permission (tags, attachments, share links, versions, relations and the other modules that take
on) now honour aconfig.records.<type>.permissions.readwithrowsorowner: the key, the provider's row grants and the owner column each grant the read, ascan_subjectdoes. Before, only the key counted as a tenant key, so{ key, rows }refused callers with a row grant (SHARE_SUBJECT_NOT_FOUNDand similar) and{ owner }checked nothing. - The memberships module lets
anonexecutemember_organization_idsandhas_organization_role. The restrictive tenant scope applies to every role, so an anonymous reader of a public table (a published storefront) hit "permission denied for function" before it reached the block's public policy. Foranonboth functions return no organizations and false. - A record type whose search reads
froma view now re-indexes on any update of the record's row, so renaming a record or setting its archived flag updates its search document. Before, only the id, tenant,deletedAtandurlcolumns were watched. blocks.share-links.tables.viewsandtables.statecan benullwhen the block manages its own tables too; before, only a block over the app's tables could leave them out.
0.25.0 (2026-10-26)
better-supabase initadds therls-guardblock to the config it writes, so row level security stays on for every table the project creates later. Remove'rls-guard'fromblocksto opt out (ADR 0104).
0.24.0 (2026-10-26)
-
The calendar block runs over an app's own calendar tables, with five opt-in options. A config without them renders the same SQL as before.
options.access: per-calendar access. Calendars get avisibility(sharedorprivate) and an owner, events avisibilityand an owner, andtables.grantsgives a membervieweroreditoraccess. Every write function checks the calendar or event it changes, the read policies hide private calendars and events from other members, and feeds and free/busy never show a private event's details.options.accessFunctionsnames app functions that decide instead. Client:setGrant,removeGrant,grants.options.userFeed: a share link whose subject is a user (calendar_user) serves every calendar that user can read as one feed (calendar_user_feed, clientuserFeed).options.rdatesadds anrdatescolumn of extra occurrence starts, andoptions.recurrence: "table"keeps rules and dates intables.rules(anrruletext column or structured columns) andtables.recurrenceDates. Saving, cancelling, splitting, importing and every read go through them.expandOccurrences,parseIcsandtoIcsread and writeRDATE.options.attendeeKey: "any": an attendee is a user, an email or a subject record, withorganizerandoptionalflags;set_calendar_attendee(event_id, attendee)updates or inserts without a unique constraint andremove_calendar_attendee(attendee_id)removes one (clientremoveAttendeeById). The old signatures keep working.options.calendarDetails: calendars getdescription,rankandisDefault,createCalendartakes them, andupdate_calendar(calendar_id, attrs)(clientupdateCalendar) changes them and recordscalendar.updated.
An owner column of another type, such as a
uuid, takesvalues.calendars.ownerId: {}, socreate_calendarcasts the owner to it. -
employeestakes three opt-in options for tables an app already has.options.name: "split"writesfirstNameandlastNameinstead of one name:createtakes them or splitsname,updatetakesfirstName,lastNameandname, and the full name is read from a mapped (generated)namecolumn, which is never written, or joined from the parts whennameis mapped tonull; the record title then falls back tofirstName.options.privateDetails: "flat"keeps the address and one emergency contact in plain columns (addressLine1,addressLine2,postalCode,city,region,country,emergencyName,emergencyPhone,emergencyRelation), written from those keys or the usualaddressobject andemergencyContactslist, and read back in that shape.options.contracts: "editable"addsupdate_employee_contractanddelete_employee_contract(clientupdateContractanddeleteContract). The private details'userandibancolumns can be mapped tonull, and a contract'ssalaryPeriodtakesvaluesfor an app enum. Without these settings the module renders as before. -
The hiring block runs over an applicant tracker's own tables.
columns.applications.candidateType: nullmakes every candidate anoptions.candidaterecord and writes the id as the column's own type, such as a uuid foreign key.options.stagestakes the app's table of stages per job, with boolean or keyed markers for hired, rejected and withdrawn stages, so the job is the pipeline andapplications.pipelinecan benull.tables.interviewerskeeps interviewers as junction rows,options.scorecardKey: "application"keeps one scorecard per reviewer per application,scorecards.recommendationcan benull, andtables.scorecardScoresstores criterion scores thatscore({ scores })writes anddetailreturns.options.hiringManager: "employee"takes an employee id, andemploymentType,sourceand interviewkindaccept value maps. A config without the new keys renders the same SQL. -
time-trackingtakeson.<type>.columnover your own entries table: a record type keeps its id in its own foreign key column (cast to the record'sidType), andsubject_typeandsubject_idcan be mapped tonullonce every type has one.options.owner: "employee"(withapprovals: falseand the employees block) keeps entries and timesheets per employee, so an employee without an account has timesheets: the timesheet key is the employee and the week,columns.timesheets.usercan benull,log_time,list_time_entries,get_timesheet,submit_timesheetandlist_timesheetstake anemployee_id, own entries and weeks are those of the caller's employee record, and rows and events carryemployeeId. The client takesemployeeIdonlog,list,timesheet,submitandtimesheets. Without these settings the module renders as before. -
Rendering blocks and running
doctororupgradeare faster again. The SQL scanner that finds policies and grants now copies untouched text in whole slices, so the actor guard's policy read no longer slows every render. -
rls-guardalso fires afteralter table, so a statement that disables row level security on a table outside the Supabase-managed schemas is undone straight away. Runbetter-supabase upgradeto refresh the module's data file (ADR 0104).
0.23.0 (2026-10-26)
- Blocks take
blocks.<name>.values.<table>.<column>, which maps each label a block writes or compares to the value your own column stores:{ cancelled: "canceled" }, several values for one label ({ started: ["in_progress", "on_hold"] }, the first is written), ornullfor a label the app does not support, which fails withVALUE_UNSUPPORTED. The map applies to writes, comparisons in functions, triggers and pipeline bindings, and to the typed fields read functions return. Tasks (state,closeReason, andpriorityonce mapped), calendar (status, andkind,transparency, attendeeroleandresponseonce mapped), employees (status) and hiring (state, jobstatus) apply it. A config withoutvaluesrenders the same SQL as before. commentsandmessaging: a record type that declares acommentaction inconfig.recordskeeps its comment threads on the record's own checks. Reading followscan_subject(type, id, 'read')without the tenant messaging read key, opening a thread and sending or editing a comment needcan_subject(..., 'comment'), and deleting others' comments takes the record'smoderateaction (when declared) or the tenant moderate key. Record types without acommentaction keep today's checks, so existing configs render as before.custom-fieldstakesoptions.layout: "keyed": each value row carries its field'skey,labelandtype, and its value in the column of that type (valueUrlandvalueEmailare new optional columns).set_field_value(tenant, subject_type, subject_id, key, label, type, value jsonb, rank, if_absent)upserts by record and key and clears the other value columns,read_field_valuesreturns typed rows, and the newdelete_field_value(value_id)recordsfield_value.deleted; the client gainssetField,readFieldsanddeleteValue. A record type can keep its id in its own column of the values table (on.<type>.column), sosubject_typeandsubject_idcan be mapped tonull. Every layout'sset_field_valuechecks the record'sfieldsaction whenconfig.recordsdeclares one. The normalized and inline layouts render as before.- More tables take the app's own columns:
blocks.calendar.options.calendarExtraColumns(written bycreate_calendar, returned bylist_calendars), andblocks.employees.options.privateDetailsExtraColumnsandcontractExtraColumns(written fromattrs.fieldsbysave_employee_private_detailsandadd_employee_contract).saved-viewswrites an extra column that isnot nullwithout adefaultinside the insert, as tags and teams do. Without the options the modules render as before. pipelines: a binding'sstatus.follow: truemoves a record to the first active stage whose category maps to a status written directly to its status column, so stage, history and time in stage stay right when app code writes the status (PIPELINE_STAGE_INVALIDwhen no active stage matches a mapped status).tasks:tables.checklistcan benullfor an app with its own subtasks, which drops the checklist table and functions and returnschecklist: null;prioritytakesvalues(the block's 0 to 4) for an app enum. Both render as before without the settings.better-supabase/sqlexports a typed policy builder and a policy rule DSL:policy,renderPolicy,readPolicies,readGrants,maskSql,rulePolicy,renderRulePolicy,readRulePolicies,renderRule,isRule,disallowedPolicyCalls,policyFunctionsSqlandPOLICY_FUNCTIONS, with thePolicyandRuletypes. A rule renders to a policy that calls onlybsb.is_member,bsb.can,bsb.ownsandbsb.uid, and reads back from the-- @bsb rulecomment above it.search: aconfig.records.<type>.searchentry takesdescription(returned on each hit asSearchHit.description),exclude(a column that keeps a row out of the index while it is set, separate fromdeletedAt),from(a view or table keyed by the record's id that the title, body, description and exclude columns read) andwatch(related tables whose changes re-index the record, directly or through aviacolumn). The index gains adescriptioncolumn only once a subject sets one, so existing configs render as before.share-linkschecks a record'sshareaction fromconfig.recordswhen its type declares one:create_share_linkneeds it on the record (as the caller, so per-row grants and owner columns count), andrevoke_share_linkandlist_share_linksneed it on top of the organization key unless the caller created the link.options.tokenHashadds a caller-madetoken_hashtocreate_share_linkand a non-consumingfind_share_link(token_hash);options.fullRowsmakeslist_share_linksreturn the tenant, subject, creator and creation time and takeinclude_revoked. The client gainscreateHashed,findand alistfilter. Without ashareaction and the options the module renders as before.config.records.<type>.permissions.<action>takes{ key, rows, owner }besides a key:rowsgrants the action on the rows of a provider resource the caller holdskeyon, through the newrowsWithprovider template (rowsWithForforcan_subject_for), andownergrants it to the user a uuid column names.can_subjectandcan_subject_forcheck every form. Blocks that act on a record ask the record's own action when its type declares one:tagschecks atagaction intaganduntag, andcustom-fieldsafieldsaction when it writes a value; a config that declares neither keeps its checks.tags:blocks.tags.permissionstakescreate,updateanddelete, each falling back tomanage. Withoptions.patch: true,create_tagtakes an optionalslug(checked against^[a-z0-9]+(-[a-z0-9]+)*$,TAG_SLUG_INVALID), andupdate_tagan optionalpatch jsonbthat setsname,slug,color,descriptionandkind, wherenullclearscolorordescription; the client'screateandupdatetake them. An extra column that isnot nullwithout adefaultis written inside the insert, socreatecan set it. Without the option the functions keep their signatures.teams:blocks.teams.permissionstakescreate,update,deleteandmembers, each falling back tomanage. Withoptions.patch: true,create_teamtakes an optionalslugandupdate_teaman optionalpatch jsonbthat setsname,sluganddescription(wherenullclears the description); the client'screateandupdatetake a trailing options object for them. Withoptions.restore: true, the newrestore_teammakes an archived team active again and recordsteam.restored, and the client'srestore(id)calls it. An extra column that isnot nullwithout adefaultis written inside the insert. Without the options the functions keep their signatures.time-tracking:options.approvals: falsedrops the approvals dependency; timesheets then keep astatuscolumn (open, submitted, approved, rejected) with optionaldecidedBy,decidedAtanddecisionNote, and members withtime_tracking.approvedecide throughapprove_timesheetand the newreject_timesheet(clientapproveandreject, eventtimesheet.rejected).options.userTimeZonestarts each member's week in the zone a column of yours holds, through a newtime_week(at, user_id). Over your own entries table, an entry can be a start and a duration (endedAt: null,secondsas the writable duration column,runningSinceas the running mark). Without these settings the module renders as before.
0.22.0 (2026-10-26)
better-supabase/create/liteaddsopenSandboxanddesignDataApi.openSandbox(project)applies a project's files to an in-memory PGlite database and offersas({ sub, role, claims })personas that run with row level security, plus arest(request)handler for a subset of PostgREST (table reads and writes, filters, order, limit, offset,rpc).designDataApi(preset, design)returns the OpenAPI 3.1 document of the Data API a design produces.validateDesignnow shares its file runner with the sandbox.importProjectinbetter-supabase/create/litereads an existing project into aDesignand a report. It takes a declarative schema or migrations folder (replayed in PGlite), any queryable database, or a Supabase project ref and access token (through the Management API read-only endpoint). The report lists what it modeled, what it kept as it is, the tables that belong to blocks, each table's adoption rung and the security findings.catalogQueryanddesignFromCatalogare exported for callers that run the query themselves.- One project pipeline for Create, the CLI and the cloud (ADR 0100).
better-supabase/createaddsloadProject,checkProjectand a singleIssuetype with aseverityand asource;checkDesign,designIssuesandvalidateDesignnow reportIssuevalues, and the twoDesignIssuetypes are gone (breaking: a lite issue hastableandfilewhere it hadmoduleandpath).previewFilestakesownTablesandownColumnsto render over tables the project already has.better-supabase/presetexports the instance rules the cloud copied:canAddInstance,blockRequires,instanceNameProblem,withInstance,withoutInstance,withEntityName,installedBlocks,presetKey,createQueryandpresetArgumentOf. RenameDesignIssuetoIssueand readissue.fileandissue.tablefor lite findings. - App table write policies now refuse a read-only support or agent session. The insert, update and delete policies that
appTablesrenders carry the sameactor_may_write()check as every block policy, and the SQL defines the function when the file needs it. Runupgradeand generate a migration to pick it up. - Doctor's BS345 check treats the
actor_may_write()support-session guard as tenant membership, so app tables that carry the guard no longer raise a false warning for attachment subjects.
0.21.0 (2026-10-25)
-
Blocks run over the app's own tables everywhere, block calls return a
Result, and Temporal values replace date strings. The upgrade guide is at From 0.20 to 0.21.Breaking:
db.$api(fn, args, options)returns anAsyncResultinstead of throwing. Call.orThrow()for the old behavior, or read.ok. It takes$rpcoptions (the newApiOptionstype), and areturnsschema validates and types the value.db.$apiResultfrom 0.19 is now a deprecated alias of$api.DbBlockSource.callis replaced byapi, the name of the API schema; the core calls it through$rpc.BlockSet.callreturns anAsyncResult, andBlockSet.apinames the API schema.- These fields are
Temporal.Instantinstead of strings: the argument ofreminders.markSent,DeliveryPayload.occurrenceAt,PlannedDelivery.occurrenceAt,Relation.createdAt,BulkRun.createdAtandfinishedAt, andIncomingWebhook.createdAtandlastReceivedAt. A bookings service's duration is aTemporal.Duration. - An app table a block runs over must have the columns that block calls need. Calls that need a missing column fail with a
*_UNSUPPORTEDerror, and a review reply without a reply column fails withREVIEW_INVALID. - The default SQL of several blocks changed: identities, queue and collections upsert
on conflictby columns, status columns are written explicitly, and the activitiesexternalRefindex exists only when the column is mapped. The line tables of quotes, invoices and deals get absb_<lines>_position_keyunique index and upsert by position. Runupgradeand generate a migration.
Added and fixed:
- Temporal values are encoded at any depth in function arguments,
queryRawparameters and block fields. AZonedDateTimeis sent as its instant, andDuration,PlainYearMonthandPlainMonthDayhave a wire form. - Every block table can be the app's own table, except the
workflow-sdkworld. Line tables take optional columns and an enumproductType. Idempotency, rate-limit, reserved-slugs, queue andaudit.registryhavenames.tables, and their default SQL quotes identifiers. - Tenant columns follow the config: state machine and numbering entities default to the
config.recordstenant, elseorganization_id(or its rename);history.tenantdefaults to the machine's tenant column; the tasks pipeline, doctor's subject check and the legacy upgrades follow a renamed tenant;genwrites renamed tenant columns and the middleware reads them back astenant_id. orderMetrics,timeTrackingMetricsanddriveSubjecttaketableandtenant; the workflow editor takestenantClaim; the SCIM sync log maps throughblocks.sso.tablesandcolumns.- Notifications deliver to adopted profiles whose locale column is an enum or a domain.
- The attachments trigger resets the scan state of client inserts into an app table. Adopted usage history is never partitioned and needs an increasing
bigintid. Adopted ledger balances keep the app's grants. - Render refuses two blocks that would create the same table, such as
blocks.idempotency.tables.leasesandblocks.leases.tables.leasesboth set tobetter_supabase.leases, and names both config keys.
-
blocks.<module>.apinow always writes a wrapper for every function the block's TypeScript client calls over a transport, also whenapi.functionslists fewer. With"rate-limit": { api: { schema: "api", functions: ["check_rate_limit"] } },checkAlloverrpcTransport(admin, { schema: "api" })failed with PGRST202 becauseapi.check_rate_limitswas missing; the module now writes it andapi.purge_rate_limits, with the samesecurity invokerbody andservice_rolegrant asapi.check_rate_limit. Runbetter-supabase addorupgradeto rewrite the module files.
0.20.0 (2026-10-25)
-
Block clients built from a
Dbget its Storage:db.<block>anddb.$blocks.<block>clients,blockSet.client(db, key)andcreateBlockClient(db, block)passdb.$storageto the block asstoragewhen theDbhas Storage, sodb.$blocks.attachments,db.$blocks.dataLifecycle, ai-files and drive read, sign and remove files as theDb's caller instead of failing without one. Astorageyou pass throughoptionsor.with({ storage })still wins.BlockContext,BlockClientOptionsandCreateBlocksOptionstakestorage, and the options.using(create)passes its creator hold it.
0.19.0 (2026-10-25)
-
Adopting existing app tables with blocks:
database.sql.tenantColumnnames the tenant column of every block table, such asorganization_id, instead oftenant_id. Explicitblocks.<name>.columns.<table>.tenantmappings still win, a name another column of a block table has is refused, andgenwrites the name to the block'snamesso its TypeScript client reads rows back withtenant_id.- The line tables of
quotes,invoicesanddeals(quote_lines,invoice_lines,deal_lines) can be the app's own tables, mapped throughtables.linesandcolumns.lines. The newoptions.lineExtraColumnsadds columns to the line table that each line'sfieldswrites and that line reads return underfields. defineSupabase(schema, { temporal }).blocks(...)passestemporalto every block instance it builds.db.$apiResult(fn, args)calls an API schema function likedb.$apiand returns aResultwith aDbError, like a repository call.db.$apiis unchanged.- Record types (
config.recordskeys,blocks.<name>.onkeys) may contain hyphens, such aspurchase-order, in every block. Subject type columns and checks accept them, and triggers named after a type use underscores (bsb_field_history_purchase_order), so two types that differ only by-and_are refused. Doctor BS346 no longer reports a hyphenated type thatconfig.recordsregisters.
0.18.3 (2026-10-25)
- With an authorization provider that sets
authorization.functions.actorMayWrite, the blocks replace calls tobetter_supabase.actor_may_write()with the provider's check but keep the function's owncreate function,grantandrevokestatements. The created-by block file no longer renderscreate or replace function (provider_check()), which failed with a syntax error.
0.18.2 (2026-10-25)
- The profiles block works over an app profiles table whose
localecolumn is an enum or a domain, such aspublic.app_locale.update_my_profilewrites the locale throughbetter_supabase.as_column_type, and a sign-up that maps a metadata key tolocalewrites it through the newbetter_supabase.try_column_type, which stores null for a value the type rejects instead of failing the sign-up.upgradeand doctor (BS342) no longer refuse an enumlocale, andadd --adoptno longer leaves it unmapped; they still refuse an enum in a column the block writes as text.
0.18.1 (2026-10-25)
-
relayRealtimeClientretries a first join that failed instead of leaving the channel dead until a reload, for example while a local Realtime service starts. Until the channel joins, each failed attempt reportsCHANNEL_ERRORand is retried with the exponential backoff up tomaxBackoffMs; anendevent before the join (upstream_error) goes through the same backoff instead of the fixedretry:loop.timeoutMs, now counted fromsubscribe(), caps this phase: the channel then reportsTIMED_OUTwith the status and problem detail of one final request, and stops.realtimeRelayno longer reports a check that can't run now as a denial. A throw fromauthorize, a policy check that can't reach Postgres and a session with anetworkorunexpectederror (such asJWKS_FETCH_FAILED) end the stream with the newunavailablereason, which the client retries; a send answers 503. Refusals keep their 400, 401, 403 or 404.better-supabase upgradealso renamesbs_event triggers, such as the audit block'sbs_audit_forget_dropped, so a full declarative diff no longer drops and recreates them.
0.18.0 (2026-10-25)
-
Close the gaps a production Expo, oRPC and MCP app hit on the blocks. See the 0.17 to 0.18 migration guide.
- Security:
team_ids_of(member)refuses a signed-in caller that names another user, andlist_memberschecks a keyblocks.organizations.permissions.listMemberscan remap. The profiles email mirror is stored lowercase, with a backfill. - The audit block takes
ipHeader,staffClaimandsubjectColumns. - The oRPC, Hono,
handle()and MCP middleware takecookies: falsefor bearer tokens and API keys only. oRPC contexts acceptheadersandurl. blocks.memberships.options.roles.manylets a member hold several roles (memberships version 3), withaddMemberRoleandremoveMemberRole, and invitations takedefaultRoleandonAccept.- Notifications (version 9) render per delivery and per locale, and take
actionsandresolve({ resolution }). Push (version 2) retries Expo sends, stores tickets and records receipts withdevices.checkReceipts(). Profiles gain alocalecolumn;add --adoptleaves it unmapped when the app'slocalecolumn is an enum. - Attachments take
offline: client ids, an upload trigger, a cleanup queue withcreateAttachmentSweeper, and an{ext}path placeholder. - PowerSync:
better-supabase powersync streamsandgen.powersyncwrite the Sync Streams and the publication migration for notifications and attachments.better-supabase/powersyncaddspowersyncNotificationsTransport,notificationRecipientsRoute,powersyncTopicPortandattachmentQueueRoute, andgenmarks the other block instances as needing the network on native. - Every block types
extraColumns, and memberships, organizations and teams type their nested options. Column types accept quoted defaults and casts. acceptInvitationByIdanddeclineInvitationByIdemitinvitation.acceptedandinvitation.declined. The access-requests approve key is in the typed permission registry, and doctor BS409 comparestokenHook.activeOrganizationFromwithblocks.permissions.activeTenant.
- Security:
0.17.0 (2026-10-25)
-
Add
ownTablePoliciesto keep blocks' policies off your own tables. Setdatabase.sql.ownTablePolicies: "app"for every block, orblocks.<name>.ownTablePoliciesfor one, which wins. Withapp, a block that runs over a table your schema creates adds none of itsbsb_<table>_<command>policies there, even where none of your policies repeats its condition, and no restrictivebsb_tenant_scopeeither, so your policies alone decide who reaches the rows (a platform permission that reads across organizations keeps working). It still writes its functions, triggers, indexes and grants. Its file keeps thedrop policy if existsand a comment that your policies govern the table, soupgraderemoves the copies an earlier install left. The default,block, keeps the behaviour since 0.15, andadd --adoptsuggestsappwhen an adopted table already has permissive policies of its own. Doctor skips such tables in BS347, and the new BS350 (info) reports one with row level security on but no permissive policy for a command the block's policies would have granted.The
organizationsblock adds itsstripe_customer_id text uniquecolumn only when the entitlements block reads the Stripe customer from it: not with aplansorcustomsource, a configuredauth.entitlements.customeron another column, or the managedbillingblock's customers table. Otherwise the column leaves the block's file onupgrade: on a managed organizations table the next declarative schema diff drops the column and its data, andstripeCustomerIdleaves the generated models. If your app reads or writes that column, declare it in your own schema file, or setauth.entitlements.customerto it (better_supabase.organizations.stripe_customer_idfor the managed table), which keeps the block adding it, before you runupgradeand the diff.When tenant and platform invitations share one table (
blocks.invitations.tables.platformInvitationsnames the tenant table), the platform invitations' open-email unique index is limited to rows without a tenant, so a person can hold open invitations to several organizations at once. The block's file drops the oldplatform_invitations_open_email_idxand createsinvitations_platform_open_email_idxin its place.Add
options.stampto theupdated-atandcreated-byblocks:client(the default) keeps stampingcreatedAt,updatedAt,createdByandupdatedByin the repository, andtriggerleaves them to thetrack_updated_atandtrack_actortriggers, so tables with column-level grants that leave those columns out accept the app's writes.genpasses it toupdatedAtExtension({ stamp })andcreatedByExtension({ stamp }), which still mark the columns read-only and refuse caller-supplied values without{ override: true }.The filter form
update({ where }, patch, args)acceptsoverridein its types, as the runtime already did.
0.16.0 (2026-10-25)
-
Realtime, session checks and uploads for apps that keep the session out of the browser, and atomic multi-limit rate limiting.
realtimeRelay(server, { topics, postgres })frombetter-supabase/serverserves Realtime to callers without a browser token of their own, such as a support session ("view as user") or an app with httpOnly session cookies. It checks each topic'srealtime.messagespolicies as the caller (the viewed user in a support session), joins upstream with the secret key and streams broadcasts and presence as server-sent events, with heartbeats, reconnects, session expiry and an overflow limit.POSTbroadcasts for the caller and is refused in a read-only support session.liveRelayTopicserves theliveQuerychannels, andrealtimeTopicAccessruns the policy check on its own.relayRealtimeClient(url)andrelayTopicPort(url)frombetter-supabase/realtimeare the client:defineTopic(...).subscribe,send,liveQuery,watchTopicand the hooks take it unchanged.<BetterSupabaseProvider realtime={...}>makesuseBroadcast,usePresence,useLiveQueryanduseLiveCountjoin through it, anduseRealtimeRelay(url)returns one whileuseSupportSession()reports a support session. The hooks'clientoptions now take anyRealtimeClient.sessionStatusRoute(server)frombetter-supabase/serveranduseSessionWatch()(plus the framework-freewatchSession()) frombetter-supabase/next/clientwatch an open page without a browser Supabase client: on focus, visibility and an interval they report an ended, banned or signed-out session and a changed claims fingerprint (support target included), and tell the other tabs through aBroadcastChannel.claimsFingerprint()computes the fingerprint on the server.bucket.reserveResumable(target, { upsert, direct })signs a resumable (TUS) upload and returnstusEndpoint,headers(x-signature,x-upsert),metadata,bucketandexpiresAt. The endpoint is<storage>/upload/resumable/sign, on the direct<project-ref>.storage.supabase.cohost for hosted projects;resumableEndpoint(url)builds it on its own.claimReservedand support-session checks work as forreserve.createRateLimit().checkAll([{ scope, key, rule }, ...])counts one hit against several limits in one round trip through the newcheck_rate_limits(hits)function of therate-limitmodule. The hit counts only when every limit allows it, and the decision names the limit that blocked and the longestretryAfter. Runbetter-supabase upgradeto add the function.
0.15.1 (2026-10-25)
- A block runs over a view of yours again, as
ownership: "adopt"did in 0.14. When your schema files or the snapshot create a view or materialized view at a block table's name (its default name, or the oneblocks.<name>.tablesmaps), the block writes no table DDL for it: nocreate table, added columns, constraints, indexes, row level security, grants or policies. It still writes the functions that read the view. An optional column the view lacks counts as mapped tonull, and a required one stopsupgradewith an error that names the view and the column. A view at the name of a table only the block keeps is still an error. Doctor reports a block whose API writes through a view Postgres can't update (BS349).organization_member_rolenow leaves out disabled memberships, like the other membership checks.better-supabase/sqlexportsdeclaredViewsandadoptedViews. codemod 0.15no longer leaves a script running the same command twice. It rewrites bothsql syncandsql upgradetoupgrade, so apackage.jsonscript or a workflowrun:step that called both now callsupgradeonce. Only identical commands next to each other and joined by&&collapse.codemod 0.15lists the lines of your own SQL that name abs_object the upgrade migration renames tobsb_: your pgTAP tests (sql.testsDir), the schema files no block wrote, and your newest migration. Each line shows under "Check these by hand" with its file and line. The codemod never rewrites SQL, since a migration you pushed must not change.better-supabase/serverexportsPERMISSION_CAP_CLAIM(bsb_permission_cap), the claim anauthorization.automation.runAshook puts the permission cap under. Through 0.15,cap_allowsandpermissionCapOfalso read the 0.14 name,bs_permission_cap, when the new claim is missing, so a hook or a queued job that still carries the old name keeps its cap instead of running uncapped.runAswarns once when it gets only the old name.
0.15.0 (2026-10-24)
-
Framework adapters now come in two tiers. Next.js, Hono, Expo Router, SvelteKit, TanStack Start and React Router are supported adapters: they get the full test matrix, an example app and every new guide. Astro, Edge Functions, Elysia, H3, Nuxt and Nitro 2 (
better-supabase/h3/v1), NestJS, Node and SolidStart are community adapters: they keep shipping in every release with a smoke test that serves a request, and their docs pages carry a community note. No adapter is removed and no import changes. Read more under adapter tiers and in ADR 0094. -
Blocks declare what they give
approvals,bulk,pipelines,share-linksandsubjectsin a newcontributesfield, and those generic blocks no longer name their consumers. A second instance contributes to the generic instance itsusesnames. Two contributions with the same subject or action name fail at render. Runbetter-supabase upgradeanddb diff; the rendered functions change only in the order of their branches. -
Block clients are keyed by instance.
genwrites ablocks.generated.tsentry for every instance, with the block it installs, itsusesand the function names its SQL writes, plus a renamed client such asticketsBlock.createBlocksreads the entry under the instance key, binds a port that two blocks provide through the consumer'susesor the newportsoption, andcreateBlockClienttakesinstance. Block queries use the table key space["bsb", instance, method, ...args], soinvalidateTablesmakes table and instance queries stale, optionally narrowed to methods. -
Blocks that attach to records take their record types from
onon the block entry instead ofoptions.subjects, andfield-historytakeson: { <type>: { fields: [...] } }.better-supabase upgrademoves the value. A config that still setsoptions.subjectsfails with the key to move, and the new doctor check BS346 reports anonentry thatconfig.recordsdoesn't register. -
Breaking: 26 blocks take plain names. The block name changes in the config, the CLI, the subpath (
better-supabase/blocks/<name>), the exports, the operation names (<block>.<action>) and the CloudEvent source (better-supabase/<block>). Table names, permission keys, event types, hint codes and queue names don't change.better-supabase codemod 0.15renames the config keys, the imports and the subpaths, and lists event sources for review.better-supabase upgrademoves the installed blocks to their new names and renames two tables that clashed: hiring'sjobsbecomesjob_openingsand catalog'scollectionsbecomesproduct_collections. A 0.14 name in the config stopsaddandgenwith a message that names the codemod.0.14 0.15 work-itemstaskspartiescontactsengagementsactivitiestargetsgoalsnumber-sequencesnumberingactorcreated-byensure-rlsrls-guardshared-signalssecurity-eventsservice-principalsservice-accountssupport-sessionsimpersonationcontrolscomplianceai-tasksai-schedulesai-providersai-keysworkflow-builderworkflow-editorjobsqueueaccesspermissionsrulesautomationstenantmembershipsactivitytimelineworkflow-sdk-worldworkflow-sdkThe docs pages move with their blocks, and
/docs/blocks/<old>redirects to the new page. -
Breaking: the SQL engine says block.
SqlModuleisBlockSql,ModuleDefinitionisBlockSqlDefinition, and the otherModule*types frombetter-supabase/sqlareBlockSql*(BlockSqlContext,BlockSqlLayout,BlockSqlNames).renderModules,resolveModules,resolveModule,isModuleIdType,sameModuleFile,InstalledModuleandSkippedModulearerenderBlocks,resolveBlocks,resolveBlock,isBlockSqlIdType,sameBlockFile,InstalledBlockandSkippedBlock.Four exports take their glossary names:
SubjectRefisRecordRef,entityFormisrecordForm(withuseRecordFormand theRecordForm*types),ShipmentCarrierisShippingProvider(testShippingProvider), andQueueBackendisQueueProvider(sqlQueueProvider,transportQueueProvider,vercelQueueProvider,testQueueProvider).better-supabase codemod 0.15renames these imports.Installed versions live in
better_supabase.blocksinstead ofbetter_supabase.modules.sql upgradecreates the new table and copies the rows before the schema diff drops the old one, and doctor reads the old table while the new one is missing. Block files carry-- @bsb-block,-- @bsb-block-data,-- @bsb-block-test,-- @bsb-namesand-- @bsb-tableslines;sql upgrade,sql syncand doctor read the@bs-*lines of files written by 0.14 and older. -
Breaking: the runtime instance is
bsb, matching the CLI's short name, soconst db = await bsb.db()replacesbs.db()in the docs, skills, examples, generated files and thectx.bsbkey on request contexts (c.var.bsb,locals.bsb,context.bsb). Runbetter-supabase codemod 0.15to rename the instance where a file creates, imports or destructures it; it lists cache tags and query keys that start withbsfor review.Strings on the wire move with it, so deploy the new package and run
better-supabase sql upgradetogether: realtime topics start withbsb:t:, the request and job headers arex-bsb-actor,x-bsb-jobandx-bsb-signature, workflow run attributes arebsb.*, the debug header isx-bsb-db-calls, the stats route is/api/bsb-stats, and Server-Timing names arebsb-proxyandbsb-verify. Workflow runs started before the upgrade keep theirbs.*attributes, so failure alerts don't count them. The support session cookie isbsb-supportand the replica cookie isbsb-primary-until, so staff in a support session start it again after the deploy.The triggers, policies, constraints, indexes and functions the blocks install are named
bsb_instead ofbs_(bsb_audit,bsb_session_active,bsb_json_<table>_<column>).sql upgraderenames the installedbs_objects in place before it applies the new block files, so nothing is created twice; an object on a table the migration role doesn't own (auth.users,storage.objects,realtime.messages) gets a warning naming the rename to do by hand. Doctor and the error mapper read both prefixes.Stored names keep
bs, because renaming them would orphan existing data: Vault secret names (bs:field-key:,bs:cred:,bs:signing:,bs:marketplace:), the queue envelope key$bsand the API key prefixbs, which existing keys are verified against. -
Breaking: the CLI has one command per job:
init,add,remove,upgrade,blocks,gen,dev,db,doctor,config,spec,scaffold,mcp,codemod,skillsandcompletion. Running a moved command exits 2 and names the new one, andbetter-supabase codemod 0.15rewrites the calls inpackage.jsonscripts and GitHub workflows.0.14 0.15 apply --preset <p>add --preset <p>adopt <block>add --adopt <block>sql add <block>add <block>sql sync,sql upgradeupgradesql dataadd --adoptsql listblocks list --installedsql print <block>blocks view <block> --sqlpreset decode <code>blocks list --preset <code>preset infoconfig --presetintrospectgen --save-snapshotseeddb seedenv,run,keys,stackdev env,dev run,dev keys,dev stackremove <block...>is new: it takes blocks out of the config andlib/blocks.ts, deletes their module files and points todb difffor the migration that drops their tables.add --adopt --checkexits 1 when the data migration is out of date, and a comment-only change to a data file no longer needs a new data migration. The MCP tools follow the commands:config_preset,blocks_installed,add_preset_dry_run,upgrade,add_presetandremove. The CLI docs move to/docs/cli/dev(env, run, keys and stack),/docs/cli/db#seedand/docs/cli/gen#saving-a-snapshot; the old pages redirect. -
Block instances live on
db..blocks(blockSet)on the definition puts each instance on the repository object (db.comments), running through the same executor as the tables and acting in the active organization. An instance whose name a table already uses stays atdb.$blocks.<instance>, anddb.$api(fn, args)calls a function in the API schema.blocks.generated.tsexportsblocks, the block for each instance, sodefineBlocks(blockConfig, blocks)lists them all.gen.hookswriteshooks.tswith a list and a record hook per table (useCustomers,useCustomer) for React, Vue, Svelte or Solid, built ondefineDataHooks. The hooks share reads, update cached rows at once oncreate,updateanddelete, and roll back on an error. They keep reads in memory by default;createClient(definition, { engine: queryEngine(queryClient) })frombetter-supabase/querykeeps them in TanStack Query.The
requireTenantoption and helper are nowrequireOrganization. Runbetter-supabase codemod 0.15to rename them; doctor reports arequireTenantthat is left. -
Blocks stop copying tables other blocks own. Leases drops its maintenance requests (install a
tasksinstance namedmaintenance_requestinstead; the upgrade renames the old table tomaintenance_requests_legacy), admission pass credits post on the ledger, inventory can keep stock at the assets locations withtables: { locations: null }, and donations requiresnumberingand contributes adonation_receiptsequence (R-{n}) that an app entry replaces. Blocks contribute numbering defaults throughcontributes.numbering. A renamed instance now reaches notifications and the queue under their own names, andgennames its events type after the instance (MaintenanceEvents) and adds it toBlockEvents. -
Breaking:
better-supabase.config.tsgroups its keys intodatabase(source,schemas,sql,seed,expose,buckets,realtime,topics,vectorSearch),auth(organization,claims,authorization,entitlements),gen(output,casing, the generatortablesoverrides and the other type options),api(openapi,specs) andtooling(doctor,env,keys,skills,scaffold).preset,blocks,plugins,records,tablesandadaptersstay at the top level.0.14 0.15 subjectsrecordsappTablestablesappTables.<name>.scopetables.<name>.ownerintegrationsadapterssql.scopedatabase.sql.ownerclaims.tenantauth.organization.claimplugins.tenant.columnauth.organization.columnblocks.<name>.modeblocks.<name>.ownershipblocks.<name>.scopeblocks.<name>.ownerblocks.<name>.entitiesblocks.<name>.namesblocks.<name>.hooksblocks.<name>.callbacksbetter-supabase codemod 0.15regroups a config file, its environment blocks and abetter-supabase.config.json. Loading a config with a 0.14 key fails with a message that names the key's new place.resolveConfigreturns the same resolved config as before, andflattenConfig,groupConfigandblockEntrySourcefrombetter-supabase/configconvert between the two shapes.initandaddwrite the grouped keys, and CLI and doctor messages name the grouped paths. Doctor finding targets keep their 0.14 names, so saved baselines still match. Create designs keepappTablesandscopein this release. -
Blocks install as instances. Each key in
blocksnames an instance; a key other than a block's name installs a second instance of the block in itsblocksetting,onlists the record types an attachable block attaches to, andusespicks the instance of a dependency. The options of a named instance are typed from its block.resolveConfigreports unknown blocks, renamed or repeated core blocks, unknownuseskeys and a missingusestogether, andResolvedConfig.instanceslists the resolved instances. The config JSON schema accepts instance keys. -
Repositories and block clients share one data contract. Reads are
list,page,get,countandaggregate; writes arecreate,update,upsertanddelete;attachanddetachlink a row to a record.findMany,findFirst,findOnly,findUnique,findById,paginate,existsand the*Manymethods go:gettakes a primary key, a unique key or{ where }(with{ optional: true }for null),createandupserttake one row or an array, andupdateanddeletetake a key or{ where }.Block clients move to the same verbs.
tags.taganduntagbecomeattachanddetach,tags.create,updateandlisttake objects,forSubject(record)on tags, channels and scores becomeslist({ on: record }), andsaveon the block clients andseton ai-cache and ai-filesproviderFilesbecomeupsert. The lint rulesno-unbounded-find-manyandno-delete-many-without-wherebecomeno-unbounded-listandno-empty-where, and the guardsnoUnboundedFindManyandnoDeleteManyWithoutWherebecomenoUnboundedListandnoDeleteWithoutWhere.Run
better-supabase codemod 0.15to rewrite the repository calls, the guard options and the lint rule names. It lists the block client calls to review. -
better-supabase db backfill <table.column>fills the null values of a column that a migration added to a table that already holds rows.--from projects.organization_id via project_idcopies each value from the table a foreign key points at, and--value "'EUR'"writes one literal. It updates--batch-sizerows per statement (default 1000) and locks only those rows, prints a line per batch, supports--dry-runand the--jsonenvelope, and touches only null rows, so a second run fills nothing. Read more under db backfill.doctoradds BS236, which reports a check addednot validthat no row fails any more, and the newdoctor --fixflag runsalter table ... validate constraintfor it. Against a database that is not local, an agent asks for consent first. JSON findings that--fixcan resolve carry the SQL in a new optionalfixfield.The migration lock lints now follow expand and contract. BS230 flags a
referencesorcheckwritten inline inadd column, BS231 flagsadd column ... not nullwithout a default, and BS233 no longer asks forlock_timeoutbefore a statement that only runsvalidate constraint. -
Breaking: designs replace preset codes. The config's
presetkey takes a preset name or an object with the conventions that differ from the defaults and the blocks, a Create URL is/create?preset=<name>or/create?design=<code>with the preset inside the design (format 7), and a design file is the design JSON with its preset.init,addandblocks liststop on a 0.14 code and namebetter-supabase codemod 0.15, which converts the config's code and*.design.jsonfiles.0.14 0.15 encodePreset(preset)presetSpec(preset)orcreateUrl(resolved)decodePreset(code)presetAndDesignOf(input)orpresetOfSpec(value)defaultPresetCode()defaultPreset()withPresetField(preset, key, value)presetFromSpec({ ...presetSpec(preset), key: value })designConfigSource(resolved, design, code)presetConfigSource(resolved, design)(async)designInstallCommand(resolved, code)presetInstallCommand(resolved, design)(async)designApplyCommand(resolved, code)presetApplyCommand(resolved, design)(async)isPresetCode,PRESET_BLOCKS,PRESET_FIELDS,PRESET_VERSIONandDecodedPresetare removed;CONVENTION_FIELDSlists the convention fields. The docs page/docs/presets/codesmoves to/docs/presets/designs. -
A
tables.<name>entry can now name a table your own schema already creates. Instead of refusing it, better-supabase enriches the table: it skipscreate tableand adds only the columns the table lacks (the scope column, the timestamps, the id when it has none, and the columns you list) withalter table ... add column if not exists, nullable unless they have a default. Enriching never overwrites what your schema wrote: the scope's policies are namedbsb_<table>_<command>on your table, so a policy of yours named<table>_selectstays, and your grants stay too, since the entry only adds the grants its scope needs. The scope column gets anot validnot-null check, so new rows must fill it whilebetter-supabase db backfillfills the old ones. Row level security, the scope's grants and policies, the restrictivebsb_tenant_scopepolicy, subject permissions, events, theupdated_attrigger, versions, read audits, rollups and lookups render the same as for a table it creates. Each feature works on its own, soscope: "none"with onlysubjector onlyeventsadds no scope column.Doctor adds two checks. BS237 reports permissive policies of your own on a scoped app table (a hint when
bsb_tenant_scopenarrows them, a warning inuserscope) and the grants on an enriched table beyond its scope (a warning when they reach columns the entry restricts). BS238 counts the rows of an enriched table without an owner and names thedb backfillcommand. BS228 no longer reports a required column without a default that an enriched table keeps nullable.genfilters a table on the tenant column its subject names (subjects.<type>.tenant), so a block over your table with its own tenant column gets the memberships filter too. -
Every block that owns tables now declares the nouns it names its tables, indexes, policies, triggers, functions and events after, so
blocks.<name>.entitiesrenames them. That covers 43 more blocks, among themquotes,invoices,orders,inventory,bookings,forms,pipelines,hiring,ai-chat,knowledge,agents,teams,tags,templatesandautomations. Quotes, invoices, orders, bookings and forms are also record types, so comments, attachments, tags and activity can point at them.Run
better-supabase upgradeafter updating. The new record types widen the subject switches in the blocks that read record titles, and three internal keys move: the orders advisory lock key, the relations lock key and thebetter_supabase.restoring_versionsetting thatversionssets while it restores a row.A config that declares
records.quote,records.invoice,records.order,records.bookingorrecords.formnow fails. Remove the entry when it points at the block's own table, or setblocks.<name>.names.<noun>.subjecttofalseto keep a table of your own. -
The per-block framework subpaths go:
better-supabase/blocks/<block>/react,/vue,/svelteand/solid(120 subpaths) andbetter-supabase/chat-sdk/react. A block's React hooks are now a registry item that shadcn copies into the app:npx shadcn add @better-supabase/use-<block>writeshooks/use-<block>.ts, with the same hook names, options and return values, and the app imports from@/hooks/use-<block>. Presets install the hook item with each block.Vue, Svelte and Solid call
useBlockController(create<Name>Controller, options)frombetter-supabase/vue,better-supabase/svelteorbetter-supabase/solid, with the controller from the block's main entry. It returns what the per-block hooks returned.better-supabase/reactnow exportsuseController,useLatest,useBlockEnvanduseBlockTenantfor your own hooks, andbetter-supabase/blocksexportsenvBlockOptions,envBlockSettingsand theBlockEnvtype.Doctor's BS418 finds imports of the removed subpaths and names the registry item.
-
Sessions verify once per request across cache scopes, and the Next.js proxy and sign-in take fewer round trips.
createServerkeeps a session memo keyed by the token's hash.server.snapshot(request)returns a verifiedSessionSnapshot, andserver.contextFromSession(snapshot)builds a context from it with no cookie read, no network call and no second verification. In Next.js,bsb.getRequestSession()returns the snapshot, so ten'use cache: private'islands verify the token once.sessionCacheKey,sessionIdTag,sessionMemoandbsb.sessions.stats()are new;createNext(..., { sessions })sizes the memo or turns it off. See the island pattern and ADR 0095.contextFromSessionaccepts only a snapshot the server made: a copy (a spread,structuredClone, a cached function's arguments) gets theinvalidcontext. Pass plain values into cached functions.- The proxy refreshes a token only within
refreshSkewSecondsof its expiry (auth.leeway, else 60), stores a refreshed session in the memo, and treatsrefresh_token_already_usedasraced: it keeps the cookies the other request set instead of signing the user out. serverTiming: truenow reportsbsb-authfor resolving the session andbsb-parse,bsb-verify,bsb-refreshandbsb-endedper phase.bsb-verifyused to be the whole resolution; readbsb-authfor that number now.isPrefetchalso recognizesnext-router-segment-prefetch,x-middleware-prefetchandx-moz: prefetch. Expo'sbsb.middleware()and API routes no longer refresh on a prefetch, like the other adapters.bsb.signIn({ email, password, next })signs in from a Server Action in one Auth call, writes the cookies, stores the session for the next render and returns a same-originredirectTo(andmfa), so the form callsrouter.replaceonce.safeRedirectPathandpasswordGrantare exported frombetter-supabase/server.AuthSessionandSessionSnapshotgainissuedAt(fromiat) andauthzVersion(from anauthz_verclaim, ornull).createServer(def, { versions })takes an authorization library's version cache. Authorizers get{ versions, memo }as a runtime,invalidateSession(userId)evicts the user from it, andsubscribeAuthzVersions({ client, topic, event, userIdKey, versions })evicts users when the database broadcasts a change on a private Realtime channel. See the version cache and ADR 0096.- SvelteKit, TanStack Start, React Router, Hono (
c.var.snapshot) and Expo hand loaders and handlers the snapshot.
-
Installed blocks now work together where they overlap.
ai-chatrecords each run's tokens on theai.input_tokensandai.output_tokensmeters whenusageis installed (turn it off withmeterUsage: false).knowledgequeues ingestion throughqueue(ingest.queueandingestJob()). Withinvoicesinstalled, a paid order creates, issues and pays an invoice and returns its id. Quote lines that name a catalog variant take its price and title when they leave them out. Time entries and leave requests carry anemployee_idwhenemployeesis installed.attachmentstakes apublicBucketsoption andAttachments.publicUrl()for files anyone may read. The registry adds@better-supabase/ai-chat-next, the AI chat route with its stream and stop routes. -
PowerSync, SQLite and TanStack DB run as engines behind the generated data hooks.
powersyncEngine(powersync, { connector, local })frombetter-supabase/powersync,sqliteEngine(database)from the newbetter-supabase/sqlite(Expo SQLite throughexpoSqliteDatabase, Supabase Lite throughliteDatabase) andtanstackDbEngine({ collections })frombetter-supabase/tanstack-dbgo tocreateClientorcreateNativeClient, so native screens readuseCustomers(...)like web screens. With a device engine,bsb.dbruns on the local database for the tables inlocaland on PostgREST for the rest.useSyncStatus()anduseConflicts()move tobetter-supabase/reactand read the engine.memoryEngineandqueryEnginetakelive, a change feed such asrealtimeChanges(betterSupabase, supabase)frombetter-supabase/realtime, andtablesto map a hook name to its tables.whereon every hook and repository takes a filter tree from a list query or saved view, checked against the filterable columns.Breaking:
better-supabase/powersync/react(useWatch),better-supabase/expo-sqlite(expoSqliteExecutor) andbetter-supabase/tanstack-db/supabase(supabaseCollection) are removed, along withwatchandsqliteTables, and@supabase-labs/tanstack-dbis no longer a peer. Doctor reports what is left as BS418. See the 0.14 to 0.15 guide. -
defineApipublishes every table and every block instance by default. Withoutresources, each table gets its CRUD operations; a map now publishes only the tables it names, andresources: falsepublishes none. Each table also gets the contract verbspage,count,aggregateandupsertasPOST /<table>/<verb>(operation ids such ascountCustomers), served bydefineResource,bsb.resourceandbsb.resourcestoo;verbslimits them, and a write hook dropsupsert. Each block instance getsPOST /<instance>/<method>per client method, configured with the newblocksoption (verbs,path,tag,permissions).createOrpc(betterSupabase).router(api, { guard, meta })serves that model as oRPC procedures, with routes that match the document.bsb.blockRouteris removed: servebsb.router(defineApi(betterSupabase, options))instead. Doctor reports BS418 for ablockRoutercall that is left. -
One automation model. Automations, workflow action steps and sequence action steps run actions from one registry:
defineActiondeclares an action (apiVersion: 1, with an optional config schema) andcreateActionRegistrycollects them;createRuleDispatchertakes{ actions }instead ofhandlers. The action hints are nowACTION_UNKNOWNandACTION_CONFIG_INVALID.better-supabase/flowsis removed. Blocks ship default automations instead: the inbox opens a task for each new conversation, hiring preboards each hired candidate and quotes orders each accepted quote (turned off). Each organization gets its own copy, which it may turn off, edit or reset withresetDefault. The conversions are actions of the target block (taskFromConversationAction,employeeFromApplicationAction,orderFromQuoteAction).createRuleSinkfalls back toeventTarget(event)whenloadreturns nothing.Workflow definitions lose their event triggers (
triggers.onEvent,builder.sink()); an automation'sworkflowaction starts them. Block timers (SLA checks, sequence waits, AI schedules, workflow schedules) run on the queue throughblockSchedulesandblockTickHandler. Doctor BS418 names each removed API and its replacement. -
better-supabase/specis the one entry for API documents. It exports the OpenAPI, AsyncAPI, Arazzo and Overlay renderers (createOpenApi,createAsyncApi,createArazzo,defineWorkflow,applyOverlays,defineOverlayand the rest) next todefineApi. The subpathsbetter-supabase/openapi,better-supabase/asyncapi,better-supabase/arazzoandbetter-supabase/overlayare removed: import the same names frombetter-supabase/spec.better-supabase codemod 0.15rewrites the imports, and doctor reports BS418 for any that are left. -
Breaking:
ownership: "adopt"is removed, because blocks now find your tables themselves. Keep writing your own declarative schema files next to the block files: a block runs over each table your schema already has and creates the rest. To upgrade, runbetter-supabase codemod 0.15, which deletesownershipand keepstablesandcolumns, thenbetter-supabase upgrade, and generate a migration. A config that still setsownershipfails validation. Read Your own schemas.A table your own schema files create (any declarative file better-supabase didn't write), or a table in the saved snapshot (
source.snapshot) that no block file or module migration created, is the app's table. Over it, the block skips itscreate table, adds only the columns it needs that your table lacks withalter table ... add column if not exists(nullable unless they have a default), and writes its functions, policies and triggers over it. It never revokes your grants or changes your constraints. Text written into a typed column of such a table goes throughbetter_supabase.as_column_type, so the column can be an enum or a domain. A module runs over the app's table for each table its spec allows (most block tables); for any other table it refuses to create a table your schema already declares and names the file.The policies a block adds to your table are named
bsb_<table>_<command>(such asbsb_teams_select) and its triggers start withbsb_, so they never replace a policy or trigger of yours with the same name. When your table already keepsupdated_atcurrent with its own trigger, the block adds nobsb_updated_attrigger there. Doctor adds BS347 (warning), for a block policy on your table next to your own policies for that command when none of them repeats its condition, and BS348 (info), for a table whose ownupdated_attrigger the block keeps.Block files carry a
-- @bsb-hashline.upgrade,addandremoveleave a block file you edited by hand alone and exit 1 naming it, unless you pass--force. Block file positions are padded to 3 digits (900_better_supabase_012_tasks.sql);upgraderenames the 2-digit files and removes block files no installed block writes, when they weren't edited.add --adoptstill proposestablesandcolumnsfrom the database, but no longer writesownership, and a column the app's table lacks is a warning, since the block's migration adds it. The enum-column check and doctor BS342 now cover the app's tables in every mode, and migration-only options such astokenStorage: "plain"are accepted for a block over a table the app has.0.14 0.15 blocks.<name>.ownership: "adopt"delete the key ( better-supabase codemod 0.15)mode: "adopt"inBlockConfig(BlockMode)"managed", with the app's tables in the layout'sownTablesa block's table the app lacks, in adopt mode created by the block a column the app's table lacks, in adopt mode added by the block ( add column if not exists)migration-only options, in adopt mode only accepted for a block over a table the app has BS330 "Adopted table without a mapped column" BS330 "App table without a column a block uses" BS344 "Adopted webhook endpoints without a format" BS344 "App webhook endpoints without a format" teams_readon an app-ownedteamstablebsb_teams_selectteam_members_readon an app-ownedteam_memberstablebsb_team_members_selectbsb_organizations_readon an app-owned organizations tablebsb_organizations_select -
The built-in plugins become block extensions, and the
pluginsconfig key and the sixbetter-supabase/plugins/*subpaths go. Theupdated-at,created-by,trashandmembershipsblocks carryupdatedAtExtension,createdByExtension,trashExtensionandmembershipsExtension, andgeninstalls the extensions of the installed blocks in the generated schema, withvalidation()and the generated validators when a schema generator is configured.auth.organization.columnturns the memberships extension on for an app's own tenancy. The query rules move tobetter-supabase/lintasguards(),safeGuards(),recommendedGuards()andstrictGuards(), andvalidation()is exported frombetter-supabase.definePluginstays the versioned interface for your own plugins..use()of an extension the schema already installed replaces it, so passing options still works. A query on an organization table without an organization is now left to RLS by default; setauth.organization.onMissing: "error"to fail it. Without Temporal and anowoption, the updated-at extension leavescreated_atandupdated_atto the column defaults and the block's trigger.Run
better-supabase codemod 0.15to move the config and the imports. A config that still haspluginsfails with a message that names the blocks. -
Presets now install the automations and queue blocks their default automations and block timers need:
helpdesk,people,erpandautomationgain automations, andcrm,helpdesk,cms,itsm,claims,ai,ai-chatandai-agentsgain the queue.erpturns on thequotes.quote_to_orderdefault. The automations block takesenableanddisableoptions with default automation keys. The content block publishes scheduled entries from acontent.publishblock timer, and itspublishScheduleoption and pg_cron job are removed. -
The
crmpreset now installs mail-sync, sequences, segments, assignment, enrichment, forecasts and lead-scoring next to deals, so leads (contacts in theleadlifecycle) are synced, scored, assigned and enrolled in email sequences. The newcmspreset installs content with publish approvals, versions and public media;erpinstalls a catalog, stock, quotes priced from the catalog, orders that invoice when paid, and employees with time and leave;piminstalls a catalog with channels, translations and public product media, plus custom fields, imports and bulk edits. Write the oldcrmblock list as a preset object to keep the 0.14 selection. -
Presets write block instances, and doctor finds the 0.15 APIs left in app code.
- A preset object takes
instances:blocksentries withblock,names,options,tables,onanduses. An instance named after a block selects it; one with anotherblockinstalls only what that block requires next to it. Your ownblocksentry for the same key is merged over the preset's. helpdeskanditsmname the tasks block's work itemsticketand its projectsissue, andpropertyadds amaintenanceinstance of tasks for maintenance requests. Setblocks.tasks.namesin your config to keep the old names.- The design JSON reads format 8, which adds the preset's
instances, anddesign-v1.jsonandconfig-v1.jsondescribe them. presetBlocksSourcewires each extra instance inlib/blocks.ts(maintenance: tasksBlock), and the config source lists it.- Doctor reports BS418 for imports of a renamed block or plugin subpath, an export named after a renamed block, and the record feature, leases maintenance and pass credit APIs 0.15 removed.
- The 0.14 to 0.15 guide ends with the upgrade order, and the consumer skill covers instances.
- A preset object takes
-
Record sections become record bindings. A block declares one
recordbinding, named by its key in the config, andgenwrites onerecords/<type>.tsper record type instead of thefeatures/folder, the navigation and the command files.bsb.record(type)replacesrecordServerandbsb.sectionAction, andgen.recordTypesreplacesgen.generateFeatures.better-supabase codemod 0.15renames the section exports and lists the calls to move. -
better-supabase scaffold api, thescaffoldconfig key (tooling.scaffold) and thescaffoldstep ofgenare removed.defineApifrombetter-supabase/specnow includes every app table and block instance by default, andcreateOrpc(betterSupabase).router(api)frombetter-supabase/orpcserves it, so there is no API module to generate. Runningscaffold apiprints that replacement, and a config that still setsscaffoldfails to load with a message that tells you to delete the key. Deletelib/api.generated.tsand the routesscaffold apiwrote, and serve the router instead: https://bettersupabase.com/docs/frameworks/orpc#serve-the-api -
Removes
better-supabase scaffold screens. The library writes no pages: build a table's screens on its generated data hooks (useTasks,useTask) and start from therecord-*UI recipes. Running the old command exits with a message that says so.scaffold apiis unchanged. -
In
tenantscope, every block table a client can reach and every tenant table intablesgets a restrictivebsb_tenant_scopepolicy. It keeps rows to the caller's organizations and to what the block's own policies grant, so a permissive policy the app adds, evenusing (true), can no longer read or write another organization's rows. Runbetter-supabase upgradeand generate a migration to apply it. -
Each block instance renders its own SQL. A second instance writes files named after it, prefixes the table, function, trigger and index names its entity renames leave unchanged with the instance name, reads the dependency instance its
usesnames, and records itself inbetter_supabase.blockswith the newblockcolumn. Its block marker names the block, the default roles grant its renamed permission keys, anddoctorandupgradetrack each instance's version. -
TypeScript 7.1 can get the schema types from better-supabase's content mapper, so the repository no longer holds
database.types.tsor the type half ofgenerated.ts.gen.contentMapper: trueturns on mapper mode.genwrites aschema.bsbmarker and agenerated.tsthat keeps the runtime values and re-exports the types withexport type * from "./schema.bsb", and writes nodatabase.types.ts.Database(the enriched one) now comes fromgenerated.ts. Files mode stays the default, and its output is unchanged.init --content-mappersets the option, adds{ "package": "better-supabase", "extensions": [".bsb"] }tocontentMappersintsconfig.jsonand adds--runExternalCodeto thetypecheckscript. It prints the change instead when a file holds comments or has no such script.- The mapper renders the same types
genwrites in files mode, from the same config and snapshot, and caches them innode_modules/.cache/better-supabase;genfills that cache, so the firsttscafter it reads the types. It watches the config, the snapshot,supabase/config.tomland a stampgenrewrites when the types change, sogen --watchreloads the editor. A failure becomes a diagnostic (BS603 to BS606) instead of stoppingtsc, and a config or snapshot that fails to load keeps the last types. - Doctor's new BS602 check reports a missing
contentMappersentry, a TypeScript older than 7.1 and atypecheckscript without--runExternalCode. - The content mapper protocol version is pinned as
SPEC_PINS.typescriptContentMapper("1").
Content mappers need TypeScript 7.1, which is in beta (
7.1.0-beta). See the content mapper page and ADR 0097. -
Blocks declare their wiring. A block manifest now lists its
envkeys,providers,routesandworkers, and the preset catalog carries them.better-supabase addandinitappend missing keys to.env.example, write commented provider stubs intoproviders.tsnext toblocks.generated.ts, and print a numbered checklist with the registry command for the routes and the crons to schedule.addalso renders installed blocks again when a new block changes their SQL, such as entitlements once billing is installed. Two doctor checks fail on missing wiring: BS504 for a required env key no env file lists, and BS505 for a required provider (enrichment, mail-sync) that no source passes with.with(...)or.using(...). -
Fixes for blocks that run over the app's tables, and for the tenant scope.
- Blocks install in any order again. A block file that runs before memberships (such as audit) used to fail with "function better_supabase.member_organization_ids() does not exist"; each block that writes the tenant scope now creates an empty
member_organization_idsfirst when it is missing. - The rendered block files are the same whatever order the blocks are listed in, so their
@bsb-hashno longer changes between runs. - Channels cast the visibility they write, and the conversation access they set, to the column's type, so both can be enums of the app's. The hiring and deals pipelines use the tenant column
columns.<table>.tenantmaps, and inventory moves stock without a ledgermemocolumn whenledger.columns.transactions.memoisnull. - The tags block no longer writes
create table if not exists (without a name whentables.taggingsisnull. - When tenant and platform invitations share one table, the invitations block writes one
bsb_invitations_readpolicy that reads both. - The drive block's read policy calls
drive_readable_ids()once per statement instead ofdrive_can(id, ...)for every row. - Over your own tables,
profilesno longer adds anavatar_pathcolumn it doesn't use, andformsscores submissions unlesscolumns.submissionsmapsscore,maxScoreorpassedtonull.add --adoptlists a required column the block adds as<column> (the block adds it). - Doctor reports fewer false positives on the app's tables. BS309 skips an old name on a table of yours, BS207 no longer counts your policy next to a block's
bsb_policy (BS347 reports it), BS347 skips a block policy whose condition is yours with moreandoperands, BS107 counts only your own policies, and BS206 no longer counts a helper called as(select helper('constant')). - A block adds no
bsb_policy on your table for a command one of your permissive policies already allows for its roles (true, the same condition, or the block's with fewerandoperands, as BS347 compares them). Postgres no longer evaluates two policies for the same rows, so themultiple_permissive_policiesadvisor stays quiet. A wider block policy still renders, and BS347 reports it. better-supabase/sqlexportshasColumnAccess,notNullCheckName,scopePolicyNameandTENANT_SCOPE_POLICY, the names doctor checks the tenant scope of your tables with, anddeclaredPoliciesandwidenedCommands, which read the policies your schema files leave and compare a block's policy with them.
- Blocks install in any order again. A block file that runs before memberships (such as audit) used to fail with "function better_supabase.member_organization_ids() does not exist"; each block that writes the tenant scope now creates an empty
-
The package README now leads with
db.customers.listanduseCustomers, and points at the docs catalog instead of listing every block. -
Search no longer creates its index triggers on the tables of blocks that render after it. Each of those blocks adds the trigger to its own file, so a design that searches a later block's table (the helpdesk preset's tickets, for example) applies on a fresh database.
0.14.0 (2026-10-22)
-
Fix seven issues an adopter reported, around
$rpctypes,findMany,DbExceptionand PowerSync.gentypes areturns tablecolumn through anot nulldomain as non-null, and prints a notice that points to@notNullfor a function whose columns stay nullable. Function arguments stay| null, which only widens what you can pass.- A top-level
_count,_sum,_avg,_minor_maxinfindManyand the other reads is now a type error and returns aninvalid_requesterror. Before, the key was silently ignored, so code that passed one gets an error now: move it intoinclude: { _count: { notes: true } }, or callaggregate()for the table itself. DbExceptionhas theDbErrorfields as its own properties (kind,status, andcode,details,hintandtablewhen set), and theDbErroras itscause.- PowerSync and Expo SQLite run includes (nested, filtered, ordered, limited and
required), related counts and related aggregates as one SQL statement.checkSqlitealso takes a query spec frombetterSupabase.spec. createUploadConnectortakesonError, which reports a failedgetSession(phase: "credentials", kindunauthorizedornetwork) and uploads that stay queued for a retry (phase: "upload").UploadRepository<Insert, Key>is typed by the table, so generated repositories fit it without a cast.uploadRoute(repository, { put: "create" })makes an insert-only route for write-once tables: aPUTcallscreate, and a conflict counts as applied.
-
Add the
assetsblock: a location hierarchy and an asset registry with assignment, coordinates and optional PostGIS.better-supabase add assetsinstalls locations in a tree (site, building, unit) without cycles, and assets with a kind, a tag, a serial number, a status (active,maintenance,retired) and an assignment to a member or any record, with its history.createAssetsfrombetter-supabase/blocks/assetsmanages them, andassetsSectionshows the assets a record holds on its page.nearfinds assets and locations within a radius. Thepostgisoption adds geography points and location areas with GiST indexes, andlocationsAtreturns the locations whose area contains a point (ADR 0066).- With bookings or work items installed, booking resources and work items get an
asset_idthatlinksets. - New permissions:
assets.read,assets.manageandassets.assign.
-
Add the
billable-timeblock (better-supabase/blocks/billable-time). It keeps an hourly rate card per organization, member and record, previews the unbilled time withunbilled(), and bills it as lines on a draft invoice withinvoice(), in bigint minor units. Billed entries can't be changed or deleted until the invoice is voided, and thebillableTimesection shows a record's unbilled time. Install it withbetter-supabase add billable-time; it needstime-trackingandinvoices. -
The
billingblock can bill tenants as Stripe Accounts v2 accounts with thecustomerconfiguration, and the module stores the account next to the customer.createBilling({ customerAccounts })creates or reuses the tenant'sv2.core.account(resolvereturns an existing one,paramsaddsv2.core.accounts.createparameters) and passescustomer_accountto Checkout and the customer portal. A tenant that already has a v1 customer keeps it.account(organizationId)andensureAccount(organizationId, details)are new, andensureCustomerfails withBILLING_CUSTOMER_PENDINGfor an account until Stripe creates its customer.handleStripeEventresolves a tenant by its customer or its account, and records thecus_id Stripe creates for the account from the first Checkout session, subscription or other event that carries both ids. Outcomes,billing.*block events andBillingStatusreportaccountId, and the newbilling.account_linkedevent is recorded when an account is linked.connectEvents: "ignore"makeshandleStripeEventskip Connect events (event.account), for an endpoint that receives platform and connected account events together. The default still handles them.- The
billingSQL module is at version 3:billing_customershas a nullablestripe_customer_account_id(^acct_),stripe_customer_idis nullable, and a row needs one of the two.link_billing_account(tenant, account)andbilling_account(tenant)are new,link_billing_customerrecords the customer on a row that has only an account,billing_customer_tenantmatches either id, andbilling_statusreturnsaccount. Runbetter-supabase sql upgradeand generate a migration. StripeClienttakes an optionalv2.core.accounts, and the portal session acceptscustomer_account.stripeInboxVerifyandverifyStripeWebhookare now tested with Connect events and with the thin event notifications of event destinations, which Stripe signs the same way.
-
Extend three blocks. Each extension is behind a new option that is off by default, so existing installs render the same SQL.
engagementswithrecordings: truestores call and meeting recordings asai-filesfiles, keeps transcript segments with speakers and timestamps, and attaches AI notes and a summary through the AI-neutral interfaces. New events:engagement.recorded,engagement.transcribedandengagement.summarized.orderswithkitchen: truegives every order line a preparation state (queued,preparing,ready,served) and a station, published for Realtime, with thekitchen-displayandorder-state-boardrecipes. New events:order.preparedandorder.served.bookingswithrecurring: truebooks a series from a recurrence rule (bookSeries, withparseRecurrenceandformatRecurrencefor the RRULE subset), moves one occurrence or every following one (reschedule) and cancels a series (cancelSeries). Every occurrence goes through the same exclusion constraint. New event:booking.rescheduled.passeswithcredits: truepays for classes with a pack of credits (bookWithCredit), keeps every credit in a ledger (credits), and refunds the credit when the booking is cancelled at leastcreditRefundBefore(default 12 hours) before it starts. New events:pass.credit_usedandpass.credit_refunded.
-
The calendar block can now tell you when members are free, and bookings can run appointment schedules.
- Events take a
kind(event,out_of_officeorfocus_time), atransparency(opaqueortransparent, mapped to the iCalendarTRANSPproperty) andautoDecline. setWorkingHoursandworkingHoursstore each member's weekly hours in a time zone, in the newcalendar_working_hourstable.freeBusy(organizationId, userIds, range)returns busy, out-of-office, focus-time and working-hours ranges per member. Postgres computes them, so recurring series, overrides, accepted invitations and approved leave all count.commonFreeTimefinds the ranges when everyone is free.- An out-of-office block, and a focus time block with
autoDecline, declines new invitations it covers. - Bookings resources take
hostUserIdandcheckBusy, so their slots skip the times the host's calendar is busy. Use them for appointment schedules.
Run
better-supabase sql sync, then generate a migration. The new columns have defaults, so existing rows keep working. - Events take a
-
Add presence on any record, record mentions with backlinks, and save for later.
- The subjects module authorizes Realtime presence on
presence:<type>:<id>for anyone who can read the record.subjectPresenceandsubjectPresenceValues(subject)frombetter-supabase/realtimejoin it withusePresence, so a channel, a comment thread's record and a document share one helper. Thepresence-avatarsUI recipe shows who else has a channel open. - Messages and comments mention a record as
@[Name](subject:<type>/<id>).messaging.recordMentions(subject)lists the messages that mention a record, for its readers only, andmessage.sentcarries the mentioned records asrecordMentions.mentionSegments,parseMentions,recordMentionanduserMentionfrombetter-supabase/blocks/messagingparse and write the syntax, and themessage-listrecipe renders record mentions as chips. - The collections block keeps a saved items list per member:
saveForLater(organizationId, subject, { note, remindAt }),saved,completeSavedandremoveSaved.remindDue()(service role) sends thenotificationyou configure through thenotifierport when a reminder is due and recordssaved_item.reminded. The block now consumesnotifieras an optional port.
Run
better-supabase sql syncand generate a migration to get the new tables, functions and policies. - The subjects module authorizes Realtime presence on
-
The comments, attachments, reactions, engagements, documents, calendar and reminders blocks declare their entities, so
blocks.<name>.entitiesrenames them like the other entity blocks:{ comments: { entities: { comment: "note" } } }turns thecommentstable intonotes,create_commentintocreate_noteandcomment.createdintonote.created. Their table indexes and policies are now named after the table, so they follow a rename.Installing comments, engagements, documents or calendar registers
comment,engagement,documentandcalendar_eventas subjects, so reactions, attachments, search, relations and the other subject blocks accept them with nosubjectsentry. Attaching a file to a comment checkscomments.createinstead ofattachments.upload, the key the comments table checks for writes; a block entity's subject can name its ownuploadaction this way. Engagements and calendar events are indexed for search when the search module is installed. Comments, attachments, engagements and calendar export input schemas:commentInputSchema,commentChangeSchema,attachmentInputSchema,engagementInputSchema,engagementChangeSchemaandcalendarEventInputSchema.To upgrade:
- Remove
subjects.comment,subjects.engagement,subjects.documentandsubjects.calendar_eventfrom your config when the block that owns them is installed: asubjectsentry with a block entity's name is an error. To keep your own entry instead, setblocks.<name>.entities.<entity>.subjecttofalse. - Run
better-supabase sql sync, then generate a migration. Reactions now checks a comment through the comment subject, which also requirescomments.read, and refuses a reaction to any subject whosedeletedAtis set. Its backfill setting is nowbetter_supabase.bs_reactions_backfill. - If you set
tablesfor one of these blocks, its policies get new names that follow the table; drop the old<block>_readstyle policies by hand after the migration, or leave them, since they are the same permissive select policies.
- Remove
-
Comments and messaging notifications can be turned off again, and they no longer write a notification nobody receives.
blocks.comments.options.notify(defaulttrue) restores the opt-out the 0.14 comments move removed:falsesends nocomment.posted.blocks.messaging.options.notify(defaulttrue) does the same formessage.mentioned,message.directandmessage.replied; following records and threads still works.comment.postedandmessage.repliedare sent only when the record or thread has a follower besides the author and the mentioned members, or anotification_audiencehook can add recipients.- Every comment and message notification carries a
subject_label: the record'ssubject_titlefromconfig.subjects, or the conversation's title. An adopted notifications table that requires a label no longer makescreate_commentfail, and one that restricts types can turn the comment and message types off withnotify: false.
-
Move comments onto the messaging core, and the activity feed into its own
activityblock. A record's comments are now its messaging conversation, so comments get resolve, pins, edit history, anchors, attachments and read markers from messaging, andassignturns a comment into a work item. See Comments, Activity and the upgrade steps in From 0.13 to 0.14.- The comments block now requires
tenant,access,subjectsandmessaging, and runs in thetenantscope only. Register each record type you comment on inconfig.subjects. - The comments module goes to version 8.
better-supabase sql upgrademoves each record's comments into one conversation, keeps every comment's id, author, body, document, mentions, thread and timestamps, moves reactions and attachments on a comment to the message, and drops thecommentstable and its functions. - Followers of a record get the
comment.postednotification, and mentioned users get messaging'smessage.mentioned. better-supabase/blocks/activityexportscreateActivity,activitySink,activityListQueryandactivityBlock. The crm, projects, helpdesk and docs presets include it.
Before After comments.read,comments.create,comments.moderatemessages.read,messages.send,messages.moderatecomments.activity,blocks.comments.permissions.activityactivity.read,blocks.activity.permissions.readcomment.created,comment.deletedmessage.sent,message.deleted, withconversationKind,recordTypeandrecordIdon a commentcomment.mentionedthe message.mentionednotificationcommentsEvents,CommentsEventsmessagingEvents,MessagingEventsfrombetter-supabase/blocks/messagingcomments.history(organizationId, subject?, options?),ActivityHistoryOptionscreateActivity({ transport, tenant }).list(subject?, options?),ActivityListOptionsactivitySink,activityListQueryfrombetter-supabase/blocks/commentsthe same names from better-supabase/blocks/activityblocks.comments.options.subjectsconfig.subjectsblocks.comments.options.maxBodyLength,extraColumnsblocks.messaging.options.maxBodyLength,extraColumnsblocks.comments.options.documentSchemaremoved blocks.comments.entities(thecommententity)the messageentity,blocks.messaging.entitiescomment.mentions,comment.createdAtcomment.mentionIds,comment.sentAtcommentsBlock.schemasremoved; commentInputSchemaandcommentChangeSchemastayreactions on { type: "comment", id }reactions on { type: "message", id }edit_comment,delete_comment,comment_subject_readable,comment_authorsedit_message,delete_message,can_subject(type, id, 'read') - The comments block now requires
-
The comments controller and its React, Vue, Svelte and Solid hooks fetch only the comment a Realtime ping names, and its thread's root for the reply count, instead of loading the whole thread again. A client passed to
createCommentsControllernow needsget. -
better-supabase/presetadds thecommunityandfeedbackpresets to theverticalsgroup, both on thepostsblock.communityissaasplus forum boards of voted posts, messaging and channels, comments, reactions, moderation, post scores, tags and search.feedbackissaasplus feedback boards of voted ideas with roadmap statuses, comments, reactions, moderation, work items linked to the ideas they ship through relations, tags and search. Each has a page under Presets. Existing presets and preset codes keep their blocks. -
Add the
contractsblock (better-supabase/blocks/contracts). A contract with a registered counterparty moves from draft through review and e-signature (the contract is frozen as a version and signed with thesignaturesblock) to active, expired or terminated. Values are bigint minor units, renewal terms (auto-renew, a notice period) schedule a reminder for the owner before the notice deadline, andrunRenewals()renews or expires contracts past their end date. Obligations carry due dates and owners, and thecontractssection lists a record's contracts. Install it withbetter-supabase add contracts; it needssubjects,versions,signaturesandreminders. -
Add the
controlsblock (better-supabase/blocks/controls). It keeps compliance frameworks and their controls, evidence linked to a control (an attachment or a note, valid until a date), and recurring evidence tasks with an assignee and an overdue state thatnotifyOverdue()reports once per lapse. A control's status (passing, failing, not started or not applicable) is computed from its evidence and tasks and rolled up per framework. Policies are published as versions, and members acknowledge each one. Install it withbetter-supabase add controls; it needsversions. -
New
coursesblock (better-supabase/blocks/courses) for courses with modules, lessons, scored quizzes, learner progress and certificates. It runs on theenrollmentsblock: a learner's enrollment in a course is an enrollment in the programcourse:<id>, with a step per required lesson, so the enrollments block keeps one record of who is enrolled in what.save,saveModuleandsaveLessonbuild the outline; modules and lessons order by fractional rank keys (ADR 0021), and a new one goes last. A lesson iscontent,videoorquiz; a quiz lesson names aformsform.enroll,unenroll,start,complete,resetandsubmitQuiztrack progress per lesson incourse_lesson_progress. Postgres grades a quiz through the forms block's scoring, so the browser never sees the answer key and can't change the score; a passed quiz completes its lesson.- Completing every required lesson completes the course and, when the course gives one, issues a certificate with a random code.
verifyCertificate(code)checks it without signing in;revokeCertificatewithdraws it. outline,lesson,progressandlearnersread the course; members read published courses,courses.enrollenrolls others,courses.managebuilds them.- The block emits
course.*,course_lesson.completedandcourse_certificate.*events, and every write is audited. Its five tables rename throughblocks.courses.entities. - The enrollments block refuses to complete or reset the steps of a
course:program, so progress only changes through the courses block.
Install it with
courses: {}next toformsandenrollments, then runbetter-supabase sql syncanddb diff. Thecourse-outlineandlesson-playerrecipes render it with ReUI. -
Add
blocks.engagements.options.bookings. With the bookings block installed and the option on, every confirmed booking becomes ameetingengagement with the external refbooking:<id>: rescheduling moves it, and cancelling completes it with the outcomecancelled: <reason>. With parties installed, the meeting sits on the person whose user or email matches the booker's, and on their company. A trigger on the bookings table does this, so bookings made through the public link or by a direct write are logged too. -
Add the
enrichmentblock (better-supabase/blocks/enrichment).createEnrichment({ transport, provider })looks a parties company or person up and stores the profile per record and provider. A match fills the record's emptydomainandwebsite, orphoneandtitle, and never overwrites a value.enrichDue()works through records with no result or a stale one from a cron, and every result writesparty.enriched.peopleDataLabsEnrichment({ apiKey })calls People Data Labs overfetch; any other source plugs in as anEnrichmentProviderwithapiVersion: 1. The block adds theenrichment.readandenrichment.runpermissions. -
Add the
forecastsblock (better-supabase/blocks/forecasts).createForecasts({ transport })snapshots the deals forecast for a period and currency withsnapshot(), keeps a copy of the deals behind each number, and lists, opens and compares snapshots withlist(),get()andchanges(), which labels each deal added, removed, won, lost or changed. Every snapshot writesforecast.snapshotted, and the block adds theforecasts.readandforecasts.snapshotpermissions.Add the
field-historyblock (better-supabase/blocks/field-history). Name the database columns to track per subject type in itssubjectsoption, and a trigger records each change with the old and new value, the author and the time.createFieldHistory({ transport }).of(subject)reads a record's changes, newest first, for members withhistory.readand read access to the record. -
Add the
mail-syncblock (better-supabase/blocks/mail-sync). Members connect their own Gmail or Outlook mailbox, andsyncDue()pulls new mail on a cron: each thread lands as anemailengagement on the people whose addresses appear in it and, withmatchDomains, on the companies whose domain matches.threadsOf(record)lists a record's mail,send()sends a new message or a reply and stores it on its thread, and a private mailbox stays visible only to its owner.gmailMail()andoutlookMail()call the Gmail API and Microsoft Graph overfetch, so no SDK is needed. Another host implementsMailProvider(apiVersion: 1). Tokens come from yourCredentialProvider, such asvercelConnectCredentials(), asked for the mailbox owner, and the block never stores one. The block adds themail.read,mail.connect,mail.sendandmail.managepermissions and themail_account.connected,mail_account.disconnected,mail_message.receivedandmail_message.sentevents. Deleting a member's data purges their mailboxes and revokes the credential reference. -
Track opens and clicks of mail sent through the
mail-syncblock, and record which template version a message came from. Withtracking: { url }oncreateMailSync,send()rewrites the HTML body's links through your tracking route and adds an open pixel; the database keeps the original HTML and only a SHA-256 of the message's tracking token.track(request)answers that route: it returns the pixel for an open, redirects a click to the stored link, and answers 404 for an unknown token.track: falsesends one message untracked.send()takes atemplateVersionId, such as atemplatesversion, andtemplateStats(organizationId, { since })returns the messages sent, opened, clicked and replied to per version. Sent messages carrytracked,openCount,clickCount,openedAtandclickedAt. The block adds themail_message.openedevent (once per message) and themail_message.clickedevent (each click, with itsurl). -
The crm preset now installs deals, quotes and sales targets next to pipelines, so a new CRM app starts with the full sales flow.
-
Add the
segmentsblock (better-supabase/blocks/segments). A segment saves a rules filter tree over one subject type, such as companies in thecustomerlifecycle, and keeps the records it matches in Postgres.refresh(segmentId)orrefreshDue()on a cron re-evaluates it and writessegment.enteredandsegment.leftfor each record that joined or left, so a workflow can react.members(),of(record)andlist()read the result. The block adds thesegments.readandsegments.editpermissions and themaxMembersoption.Add the
assignmentblock (better-supabase/blocks/assignment). A queue covers one subject type, around_robinorweightedstrategy and an optional territory filter.assign(organizationId, { type, id, fields })picks an owner from the first matching queue, logs the pick and writessubject.assigned; the app writes the owner onto the record. The block adds theassignment.read,assignment.manageandassignment.assignpermissions. -
Add the
dispatchblock (better-supabase/blocks/dispatch). It schedules work orders at a location or asset into time slots for technicians who are members, orders a technician's day as a route of stops, moves each order throughunscheduled,scheduled,en_route,on_site,doneandcancelledwith an event for every step, and links the parts an order uses to assets or inventory items.board()returns the schedule and the backlog for a date range, anddispatchSectionshows a record's work orders. Install it withbetter-supabase add dispatch.Add the
shipmentsblock (better-supabase/blocks/shipments). It stores packages, addresses and labels, keeps a tracking timeline per shipment, and derives the status and delivery time from the latest tracking event, andshipmentsSectionshows a record's shipments. Carriers plug in through the versionedShipmentCarrierinterface (apiVersion: 1);flatRateCarriercovers fixed prices, andingest()records a carrier's signed tracking webhook once, however often it is delivered.better-supabase/testingaddstestShipmentCarrier, the conformance case for carrier adapters. Install it withbetter-supabase add shipments.The Next.js example adds a dispatch board, a technician's day and shipment tracking as UI recipes.
-
Documents now take suggestions and named versions.
suggest(documentId, update, summary)stores a Yjs update as a suggestion without changing the document. Members get the newdocuments.suggestpermission, so someone who can only read a subject can still suggest.suggestions(documentId)lists them, anddecideSuggestion(id, decision, note)accepts, rejects or withdraws one. Accepting appends the update to the log with the author as its actor.- The provider from
better-supabase/yjstakesmode: "suggest"andsetMode(), keeps edits as a draft in that mode, and addssubmitSuggestion()andacceptSuggestion().openreturnscanSuggest. nameVersion(documentId, versionId, label)names or unnames a version,versions(documentId, { named: true })lists the named ones, and each version carriessourceandfrozen.- New events:
document.suggested,document.suggestion_acceptedanddocument.suggestion_rejected.
Run
better-supabase sql sync, then generate a migration. If you list role permissions yourself, adddocuments.suggestwhere members should suggest. -
The drive takes labels and file approvals.
- With the tags block installed,
label(id, tagId, applied?)puts a tag on a node or takes it off, andlabeled(organizationId, tagId)lists the nodes with a tag. Every node carrieslabels. - With the approvals block installed,
requestApproval(id, { attachmentId, reason })asks for approval of the file's current content or of one earlier revision, andapprovals(id)lists the requests withattachmentId,revisionandcurrent. Every node carriesapproval, the request for its current content, so a new upload clears it and restoring an approved revision brings it back. Add a policy for theapproveaction ondrive_node. - New types:
DriveLabel,DriveApprovalStateandDriveApproval.
With a managed drive installed, the tags and approvals functions now check the drive grants for
drive_nodesubjects: reading tags or listing requests needs read access to the node, and tagging or requesting approval needs write access. Before, any member of the organization could do both. Runbetter-supabase sql sync, then generate a migration. - With the tags block installed,
-
Add the
enrollmentsblock: enroll a party, member or any record in a program of steps, and track its progress and completion.better-supabase add enrollmentsinstalls programs per organization. A program has ordered steps and the subject types it enrolls. Saving changed steps raises the program's version, and enrolling again picks up the new steps while keeping the completed ones.createEnrollmentsfrombetter-supabase/blocks/enrollmentssaves programs, enrolls subjects, completes and resets steps, cancels enrollments and lists them by program, subject or status. Changes emitenrollment.created,enrollment.step_completed,enrollment.completedandenrollment.cancelled, andenrollmentsSectionshows a record's enrollments on its page (ADR 0077).- New permissions:
enrollments.read,enrollments.enrollandenrollments.manage.
-
sql upgraderenames an installed block's tables when you changeblocks.<name>.entities, instead of refusing the change.- It compares the module SQL under the installed names (from the
@bs-entitiesline) and the new ones, and writes guarded renames for tables, columns, indexes, policies, triggers and functions, so the rows stay. Permission keys in a role and permission catalog and storedsubject_typevalues move to the new names too. Each statement checks the old name first, so a second run changes nothing. sql upgrade --checkreports<block> has entity renames to apply to its tables, and its JSONdatagainsrenameswhen there are any.- Number sequence keys, recorded outbox events and your own hook functions keep their names; rename those yourself.
- SQL modules can declare a renamed table or column in
NAMES.migrations.sql upgraderenders the rename after your table and entity renames. entityRenameChangesis removed frombetter-supabase/sql. UseentityRenamePlan(names, installedModules, installedSql, layout), which returns the rename steps and the modules it can't pair up.
- It compares the module SQL under the installed names (from the
-
Add the
field-encryptionblock and audited reads, for apps that keep values such as a diagnosis or a birth date.field-encryptionkeeps one data key per tenant, user or app in Supabase Vault and encrypts values with pgcrypto (AES-256).drop_field_key(owner)deletes a key, which shreds every value sealed under it, and recordsfield_key.dropped.- An app table column takes
encrypted: true. It is stored as ciphertext, hidden from signed-in users, and read throughpublic.<table>_reveal(ids), which returns the configured types for the rows in the caller's scope.gentypes the column as its configured type. An encrypted column can't be unique, indexed, a reference, an identity,text[], or used where the database reads the value. - Custom fields take
encryptDefinition(id)fortext,emailandurlfields, andlistDefinitionsreportsencrypted. The definitions table gains anencryptedcolumn, added to an adopted table too unless you mapblocks.custom-fields.columns.definitions.encryptedtonull; runsql syncand generate a migration. appTables.<t>.auditReadsand thecustom-fieldsoptionauditReadswrite one audit entry per tenant and call, with the new categoryread, the acting member and the row ids. They need theauditblock.- Designs that use
encryptedorauditReadsare design format 6, and turning encryption on or off is a breaking change in the design diff.
There is no searchable equality on encrypted values; see the Field encryption docs page for the limits.
-
Anchor messages and comments to a file.
fileAnchor(attachmentId, { page, region, start, end })frombetter-supabase/blocks/messagingorbetter-supabase/blocks/commentspoints a top-level message at a page, a region of a page or video frame, or a moment or span of an attachment on the same record or conversation.send_messagechecks the shape and the file and fails withMESSAGING_ANCHOR_INVALIDotherwise, andanchoredTo(attachmentId)on both clients lists a file's messages or comments. Other anchors, such as text ranges, are stored as before. -
Turn an event in one block into a record in another, and build forms from a block's entity schema with the organization's custom fields. See Flows, Entity forms and Composing blocks.
better-supabase/flowsis a new subpath.defineFlow({ name, on, target, source, load, input, map, create })describes a flow, andcreateFlows({ flows, clients, enqueue })runs the listed flows from the outbox throughflows.sink(), or as jobs throughenqueueandflows.handler(). A flow runs once per source record: it records acreated_fromrelation and finds it again on a redelivered event. Flows carryapiVersion: 1.- Four built-in flows, each off until listed:
conversationToWorkItem,applicationToEmployee,bookingToEngagementandquoteToOrder(which takes yourcreate, since orders have no conversion from a quote yet). entityForm(schema, { fields, labels, customFields, timeZone })inbetter-supabase/recordslists the form fields of an entity schema and the custom fields, turns input text into typed values and validates both, returning the entity input and the custom values apart.useEntityForm(form, { initial, onSubmit })inbetter-supabase/reactholds the values, errors and pending state of an entity form.- The
entity-formrecipe renders the work item create dialog with the organization's custom fields.
-
The
formsblock scores quizzes and rolls up Net Promoter Scores. Existing forms keep working: scoring and NPS only apply to versions that use them.- A field takes a
correctanswer andpoints(1 by default), and a definition takesscoring.passMark, a percentage.publishmoves the correct answers into the newform_answer_keystable, which no client role reads, so respondents never see them; callers withforms.manageget them merged back. - Postgres scores a final submission inside
submitand storesscore,max_scoreandpassedonform_submissions. Submissions return them asscore: { score, maxScore, passed }, and theform_submission.submittedevent carries them.formScore(definition, answers)computes the same grade in the app. - The
npsfield type takes an integer from 0 to 10.forms.nps(formId, { field, since, until, bucket })(SQLform_nps) returns the promoters, passives, detractors and score, overall and per UTC day, week, month, quarter or year.npsCategoryandnpsScoredo the same in the app. - On adopted tables, map
tables.answerKeysand thescore,maxScoreandpassedsubmission columns to score; without them,publishrefuses a correct answer withFORM_SCORING_UNAVAILABLE.
The forms module moves to version 2. Run
better-supabase sql sync, thendb diff, to add the table and columns. - A field takes a
-
genwrites a record feature per subject, so a record page needs no hand-written loader or actions.- With a block that adds record sections installed,
genwritesfeatures/<subject>/next to the main module: the feature (defineRecordFeature), and for Next.js a server file (recordServer), one Server Action per section write and a client provider. With TanStack Query installed it also writes the record's query options. SetgenerateFeatures: falseto turn it off. No UI is generated; the cards stay recipes. - The share links, relations, versions and SLA blocks add sections (
shareLinks,relations,versions,sla), and every section can declare its writes. better-supabase/recordsaddsdefineRecordFeature,featureWritesandrunSectionWrite;better-supabase/nextaddsrecordServer;better-supabase/reactaddscreateRecordProvider;better-supabase/queryaddsrecordQueriesandinvalidateOnRecordEvents.
- With a block that adds record sections installed,
-
Add the
guestsblock: clients and contractors invited by email who reach only the records you grant them, and a portal for the party they act for.better-supabase add guestsinstalls guests and per-record grants.createGuestsfrombetter-supabase/blocks/guestsinvites by email (a one-time token whose email must match on accept), grantsread,commentanduploadon a record, revokes, and lists a record's guests or the caller's own access;guestsSectionshows a record's guests on its page.- Comments, attachments, invoices and bookings let guests in through the new
ctx.scope.guestandctx.scope.guestPartychecks: a granted record, and the invoices addressed to the guest's party. Guests are never members, and without the block the policies don't change. - An authorization provider can answer for guests through the optional
portalSubjectsandportalPartiestemplates inauthorization.functions;apiVersionstays 1.
-
Move the inbox onto the messaging core. Inbox conversations are core conversations of kind
inbox, and messages and internal notes are core messages, so the inbox shares read markers, typing, mentions, files and reactions with channels and comments. See Inbox and the upgrade steps in From 0.13 to 0.14.- The inbox block now requires
messagingandattachments, and reactions on inbox messages need thereactionsblock. - Notes are messages with
kind: "note"that only staff read. Read markers live inconversation_members.last_read_at, and typing goes through messaging'sset_typing. - Files are scanned attachment rows. Upload with
messages.createUploadandconfirmUpload; channel files wait infiles.pending()until the chat-sdkimportFilesfetches and confirms them. useConversation,useInboxWidgetand their controllers takeget(messageId)and fetch only the message a Realtime ping names.- The inbox module goes to version 4.
better-supabase sql upgrademoves conversations, messages, notes, participants, read markers, files and reactions with their ids, then drops the old tables and functions.
Before After inbox_messages,conversation_participants,conversation_readsmessageswithinbox_message_details,conversation_membersset_inbox_typingset_typing(conversation, typing, actor)reactions on { type: "inbox_message", id }reactions on { type: "message", id }, throughreact_to_inbox_messagemessages.reactandInboxMessage.reactionsas{ [emoji]: actors }arrays of { emoji, count, reacted, actors }InboxMessage.mentionsmentionIdsauthorId,editedAt,deletedAtasnullundefined; a contact's id isconversation.contactIdMessageAttachment, paths inMessageInput.attachmentsupload ids in attachments, channel files asInboxFileSourceinfilesPurgedContact.attachmentsas paths{ bucket, path }recordsthe topic inbox:<conversationId>messages:<conversationId> - The inbox block now requires
-
The inbox block schedules staff replies and wakes snoozed conversations on time.
inbox.messages.schedule(conversationId, input, at)saves a reply for later in the newscheduled_inbox_messagestable. Only its author sees it (messages.scheduled), moves it (reschedule) or deletes it (cancelScheduled).inbox.publishDue()(service only) sends the due replies through the normal reply path as their authors, and drops a reply whose author lostinbox.reply.- Snoozing needs a time in the future:
set_conversation_statuswith a pastsnoozed_untilnow fails withINBOX_SNOOZE_UNTIL(22023). wakeSnoozed()logsunsnoozedin the conversation's events, emits the newinbox_conversation.unsnoozedevent and notifies the assignee, or the inbox's members while nobody is assigned (inbox.snooze_ended).- With the jobs block, snoozing and scheduling queue a delayed job on
inbox_schedule(the newscheduleQueueoption) for the right time, so a handler that callswakeSnoozed()andpublishDue()runs them without a cron. - The chat-sdk
maintain()also sends the due replies and returns their count aspublished.
Run
better-supabase sql syncand generate a migration for the new table and functions. -
Add the
incidentsblock (better-supabase/blocks/incidents). Incidents carry a severity, a status timeline of updates, the components they affect and a postmortem. A component's status follows its open incidents and keeps an uptime history. Each organization can publish a status page, andpublicStatusPage(slug)returns it to anyone, signed in or not: the public components with their daily uptime and the public incidents with their public updates, and nothing else. Install it withbetter-supabase add incidents. -
Add the
leases,expensesanddonationsblocks, which post on the ledger instead of keeping balances of their own.leases(better-supabase/blocks/leases) lets units from the assets block to parties, with rent in bigint minor units per week, month, quarter or year.postDueRent()posts each rent period on the ledger once, so running it again posts nothing new, andrecordPayment()settles the balance due. Deposits are held through ledger holds untilterminate()captures a deduction and returns the rest. Leases renew, and members file maintenance requests on the unit. TheleasesSectionlists a party's leases.expenses(better-supabase/blocks/expenses) collects reports with lines in categories and receipts as attachments on the lines.submit()checks the spend policy (a limit per category and a receipt threshold) and opens an approval through the approvals block. An approved report posts on the ledger against the member's payable account, andreimburse()settles it.donations(better-supabase/blocks/donations) records gifts and pledges from donors to funds and campaigns, and posts each gift on the ledger.give()andchargeDuePledges()charge through aPaymentProvider, once per pledge period, andwebhook()applies the provider's events. Gift and yearly tax receipts are numbered per organization, with number-sequences when it's installed, andgivingSummary()returns a donor's year. ThegivingSectionshows a donor's giving.
Each block takes
extraColumnson its main table (lease_agreements,expense_reports,donations), typed with the client'sfieldsschema.Install them with
better-supabase add leases,add expensesoradd donations; each needsledger. -
Add the
ledgerblock: double-entry accounts, balanced transactions, running balances and holds. Inventory stock, leave balances and invoice payments move onto it (breaking for apps that read those tables directly).better-supabase add ledgerinstalls accounts per organization in a currency (minor units,Money) or a custom unit, transactions whose entries sum to zero per unit, append-only entries corrected byreverse, and holds that are captured or released.createLedgerfrombetter-supabase/blocks/ledgeropens accounts, posts and reads balances;ledgerSectionshows a record's accounts on its page. Credits, loyalty points, gift cards and trust balances are account kinds.- Inventory, leave and invoices require
ledger. Their client methods and SQL functions keep their names and results;sql upgradecopies the old rows into ledger transactions with the same ids and drops the old tables.
Before After stock_movementsledger_transactionsof kindstock.<reason>leave_ledgerledger_transactionsof kindleave.<entry>invoice_paymentsledger_transactionsof kindinvoice.payment/invoice.refundblocks.<name>.tableskey for the aboveremoved; read the ledger instead See the 0.13 to 0.14 upgrade guide.
-
Add the
channelsblock: public and private team channels on the messaging core, with topics, purposes, membership, archiving and an optional linked record. See Channels.createChannelsinbetter-supabase/blocks/channelscreates, updates, archives, joins, leaves, invites, lists, browses and finds channels, and lists the channels linked to a record.- Channels are an entity, so search, share links and reactions accept them, and
blocks.channels.entitiesrenames them. useMessagesanduseConversationsinbetter-supabase/blocks/messaging/react(and the Vue, Svelte and Solid entries) keep a conversation's messages, a thread, who is typing and the conversation list live over Realtime.createMessagesControllerandcreateConversationsControllerrun them without a framework.- The
chatpreset installssaaswith messaging, channels, reactions and attachments. - The
channels.createandchannels.managepermissions join the default roles. - The recipes
channel-sidebar,message-list,message-composerandthread-panelbuild a chat screen.
-
Add the
messagingblock: conversations, members, threaded messages, edits, pins, mentions, scheduled messages, read markers and typing, which channels, comments and the inbox build on (ADR 0062). See Messaging.The inbox renames the names that now belong to the core. Run
better-supabase sql upgrade(the inbox module moves to version 3) and update your calls:Before After the conversationstableinbox_conversationssend_message,edit_message,get_messagesend_inbox_message,edit_inbox_message,get_inbox_messagelist_messages,list_conversationslist_inbox_messages,list_inbox_conversationsset_typingset_inbox_typingcreateInboxand the Chat SDK inbox adapter call the new names, so apps that go through them need no change beyond the upgrade.createMessaginginbetter-supabase/blocks/messagingopens channels, direct and group messages and record conversations, sends, edits and threads messages, lists conversations with unread and mention counts, and moves read markers.- Messages and conversations are entities, so reactions, attachments, share links and search accept them, and
blocks.messaging.entitiesrenames them. - Mentions notify readers of the conversation, direct messages notify the other people in them, and thread replies notify the thread's followers.
- The
messages.read,messages.sendandmessages.moderatepermissions join the default roles. ctx.enqueuein module code takes adelay.
-
Add the
moderationblock: reports, a review queue, decisions and bans for any subject.better-supabase add moderationinstalls moderation items, reports, a decision log and bans per organization. Members report a subject for one of the configuredreasons. AtautoHideThresholdopen reports (3 by default, 0 turns it off) the content is hidden until a moderator decides.createModerationfrombetter-supabase/blocks/moderationreports content, reads the queue and one item with its reports and actions, decides (approve, hide, remove, restore, or ban, which removes the content and bans its author), reads the statuses of a list of subjects, and bans and unbans users. Decisions emitmoderation_item.decided, reports emitmoderation_report.created, and bans emitmoderation_ban.createdandmoderation_ban.lifted.moderationSectionshows a record's item on its page.- With the messaging block, report a message or a comment as
{ type: "message", id }. Hidden, removed and pending messages stay readable only to their author and moderators, removing a message empties it, and banned members can't send messages or comments. - New permissions:
moderation.read,moderation.report,moderation.manageandmoderation.ban. Members getmoderation.reportby default.
-
Breaking: onboarding checklists run on the enrollments block.
- The onboarding block now requires
enrollments. Each checklist is the programonboarding:<checklist>, with the organization or the user enrolled in it. better-supabase sql upgrademoves the rows ofonboarding_progressinto enrollments and their completed steps, then drops the table.createOnboarding,useOnboardingand the onboarding functions keep their signatures.- Queries on
onboarding_progressreadenrollment_stepsjoined toenrollmentsinstead. See the 0.13 to 0.14 guide.
- The onboarding block now requires
-
Add the
passesblock (better-supabase/blocks/passes): admission passes on QR codes and NFC tags. Issue a ticket for a booking or a pass for a resource, sign its token with the signing-keys block (token,typ: vnd.pass+jwt), and check holders in withcheckIn, which verifies the signature against your JWKS before the database decides. Every scan is logged with why it was turned away, and passes without a booking count against the resource's capacity with its confirmed bookings and live holds. A passes section lists a record's passes, and a merged record keeps its passes. Install it withbetter-supabase add passes. -
The app can now check permissions and show any subject's title without writing its own queries.
better-supabase/blocks/accesscalls the newmy_permissions(tenant, keys)SQL function, which returns the keys the caller holds in a tenant.access.can(key),access.flags({ edit: key })andpermissionFlags(set, map)returncanXbooleans typed by the keys you pass, such as the generatedpermissionsconstant. In React,usePermission(key)and<Can permission={key}>frombetter-supabase/blocks/access/reactshare one call per render, and the Vue, Svelte and Solid bindings exportusePermissions.better-supabase/blocks/subjectsresolvesSubjectReflists to a title and a path through the newsubject_titles(refs)SQL function, which runs as the caller and leaves out rows the caller can't read.useSubjectanduseSubjectsbatch every lookup of one render into one call. The new SubjectLink, SubjectChip and Can recipes show them in the Next.js example.gennow writes aurlsentry for every subject type with aurl(block entities,config.subjectsand app table subjects), andbetter-supabase add clientpasses the generatedblockConfigto the browser client when the project has blocks.To upgrade, run
better-supabase sql syncand generate a migration. Withblocks.access.mode: "custom", writemy_permissions(tenant, keys text[] default null) returns text[]yourself before you use<Can>. -
Breaking: reactions carry up and down votes.
vote(subject, value)sets the caller's vote (1,-1, or0to clear it) and returns the subject's tally, andvotes(subjects)reads tallies keyedtype:id. Thereaction_scorestable keeps each subject's score, up and down counts.- Reaction rows gain
kind(emojiorvote) andvalue, and the unique key includeskind.better-supabase sql upgradefills them for existing rows. A custom-mode reactions table needs both columns. reaction.addedandreaction.removedalso fire for votes, withkindandvalue. Filter onkind === "emoji"to keep the old meaning. See the 0.13 to 0.14 guide.
-
Show record sections as list columns, merge a record's sections into one timeline, and list what waits on the caller across blocks. See Record lists and My work.
defineRecordList(feature, list, { columns })inbetter-supabase/recordsruns a list query and fills each section column (countordata) for the whole page in one wave, withcanflags and the filter fields.recordListServer(bs, recordList)inbetter-supabase/nextloads it as plain data.loadTimeline(source, subject)merges every section with atimelinehook, newest first, and lists the sections it skipped. The comments, versions and attachments sections map their rows to timeline entries, and the comments section counts rows for list columns.recordServer(...).timeline(id)loads it after the permission check.- The subjects block installs
my_work(tenant, page_size): assigned work items, approvals the caller can decide, due reminders, mentions and SLA warnings, each only when its block is installed.blocks.subjects.myWork()calls it, andloadMyWorkgroups the items by kind with counts. useRecordListState(list, useQueryStates(parsers))inbetter-supabase/reactkeeps a list's sort, facets, filter and page in the URL through nuqs and returns the typed query.- With record features on,
genwritesnavigation.generated.tsandcommands.generated.ts: a sidebar item and a "Go to" command per subject with a list route, each with its read permission.
Run
better-supabase sql upgradeto addmy_workto an installed subjects block. -
Load a record page's sections with
better-supabase/records.- Blocks declare the parts of a record page they own with
defineSection(an extension interface,apiVersion: 1) on the manifest'ssections. The comments, attachments and tags blocks shipcommentsSection,attachmentsSectionandtagsSection, each with an optimistic reducer foruseOptimistic. loadSectionsloads several sections of one record in parallel, each settled asok,errororhidden;sectionCanhides the sections the caller has no permission for, without running their query.countSectioncounts one section's rows for many records.createRecordControllerkeeps the sections current over one realtime topic.- The subjects block's
summarycalls the newrecord_summaryfunction: the record's title and path with a count and unread flag forcommentsandattachmentsin one round trip. Tags are not counted, because taggings have no read policy. Apps in custom access mode that installsubjectsgetrecord_summaryin the subjects contract. better-supabase/nextaddsrecordTag,sectionTag,invalidateSectionandbs.sectionAction, a block action that drops the cached section after a write.better-supabase/testingaddstestSection, which checks a section against thedefineSectioncontract.
- Blocks declare the parts of a record page they own with
-
Breaking: review moderation moves to the moderation block.
- The reviews block now requires
moderation. Each review has a moderation item, and moderators can decide on reviews from the moderation queue next to other content.publish_reviewandreject_reviewkeep working and approve or hide the review's item. - The
moderated_byandmoderated_atcolumns ofreviewsare gone.better-supabase sql upgrademoves them onto moderation items and logs each past decision, andbetter-supabase sql dataputs the reviews written before the upgrade under moderation. Read the last decision from the item (decidedBy,decidedAt) instead. - A custom-mode reviews table drops both columns, and
moderatedByandmoderatedAtare no longer column names you can rename. See the 0.13 to 0.14 guide.
- The reviews block now requires
-
Add the
scoresblock: tenant-editable scoring models that write versioned scores to any record.better-supabase add scoresinstalls score models per organization. A model has rules (a rules filter tree worth points), metrics (a number field or the vote score times a weight, with a cap) and bands. Saving changed rules, metrics or bands raises the model's version and keeps the old definition.createScoresfrombetter-supabase/blocks/scoressaves models, computes a record's score from its fields with a breakdown, and reads current scores, history and the top scores per band. A changed score emitsscore.changed, andscoresSectionshows a record's scores on its page. Lead scoring and health scoring are models (ADR 0067).- New permissions:
scores.read,scores.manageandscores.compute.
-
Add three blocks:
sequencesfor multi-step outreach,lead-scoringfor scores fed by segments, mail and enrichment, andpostsfor forum and feedback boards.better-supabase/blocks/sequencesruns email, wait and task steps per contact as an enrollment program (sequence:<id>).runDue()sends due emails from the contact's mailbox through the newmailerport, whichmail-syncprovides, retries failed sends and ends a run when the contact replies. Task steps create work items whenwork-itemsis installed.better-supabase/blocks/lead-scoringscores people, and optionally companies, under ascoresmodel.leadRuleFields(subjectType)adds thesegments,mail.*andenrichment.statusfields to the rule catalog, a trigger marks records whose columns, segments or mail changed, andscoreDue()rescores them.better-supabase/blocks/postskeeps boards and posts with votes fromreactions, replies fromcommentsand reports, hiding and bans frommoderation. Moderators set a roadmap status, pin, lock and merge duplicates, andmoderation: "pre"holds new posts for review.mail-synclets the service role record a sent message for any connected mailbox, so a server-side sender such as the sequences runner can send on a member's behalf.- The enrollments block refuses to complete or reset a step of a
sequence:program, as it does forcourse:programs. - The
sequence-builderandpost-boardUI recipes show the blocks in the example app.
-
Give signatures their own block at
better-supabase/blocks/signatures. The SQL module, its tables andblocks.signaturesstay the same, so only imports change. See Signatures and From 0.13 to 0.14.Before ( better-supabase/blocks/forms)After ( better-supabase/blocks/signatures)createSignaturesand its typescreateSignaturesand its typessignaturesBlocksignaturesBlocksignaturesEvents,SignaturesEventssignaturesEvents,SignaturesEvents -
Merging two companies or two people now moves the dropped record's comments, attachments, reactions, tags, relations and guest grants to the kept record in the same transaction.
- Each module that stores rows per subject installs a merge handler, and
better_supabase.merge_subject_refs(subject_table, keep, drop)runs them all. Rows the kept record already has (the same reaction, tag or guest grant) are dropped instead of duplicated. - Apps can move their own tables in the same merge with a
security definerfunction markedbetter-supabase:subject-merge. See Merging subject records on the SQL modules page. - Run
better-supabase sql syncand generate a migration to install the handlers. Thecompany.mergedandperson.mergedevents still fire, so existing consumers keep working.
- Each module that stores rows per subject installs a merge handler, and
-
Every block method that works on a subject now takes a
SubjectRef({ type, id }) as its first argument, and reads the tenant from the block's newtenantoption instead of anorganizationIdargument. This covers comments, attachments, tags, reactions, relations, versions, sla, share links, custom fields, reminders, time tracking, approvals and the state machine. Rows carrysubject: SubjectRefin place ofsubjectTypeandsubjectId, and batch methods take a list of subjects and return a record keyedtype:id. A call without a tenant fails withinvalid_requestand the hintTENANT_REQUIRED.createBlockClient(ctx.db, commentsBlock, { config: blockConfig })andblockSet.client(ctx.db, "comments")build one block for a request: they call throughctx.dband read the tenant fromdb.$context.tenant, solib/blocks.tsno longer needs a wrapper per block that passes the organization. In the browser, passblocks: blockConfigtocreateClient, and the hooks read each block's schema and realtime topic from it and the tenant from the client'stenantoption or the session's tenant claim; the hooks no longer takeschemaororganizationId.Comments and attachments return their author on
list:authorholds the name and avatar URL from the profiles module, through the newcomment_authorsandattachment_authorsfunctions, which return only authors of rows the caller may read. It isundefinedwithout the profiles module.Before After comments.create({ organizationId, subjectType, subjectId, body })comments.create(subject, { body })comments.list(organizationId, subjectType, subjectId, options?)comments.list(subject, options?)comments.counts(organizationId, subjectType, subjectIds), keyed by idcomments.counts(subjects), keyedtype:idcomments.copy(organizationId, from, to)comments.copy(from, to)comments.history(organizationId, subject?, options?)comments.history(subject?, options?)attachments.upload({ organizationId, subjectType, subjectId, ... })attachments.upload(subject | null, attachment)attachments.put({ organizationId, subjectType, subjectId, ... }, file)attachments.put(subject | null, attachment, file)attachments.list(organizationId, subjectType?, subjectId?)attachments.list(subject?)versions.snapshot({ organizationId, subjectType, subjectId, ... })versions.snapshot(subject, input?)versions.list(organizationId, subjectType, subjectId, options?)versions.list(subject, options?)shareLinks.create(organizationId, subjectType, subjectId, options?)shareLinks.create(subject, options?)shareLinks.recordView(organizationId, subjectType, subjectId, viewerKind, viewer?)shareLinks.recordView(subject, viewerKind, viewer?)shareLinks.list(subjectType, subjectId),setState(subjectType, subjectId, starred)shareLinks.list(subject),setState(subject, starred)tags.create(organizationId, kind, name, ...),tags.list(organizationId, kind?)tags.create(kind, name, ...),tags.list(kind?)tags.tag(organizationId, subjectType, subjectId, tagId), anduntagtags.tag(subject, tagId), anduntagtags.forSubject(organizationId, subjectType, subjectId)tags.forSubject(subject)reactions.react(organizationId, subjectType, subjectId, emoji, options?)reactions.react(subject, emoji, options?)reactions.summary(organizationId, subjectType, subjectIds), keyed by idreactions.summary(subjects), keyedtype:idreactions.customEmoji(organizationId),saveCustomEmoji(organizationId, input)reactions.customEmoji(),saveCustomEmoji(input)customFields.listDefinitions(organizationId, entity),saveDefinition(organizationId, entity, ...)customFields.listDefinitions(entity),saveDefinition(entity, ...)customFields.readValues(organizationId, subjectType, subjectId)customFields.readValues(subject)customFields.setValue(organizationId, subjectType, subjectId, definitionId, value)customFields.setValue(subject, definitionId, value)relations.link({ organizationId, source, target, kind, ... }), andunlinkrelations.link(source, target, { kind, data?, fields? }), andunlink(source, target, { kind })relations.of(organizationId, subject, kind?),edges(organizationId, kind)relations.of(subject, kind?),edges(kind)relations.ancestors(organizationId, kind, subject), anddescendantsrelations.ancestors(subject, kind), anddescendantsrelations.rollup({ organizationId, subject, ... })relations.rollup(subject, { kind, of, agg, column? })relations.convertedInto(organizationId, origin, intoType),lineage(organizationId, subject)relations.convertedInto(origin, intoType),lineage(subject)sla.savePolicy(organizationId, policy)sla.savePolicy(policy)approvals.request({ organizationId, subjectType, subjectId, action, ... })approvals.request(subject, { action, reason?, payload? })approvals.list(organizationId, options?)approvals.list(options?), with an optionalsubjectfilterapprovals.isApproved(subjectType, subjectId, action)approvals.isApproved(subject, action)stateMachine.transition(subjectType, subjectId, to, reason?)stateMachine.transition(subject, to, reason?), and the same forpause,resume,setFlag,state,historyandstagesreminders.save(organizationId, subjectType, subjectId, offsetMinutes?, fields?)reminders.save(subject, offsetMinutes?, fields?)reminders.list(organizationId, subjectType, subjectId)reminders.list(subject)timeTracking.start(organizationId, fields?),stop(organizationId),running(organizationId)timeTracking.start(fields?),stop(),running()timeTracking.log,list,timesheet,submitandtimesheetswithorganizationIdfirstthe same calls without it; entries take subjectinstead ofsubjectTypeandsubjectIdrow.subjectType,row.subjectIdrow.subject.type,row.subject.iduseComments({ organizationId, subjectType, subjectId, schema?, topic?, limit? })useComments({ subject, topic?, limit? })useReactions({ organizationId, subjectType, subjectIds, schema?, topic? })useReactions({ subjects, topic? })useTagInput({ organizationId, subjectType, subjectId, kind, schema? })useTagInput({ subject, kind })To upgrade:
- Pass
tenantto blocks you create yourself (createComments({ transport, tenant: () => ctx.tenant })), or build them withcreateBlockClientorblockSet.client, which pass the request's tenant. - Replace each
organizationId, subjectType, subjectIdargument list with one{ type, id }object, and readrow.subjectinstead ofrow.subjectTypeandrow.subjectId. Read batch results by`${type}:${id}`. - Pass
blocks: blockConfigto the browsercreateClientand dropschemafrom the hooks. - Run
better-supabase sql sync, then generate a migration, for the comments and attachments author functions.
- Pass
-
Attachments keep versions and show image previews, and work items get checklists, repeat rules, watchers and attachments. See Attachments and Work items.
Run
better-supabase sql upgrade(orsql syncand a new migration):create_attachmenttakes three more arguments, so the upgrade drops and recreates it.attachments.replace(id, file)uploads a new file under the same attachment and keeps the current one as an earlier version.versions(id)lists them andrestore(id, version)makes one current again. Both emitattachment.replacedandattachment.restored.- Attachments record
width,heightandpages, andattachments.images(options)signs resized URLs foruseImage, behind the scan gate. createAttachmentUploadControlleranduseAttachmentUploadinbetter-supabase/blocks/attachments/react,/vue,/svelteand/solidupload files side by side with progress, wait for the scan, and retry or dismiss a failed upload.- Work items take
attachmentIdsoncreateand anattachmentschange onupdate, which link files the caller uploaded without a subject. - Work items have checklists:
saveChecklistItem,removeChecklistItemandchecklist, and each item carrieschecklist: { total, done }.get(id)reads one item. Thechecklistsection (workItemChecklistSection, with theworkItemChecklistOptimisticreducer) shows the steps on the item's page. - With the reminders block installed,
setRecurrence(id, { rrule, tzid })gives an item a repeat rule, andworkItemRecurrenceSink(workItems)creates the next item when a repeating one is completed.repeat(id, dueAt)runs once per item, so a redelivered event changes nothing. - With the notifications block installed,
watch(id, level)andwatchers(id)follow an item through notification subscriptions.
-
Add AI thread summaries to the messaging block, without tying it to an SDK.
messaging.summarize(target, summarizer, { force, maxMessages })summarizes a conversation ({ conversationId }) or a thread ({ threadId }) from the messages the caller can read, leaving out internal notes and deleted messages, and saves it as the service role.messaging.summary(target)reads it. A saved summary isstaleonce a message in its scope is sent after it, edited or deleted, andsummarizereturns a current one without calling the model.- The summarizer is a versioned
ThreadSummarizer(apiVersion: 1).summarizeWith(model, { providers, instructions, gateway, maxOutputTokens })frombetter-supabase/ai-sdkprovides one overgenerateTextwith an AI Gateway model string, tags the spend with the tenant and thesummaryfeature, and sends the tenant's own keys as BYOK when you pass the ai-providers block. createMessagingtakes an optionalservicetransport for the summary writes;createBlockspasses it.
Run
better-supabase sql syncand generate a migration to get thethread_summariestable and thethread_summaryandsave_thread_summaryfunctions. -
Rename a block's entities once in the config and get typed config keys, renamed clients, automatic subjects, generated name constants, input schemas, block hooks and server helpers. See Typed blocks.
This release breaks the config and a few exports. Update them as follows:
Before After sql: { naming: { tenant: "workspace" } }blocks: { tenant: { entities: { organization: "workspace" } } }workItemsSubjects(),dealsSubjects(),partiesSubjects(),catalogSubjects(),employeesSubjects()insubjectsnothing: installed blocks register their entities as subjects. Remove the spread. the helpers' urloptionblocks.<name>.entities.<entity>.url, such ascatalog: { entities: { product: { url: "/products/{id}" } } }CatalogSubjectsOptions,SqlNamingEntityConfig,EntitiesConfigblockConfig[name].naminginblocks.generated.tsblockConfig[name].names(runbetter-supabase gen)work_itemmethods, types and events afterentities: { work_item: "task" }saveWorkItembecomessaveTask,workItemIdbecomestaskId,work_item.createdbecomestask.created,work_items.readbecomestasks.readA
subjectsentry with the name of a block entity is now an error, and changingentitieson an installed block makessql upgraderefuse.blocks.<name>.entitiesrenames a block's nouns in its tables, columns, functions, events, permission keys, subjects and generated types. Every config key underblocksis typed from the block's names, anddefineConfigkeeps the config's literal types.renameBlock(block, names)inbetter-supabase/blocksrenames a block client's methods, argument keys, result keys and events.genwritestasksBlockand type aliases such asTaskfor each renamed block.blocks.generated.tsalso exportspermissions,PermissionKey,RoleName,blockEvents,urls,topicsandpaths.- The deals, parties, work-items, employees and catalog blocks export Standard Schema input schemas, such as
workItemInputSchema,workItemChangeSchemaandworkItemListFilterSchema. - The
zod,valibot,standardSchemaandjsonSchemagenerators write schemas for SQL functions (<function>Args,<function>Result) and for block entities (<entity>Input,<entity>Change,<entity>ListFilter).fieldMeta: trueadds labels, required flags, enum options and check bounds. blockQueries(blocks)andinvalidateOnBlockEventsinbetter-supabase/querymake TanStack Query options for every block method and invalidate reads when a block event arrives.useBlockQuery,useBlockMutationanduseBlockEventinbetter-supabase/react,/vue,/svelteand/solidwork with any block client, renamed or not.bs.blockAction(client, method, options)inbetter-supabase/nextandblockRouter(client, options)inbetter-supabase/orpcexpose block methods as server actions and oRPC procedures.- The
nuqs()generator writes typed search params for your tables, and thefactories()generator writes test factories, withdefineFactoryandfactoryTimeinbetter-supabase/testing.
-
better-supabase/presetadds 17 vertical presets in a newverticalsgroup (PRESET_GROUPS.verticals), so/createandinitlist them under Verticals:property,field-service,clinic,lms,events,legal,spend,contracts,customer-success,logistics,pos,fitness,nonprofit,itsm,compliance,constructionandclaims. Each one issaasplus the blocks of one kind of business app, such as leases on the ledger for property management, a dispatch board for field service or controls with recurring evidence for compliance, and each has a page under Presets. Theclinicpreset installsfield-encryption; its page shows the config for encrypted columns and read audits, which name your own tables and so stay in your config. Existing presets and preset codes keep their blocks. -
Security fix: a record's conversation and a channel linked to a record stay in the record's tenant.
open_conversationwith kindsubject(and socreate_comment) andcreate_channelwithsubjectTypeandsubjectIdchecked only that the record exists and that the caller holds its read permission in the record's own tenant, and they read the record past its table's policies. A member of two tenants could post a comment in one tenant on a record of the other, and any member could when the record type has no read permission inconfig.subjects. Both now refuse a record whose tenant column inconfig.subjectsnames another tenant, withMESSAGING_NOT_FOUNDorCHANNELS_NOT_FOUND, for the service role as well. Types withtenant: falseare not compared.
0.13.0 (2026-10-21)
-
Structured, non-throwing design APIs, a provider-neutral OAuth subpath, deploy records and a doctor rule for dropped library functions. See From 0.11 to 0.12.
parseDesign,decodeDesign,designFileSourceandreadDesignFileinbetter-supabase/presetthrow aDesignParseErrorwith a stablecodeand a JSON Pointerpath.safeParseDesignandsafeDesignFileSourcereturn{ ok: false, issues }instead of throwing.DesignTooLongErroris aDesignParseErrorwith the codetoo_long.DesignIssuefromcheckDesigngainscodeandpath, and a successfulDesignCheckgainsfitsUrl.designSchemaisparseDesignas a Standard Schema, andschemas/design-v1.jsonpublishes the design as JSON Schema.DEFAULT_PRESET_NAME,defaultPreset()anddefaultPresetCode()name the preset Create andinitstart from.better-supabase/create/oauthholds PKCE, sealed cookies and anOAuthSessionshape for any OAuth provider.sealandunsealtake an optional HKDFinfo.better-supabase/create/supabasere-exports them, andSupabaseSessionandisSessionstay as aliases.newDeployId(),deployQuery(files, { id })andDeployRecordinbetter-supabase/createlet a host app match a project to the preset it deployed.DeployResponsegainsid,presetanddesign.- Doctor's BS235 warns when an unapplied migration drops a
better_supabasefunction without creating it again with the same number of arguments, as a schema diff did foraudit()in 0.11.
-
codemod 0.9now pinsdefaultFormat: "standard"on an adoptedwebhooks-outblock that maps nocolumns.endpoints.formatand sets nodefaultFormat, which keeps the 0.8 body, and listssql addcalls in scripts and workflows for review (addalso wires clients). A newcodemod 0.11pinsdefaultFormat: "cloudevents"under the same conditions, since adopt mode requires the key from 0.11. Both list the edit for review. -
Add
better-supabase db diff, which turns the declarative schema into a migration with the Supabase CLI's command for the workflow and, when the shadow database can't start because no System V shared memory segment is left, diffs inside the running stack instead.--in-stackskips the shadow database,-f <name>writes the migration, and$BSB_PG_BINnames the directory withpg_dumpandpsqlwhen the CLI can't find them next to the postmaster. -
Add doctor checks for the machine's System V shared memory, which every local stack and shadow database needs.
- BS700 warns when 80% of the segment limit is in use (32 on macOS) and names the stacks that hold segments, so
supabase db difffailing withcould not create shared memory segmentpoints atstack prune. - BS701 warns when a stack holds more than its one interlock segment, which means its Postgres sets
shared_memory_typeordynamic_shared_memory_typetosysv.
- BS700 warns when 80% of the segment limit is in use (32 on macOS) and names the stacks that hold segments, so
-
doctor,gen,db queryandseed --applyno longer guess port 54322 for the local stack. Whensupabase/config.tomlsets no[db] portandsupabase statusfails, they stop withnot_foundand name both sources, so a per-worktree stack (supabase start --runtime native) can't reach another project's database on 54322.--stack <name>(or$BSB_STACK) readssupabase status --stack <name>whensupabase/stacks/<name>/config.tomlsets no port. -
A
permissionon an action, route, loader or oRPC middleware can now be checked against the row it acts on. Passresource: (input, ctx) => AuthorizationResourcenext topermission: it runs after the session andrequireTenantchecks, gets the validated input and the request's context (db,session,tenant), and its return value replaces the default{ type: "action" }or{ type: "route" }resource. A loader that throws refuses the caller: aDbExceptionkeeps its error (such asnot_found), and any other throw refuses withforbiddenandcode: "RESOURCE_UNAVAILABLE". Every adapter supports it, andbs.middleware()inbetter-supabase/orpcnow passes the procedure's input to the checks. The loader's context type is exported asResourceLoaderContext. -
Add
better-supabase stack lsandstack prunefor the Supabase CLI's managed stacks.stack lslists every stack with its branch, project root and running state, marks stacks whose worktree or branch is gone, and counts the System V shared memory segments each one holds against the system limit.stack prunedestroys the stacks whose worktree or branch is gone, never the one for this checkout.--stop-idlealso stops the running stacks of other branches, and--dry-runprints the plan. Destroying a stack needs consent in agent mode.- The command manifest has a new effect kind,
stacks, withreadorwriteaccess, inschemas/cli-commands-v1.json.
-
Crop, show and download stored images through Storage image transformations. See Image transformations.
defineBuckettakesvariants, named transforms such asthumb: { width: 160, height: 160, resize: "cover" }.renderUrl,signedUrlandpublicUrlaccept a variant name wherever they took a transform, and the names are typed.defineBucketrefuses a side outside 1 to 2500 or a quality outside 20 to 100.avatarBucket()andorganizationLogoBucket()come withsm,mdandlgvariants: center-cropped squares of 48, 96 and 256 for avatars, and squares of 64, 128 and 256 that fit the whole logo. Passvariantsto replace them.useImage(bucket, target, variant)inbetter-supabase/reactreturnssrc, asrcSetat 1x and 2x,widthandheight. Public buckets build the URLs while rendering; private buckets sign them and sign again before they expire.storageImageSrcSet({ url })inbetter-supabase/storagebuilds asrcsetfor a public Storage URL.- New types:
ImageTransform,ImageVariant,ImageSource,StorageImageandUseImageOptions. - Fix: the
better-supabase/next/imageloader andstorageImageUrlkeep a crop's shape. Whensrccarries awidthandheight, the height scales with each requested width, so a square crop stays square. A size over 2500 now shrinks both sides by the same factor instead of clamping the width alone.
-
Add
authorization.functions.teamIdsOf, a template that returns the team ids a user belongs to. Under theprovideraccess model,team_ids_of()in theteamsblock returns its set instead of readingteam_members, andsaved-viewsandcollectionsshare with those teams even without theteamsblock. Doctor BS417 warns when the provider declares ateamscope, one of those blocks is installed, and the template is unset. -
Seed each tenant with the same demo rows.
defineTenantSeed(betterSupabase, (tenant) => fixtures)inbetter-supabase/testingbuilds typed fixtures from a tenant id, andbetter-supabase seed --tenant <slug>(or--tenant '*') inserts them for organizations from the organizations block, all in one transaction. The file comes from the newseed.perTenantconfig key (supabase/seed.tenant.tsby default).seedTenantOnCreate(betterSupabase, seed, { sql })applies the seed to each organization created in development; it runs after the create call and never changes its result. -
Add
codecs: { timestamptz: "utc" }.timestamptzcolumns staystring, but every value is rewritten in UTC as ISO 8601 with aZand keeps all its fraction digits (2026-10-21 07:10:00.123456+02reads as2026-10-21T05:10:00.123456Z).infinitypasses through. The default stays"string". -
The Vercel Marketplace block serves the Partner API.
marketplace.partnerApi({ resources, plans })returns one handler for the installation, resource, secret rotation and plan routes. It verifies Vercel's OIDC token (signature against/.well-known/jwks, issuer, audience and expiry) and requires itsinstallation_idto match the path, answering 401 or 403 as Problem Details. The installation's access token is sealed in Vault, soaccessTokenis now optional. Tenants are tracked per installation and resource, and an empty tenant the integration created is removed with it. A rotation revokes the previous secrets only after the new ones are issued.reportUsagenow sends one request per billing period, with the period total asperiodValueand the part not reported before asdayValue, and no longer sendsplanValue. It moves the reported amount only after Vercel answers 2xx.marketplace.usageRoute({ secret, usage })runs it from a cron caller. The SSO exchange reads keys fromhttps://marketplace.vercel.com/.well-known/jwks, the path Vercel's discovery document names. Runbetter-supabase gento apply the module's version 2 upgrade. -
Add
withClaims(postgres, claims, fn)tobetter-supabase/testing. It runs raw SQL as the user the claims describe (roleandrequest.jwt.claimsare set, soauth.uid(),auth.jwt()and RLS apply) inside one transaction that always rolls back. -
Two SQL fixes. See From 0.11 to 0.12 for what to check.
better_supabase.acting_member()is granted toservice_roleonly;anonandauthenticatedgetpermission deniedinstead of an RPC that returned null.better_supabase.set_actor()issecurity definer, so the trigger still records the actor for every writer. Runsql syncto get the new grant in a migration. If your own SQL callsacting_member(), run it asservice_roleor from asecurity definerfunction.- Module file headers no longer carry the package version, so a release doesn't rewrite every module file. The
@bs-modulemarker keeps the module version, and a header written by an older release still counts as current.ModuleLayout.versionis deprecated.
-
The Record grid recipe, on the UI recipes page and in the skill reference, now notes that a copy of
@reui/data-gridinstalled from ReUI 2.8.0 or earlier doesn't repaint after an edit that keeps the row count. Reinstall it withnpx shadcn add @reui/data-grid --overwrite, or addtable.options.datato the dependency list of thevaluememo inDataGridProvider. -
Security fix for support session upload claims. In 0.12.0,
claimSignedUpload,claimReservedand the blocks'confirmandcommitclaimed any object without an owner on a path the target may insert into. That could include a file the service role stored earlier, such as an export or an import, which the claim then handed to the target and stamped with the session. A claim now only takes an object without an owner whoseupdated_atis at or after the session'sstartedAt, and in a versioned bucket only the current version. Older objects are refused with403AccessDenied. An upsert reservation that replaces such an object during the session can still be claimed.Required change for direct callers:
SupportStorageOptions.sessionnow needsstartedAt. The server already passes the wholeSupportSession; pass it too when you callsupportStorageyourself.uploadToSignedUrlon the server removes what it stored when the claim fails or is refused. A refused claim after a browser upload, includinguploadwithonProgress, removes nothing, because the claim can't tell that upload from another object without an owner;sweepremoves what is never claimed. A claim of an object the target already owns now succeeds even when it is older than the session. The impersonation page documents the limits of the claim's insert rehearsal and how to sweep uploads that are never claimed.
0.12.0 (2026-10-20)
-
Check a Create design in one call, and hand designs too large for a URL to
initas a file.checkDesign(input, preset)inbetter-supabase/createchecks a design object, design code or/createURL against a preset with every rule the canvas andsql syncapply. It returns{ ok: true, design, code }, wherecodeisnullfor a design too long for a URL, or{ ok: false, issues }, and never throws for a bad design.parseDesign(value)inbetter-supabase/presetchecks the shape of a design object.designFileSourceandreadDesignFilewrite and read a design file (better-supabase.design.json,DESIGN_FILE), which holds the preset code and the design as JSON with no length limit.init --preset ./better-supabase.design.jsonandapply --preset ./better-supabase.design.jsonread a design file like a Create URL.DesignTooLongErrornow points to it.
-
Doctor's BS503 warns when the shell exports a
SUPABASE_*variable (plain or with a browser prefix) that differs from the running local stack, so an app started from that shell would talk to another project. It readssupabase statusonly when such a variable is exported, and shows redacted values. -
better-supabase envwrites the full stack env:SUPABASE_URLandSUPABASE_PUBLISHABLE_KEYunder their plain names for server code, the same two with the browser prefix, and the newSUPABASE_JWKS_URL. The secret key, database URL and JWT secret never get a browser prefix.--write <file>names the file (--outstill works), and--prefixtakes a framework name (next,vite,expo,nuxt,astro,sveltekit),none, or the prefix itself. Help lists a long alias after the flag it stands for. -
Add
better-supabase run -- <cmd>. It starts the command with the running stack's URL and keys set, over the shell's exported variables and every.envfile, passes its output and exit code through, and forwards Ctrl+C andSIGTERM. When an exportedSUPABASE_*variable differs from the stack,runwarns and names it, showing the host and port of a URL or asha256:fingerprint of a key, never the value. -
Server auth can run hermetic.
auth.jwks: false(ornull) verifies against no keys and never fetches one, ignoringSUPABASE_JWKSandSUPABASE_JWKS_URL;nullused to fall through to the JWKS URL.createServer({ env })also takes the variables as an object ({ SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY }) and loads only those, never filling a missing one fromprocess.env.createTestSigner().jwksis typed so it passes toauth.jwkswithout a cast. -
Signed uploads work in a writable support session.
supportStorageused to refusecreateSignedUploadUrlanduploadToSignedUrlwithSUPPORT_STORAGE_WRITES, sobucket.connect(storage).reserve(...)and the blocks' browser uploads failed, and an admin could not upload a file as the user. NowcreateSignedUploadUrlruns the same dry run asuploadas the target (an insert, or an upsert withupsert: true, refused with Storage's403), then the service client signs the URL.An object uploaded to a signed URL has no owner, so a claim step finishes the upload. It checks again that the target may insert at the path, then makes the target the owner and adds
supportSessionIdandsupportAdminIdto the object'suser_metadata. It claims only an object without an owner; one another user owns is refused with403AccessDenied. TheStorageApithatsupportStoragereturns hasclaimSignedUpload(bucket, path), and a connected bucket hasclaimReserved(reservation), which succeeds without a request outside a support session, so call it after a reserved upload and before you record the file.uploadToSignedUrlon the server anduploadwithonProgressclaim on their own.The blocks claim in their own finish step:
attachments.confirm,drive.commitand the AI files block'sfiles.confirmclaim the upload before they record it. A refused claim keeps the record pending and returns the block'sforbidden(ATTACHMENT_FORBIDDEN,DRIVE_FORBIDDEN,AI_FILE_FORBIDDEN) ornot_found(ATTACHMENT_NOT_UPLOADED,AI_FILE_NOT_UPLOADED) error. Outside a support session they make no extra request. Read-only sessions still refuse every write withSUPPORT_READ_ONLY. -
Create moved to the cloud app.
createUrl()and the commentinitwrites above a preset now link tohttps://app.bettersupabase.com/create. Oldbettersupabase.com/createlinks redirect there with their query string, andpresetOfanddesignOfstill read both.
0.11.0 (2026-10-20)
-
bs.admin()returns anAdminDbwith$authAdmin, the typed Auth admin API (auth.admin) of the secret-key client, so cron jobs and webhook handlers can create, invite, ban and delete users without a second client. Request repositories don't have it. TheAdminDbtype is exported frombetter-supabase/server. -
Fixes and additions from adopter feedback.
New API:
matchDbError(error, matchers)maps aDbErrorkind to a value, fororThrowfactories.paginate({ withCount: true })returnstotalon offset and cursor pages and narrows its type tonumber. On a cursor page after the first, it sends one extra request to count the matching rows.db.$buckets.<name>is each bucket registered withbetterSupabase.buckets(), connected todb.$storage. The type follows$with(),$withoutPlugins()and thedb,sqlandadmin()repositories ofcreateServer(betterSupabase), anddb.$storageon a serverDbnow uses the caller's Storage client. Every framework adapter (next,hono,orpc,edge,mcp,astro,sveltekit,react-router,solid-start,tanstack-startandexpo) carries the registry through a new trailingBtype parameter, soctx.db.$buckets.<name>is typed in handlers, actions and routes.ctx.db.$storageandctx.db.$bucketsnow work on request contexts.better-supabase/testingaddsscopedSeed,withRollbackandTestUser.context.asUseralso turns off supabase-js trace propagation.genemitsWritableColumnOfandGeneratedColumnOf, and the schema types exportWritableColumnsandGeneratedColumns.
Fixes:
updatewith no columns to write reads the row and returns it, andupdateManyreturns a count of 0, instead of failing withinvalid_request. A caller that relied on that error needs to check for empty data itself. A plugin that leaves the patch empty still getsinvalid_request.createMany,upsertMany,updateManyanddeleteManytype their result byreturning.orderByacceptsundefinedvalues andupdateManydata no longer infers readonly arrays.- The client follows auth state only when the supabase client has it.
- Text filter escaping and case rules are documented, and
$rpctyping is pinned as stable API.
The generated column
memberships.tier_roleinsupabase/is a repo-only test fixture and does not ship in the package. -
Attachments and comments subjects taken from the subject registry now carry the registry's per-action keys:
subjects.<type>.permissions.uploadandmanagefor attachments,createandmoderatefor comments. The registry'sreadstays the key for reading the subject itself.blocks.<block>.options.subjects.<type>.permissionsoverrides them key by key.Doctor
BS345warns when an attachments subject has noreadoruploadkey of its own while its table's policies check more than tenant membership, so any member of the tenant would get the files of rows they can't open. -
Adds
better-supabase db query <file...>, which runs SQL files as multi-statement scripts against the local stack or the database in the connection string.--single-transactionkeeps all files or none. -
seed --applyanddb queryaccept--stack <name>(or$BSB_STACK) to connect to the stack insupabase/stacks/<name>/config.tomlinstead of the default local stack. -
Closes the gaps found on 0.9.0:
audit()takestenant_pathandtenant_function,admin({}, { as })names the acting member, optional RPC arguments acceptundefined,createHonoandcreateNextshare one server, OAuth server resources follow RFC 8707,jwtTypevalidatestyp, billing webhooks cover subscriptions, usage meters count distinct or computed values, and the doctor flags partitions without RLS (BS343). -
bs.middleware()frombetter-supabase/expohands the session it refreshed to the loaders andbs.requestcalls of the same request. They read the new cookies without calling Auth again, so a loader withrefresh: falserenders signed in on the first paint after an expired token, and each request makes at most one Auth call. Loaders that run without middleware still refresh on their own. -
Add the
ieqfilter operator for case-insensitive equality, on text columns and jsonbpathfilters. It sendsilikewith%,_and\escaped, sowhere: { email: { ieq: input } }matches only that address in any case.Add the
require-escape-likerule tobetter-supabase/lint, on as a warning inconfigs.recommended. It flags alikeorilikevalue taken from a variable, a property, or a template or concatenation withoutescapeLike(...). -
Realtime topic triggers read less and send less.
- A generated trigger function reads each parent row once per changed row, into a local record, however many values, payload keys and topics use it. A custom payload is built once for all topics. Before, every lookup ran again for the payload, for each topic's values and for each nested level. Run
sql syncto rewrite the functions; the messages they send don't change. topic.trigger(table, { when: { changed: ["status"] } }), andwhenon arealtime.triggersentry, send an update only when one of the listed columns changed. On a trigger for updates alone it becomes the trigger'swhenclause, otherwise an early return in the function. Inserts and deletes always send.- A delete whose lookup finds no parent row, such as a child removed by
on delete cascade, raises a warning that starts withbetter-supabase: realtime lookup found no rowinstead of skipping the topic silently. The Realtime docs have a new "Deletes and cascades" section.
- A generated trigger function reads each parent row once per changed row, into a local record, however many values, payload keys and topics use it. A custom payload is built once for all topics. Before, every lookup ran again for the payload, for each topic's values and for each nested level. Run
-
New block
better-supabase/blocks/vercel-marketplace(better-supabase add vercel-marketplace): installations, resources, plans, invoices and meter reports for an app listed on the Vercel Marketplace.createVercelMarketplace()verifies webhooks (x-vercel-signature, HMAC-SHA1), appliesintegration-configuration.removedand invoice events (the newest event wins), exchanges SSO codes and verifies theid_tokenagainst Vercel's JWKS, submits invoices and reports usage with retries. Only the service role calls it. -
vercelQueueBackend(client)inbetter-supabase/blocks/jobsruns jobs on Vercel Queues. Pass aPollingQueueClientfrom@vercel/queue(new optional peer,>=0.8 <0.9). It passestestQueueBackend. Vercel Queues keeps no dead letters and has no schedules, soschedulestill needs the SQL backend. -
An adopted
webhooks-outendpoints table has to choose its body format.Breaking config change: in adopt mode, when
columns.endpoints.formatmaps no column,sql syncnow refuses the config unlessblocks.webhooks-out.options.defaultFormatis set. Without a format column every endpoint getsdefaultFormat, whose default changed from the 0.8 body (standard) tocloudeventsin 0.9, so receivers broke without any change to the config. SetdefaultFormat: "standard"to keep the 0.8 body,"cloudevents"if your receivers read CloudEvents, or map a format column.Doctor reports the same config as
BS344(warning), and says whether the table has noformatcolumn or one the config doesn't map. The webhooks-out page listsdefaultFormatand the version 3 columns, and the new 0.9 to 0.10 guide covers the change. -
sealfrombetter-supabase/create/supabasenow accepts any object, so other OAuth connections on the Create page can reuse the sealed session cookie.
0.10.0 (2026-10-20)
-
Adopt mode takes enum columns where a block writes kinds and subject types. In adopt mode the tags block casts the
kindandsubjectTypevalues it writes and compares, andnext_numbercasts theentity, to the adopted column's type through the newbetter_supabase.as_column_type(value, target), sokind public.organization_tag_kindorentity public.workflow_subject_typeworks. An enum on any other text column a block writes a parameter or computed value into is refused instead of failing at runtime (columns a block writes only string literals into, such as the teamsstatus, may stay enums):sql syncandbetter-supabase adoptreport it when the schema files declare the enum, and doctor reports it as BS342. A module table spec lists its castable columns intyped, andModuleContext.cast(table, column, value)renders the cast. -
App table columns take
access: "read"oraccess: "server".sql syncthen grantsselect,insertandupdateon the columns signed-in users may use, by name, and the<table>_viewlists only the readable columns.genmarks a server columnselectable: false, so a default select leaves it out and the row type makes it optional; select it by name with the service role client.appTablesrefuses a required restricted column without a default, and a server column used as the subject title, a search column, a rollup or lookup source, or inevents.include. Tightening a column's access is a breaking change in the design diff, and Create design codes withaccessuse format 5.doctorcounts column grants for BS106, so a table whose grants list columns no longer reports "Table not granted to the Data API". -
App tables emit outbox events, and rules and the workflow builder react to them (ADR 0048).
appTables.<name>.events(trueor{ on, include }) adds a trigger that writes<type>.created,<type>.updatedand<type>.deletedto the outbox in the same transaction as the write. The payload is anAppTableEventDatawith the id, the tenant, the subject, theincludecolumns and, on update, the changed columns. It needs the outbox block.gen blockswritesappTableEvents, a typed event map.createRuleSinkruns the rules for each outbox event and dispatches their actions, andWorkflowBuilder.sink()starts the event triggers that match.- Rules get the built-in handlers
notifyAction,setFieldAction,webhookActionandworkflowAction. - A change to
eventsis the safe design changetable.events, and a design witheventsis format 4.
gentagsappTableEventsandappTableEventSchemaswith@public, so Knip doesn't report the one an app leaves unused. -
App tables get record history with per-field restore, upsert imports and a bulk set action.
appTables.<name>.subject.versions(trueor{ columns, auto }) registers the table with the versions block, so its rows get snapshots without an entry insubjects. It needs the versions block, and a design withversionsis format 4. A change to it is the safe design changetable.versions.versions.restoreFields(id, fields)writes back only the named fields. It fails withVERSION_FIELDS_EMPTY,VERSION_FIELD_UNKNOWNorVERSION_RESTORE_UNSUPPORTED.appTableImportbuilds an import keyed on one of the table's unique sets that updates existing rows (update: "fill"or"overwrite"), andpreviewImportcounts the rows it would create, change and leave unchanged.- The bulk action
appTables.setsets columns on the selected rows throughapp_table_set, as the caller. A row fails withAPP_TABLE_SET_EMPTY,APP_TABLE_SET_COLUMN,APP_TABLE_SET_SUBJECTorAPP_TABLE_SET_NOT_FOUND. - New recipes: record history and upsert import.
-
Add
better-supabase mcp, which serves the CLI to a coding agent as an MCP server on stdio. The read-only tools (doctor,blocks_list,config,gen_check,apply_dry_runand others) run by default, and--allow-writesaddsgen,sql_sync,applyandadd, each of which asks for the user's consent with a token before it writes.better-supabase/mcpnow exportsanswerMessageandanswerLinefor serving aProtocolServerover any transport, andcreateMcplogs one warning naming the tools a missing authorizer hides. -
Add
better-supabase/createandbetter-supabase/create/supabase. They hold the design model, schema parsing, previews, deploy plans, Supabase OAuth and the Management API client that/createused to keep inside the marketing app, so other apps can build on them. -
Add
better-supabase/create/lite.validateDesign(files)applies the files Create generates to an in-memory PGlite database through@supabase/liteand reports what Postgres rejects. Modules that needpgmqorbtree_gistare reported as skipped. -
Doctor checks the migrations that haven't run for statements that lock a table with rows: an index built without
concurrently(BS229), a foreign key or check added withoutnot valid(BS230), a column type change orset not nullwithout a validated check (BS231), a column added with a volatile default (BS232), a migration that takes an exclusive lock beforeset lock_timeout(BS233), and drops or renames (BS234, info). With--db-urlit checks the migrations the database hasn't applied; offline, the ones after the newdoctor.migrationSafety.sincesetting, or the newest one.initandadoptsetsinceto the newest migration. -
loadEnv,parseEnvandenvSchemareaddbUrlfromPOSTGRES_URLand thenPOSTGRES_URL_NON_POOLINGwhenSUPABASE_DB_URLandDATABASE_URLare unset, the names the Vercel Supabase integration and Vercel Postgres set.createPostgres()falls back to the same names in the same order. -
Add
migrationBetween(code, base, next)tobetter-supabase/create. It returns the migration that takes a deployed design to the next one for added tables and columns, and refuses breaking or unsupported changes with the changes that caused it. -
number-sequencesacceptsinandnot inlists of string or number literals inassignOn, such asnew.status in ('sent', 'overdue'), which its comma ban refused. A comma anywhere else outside a quoted string is still refused, and so is an unterminated quote, which could only fail at migration time. -
number-sequencesentities takepermission: the keypreview_numberchecks for that entity, such asinvoices.writefor invoices andquotes.writefor quotes. An entity without one keeps checkingblocks.number-sequences.permissions.assign.modulePermissionKeyslists the entity keys, sosql syncand doctor check them against the authorization provider, andModulePermissionKeygains an optionalsettingwith the config path that sets the key. -
sql syncnow keepsnumber-sequencescounters in step when a tenant changes its period. For an entity withtable,columnandperiodColumnthat setsperiodFrom, orformatFromwithperiod: "format", it adds anafter updatetrigger,bs_sync_number_period_<entity>, to each tenant table those columns name. When an update changes the tenant's effective period, the trigger runssync_number_sequences(tenant, entity)in the same transaction, so no number repeats; other updates leave the counters alone. It compares the old and new rows through the newnumber_period_kind(period, format), so a generated column works too. WithoutperiodColumnno trigger is added, as sync cannot run for such an entity. Drop a hand-written trigger that called sync on a period change. -
number-sequencesaddspreview_number(tenant, entity, at)andcreateNumberSequences().preview(): the formatted number the next document would get, in the tenant's format and period, without assigning it. Signed-in users may call it when they hold the block'sassignpermission (blocks.number-sequences.permissions.assign, defaultnumber_sequences.assign), which until now no function checked; others getNUMBER_FORBIDDEN.next_numberstays service-only, and documents keep getting their numbers from the trigger. -
number-sequencestakes the period of a new number from the row: withperiodColumnset, the trigger reads the period and the date tokens of the format from that column (adate,timestamportimestamptz, in UTC), such as an invoice's issue date, and falls back to the time of assignment while it is null.sync_number_sequencesreads adatecolumn in UTC too. -
The number-sequences block adds
sync_number_sequences(p_tenant, p_entity), a service-only function that raises each counter to the highest number its table already holds, per tenant and period, and never lowers one. Run it after seeding (select better_supabase.sync_number_sequences();at the end ofsupabase/seed.sql), after an import, or once after adopting tables whose documents already have numbers, so the next number does not collide. It reads the entities that settableandcolumnand parses each number with the entity'sformat; the period comes from{yyyy},{yy}and{mm}in the format, or from the newperiodColumnoption. -
number-sequencesnumbers each tenant in its own format.formatFrom: { column: "schema.table.column", key }reads a tenant's format from a settings column and falls back to the entity'sformat; a tenant format without{n}fails withNUMBER_FORMAT_INVALID. The newperiod: "format"restarts the counter by the format's tokens: monthly with a year and{mm}, yearly with only a year, never without either, so one tenant can number continuously and another per year.sequenceColumnalso stores the bare number next to the formatted one.sync_number_sequencesreads per-tenant formats and sequence columns, and the orders, invoices, quotes, deals and work-items modules use the tenant's format when they number through the block. -
number-sequencesentities takeperiodFrom: { column, key? }, the column that holds each tenant's reset period (none,year,monthorformat), so a tenant can keep a format such asINV-{yyyy}{mm}-{n}and still number on through the year. A null or empty value falls back to the entity'speriod, soperiod: "format"keeps deriving the period from the format; any other value fails withNUMBER_PERIOD_INVALID.number_period(tenant, entity)returns a tenant's choice.next_number,preview_numberandsync_number_sequencesuse the same period, and sync needsperiodColumnfor such an entity. -
realtime.triggersentries take everythingtopic.trigger()does: lookups through a parent row ({ from, via, select, key }), a payload object whose values are columns, lookups or{ sql }expressions, one event name per operation, extratopicswith their own values, andfunctionSchema.sql syncpasses each entry to the topic'strigger(), so the config and the call write the same SQL.topic.trigger()withoutbetterSupabasetakes lookups by database names too, withkeydefaulting toid, andrealtime-tablesis required only for triggers that callbetter_supabase.broadcast_topic(). -
The number-sequences and teams docs name the adopt-mode table keys the blocks read:
tables.sequences(nottables.numberSequences) andtables.members(nottables.teamMembers). A unit test now checks everytables.*andcolumns.*key on the blocks pages against the block's SQL modules. -
Fix block findings from the no-code research review.
create_share_linkchecks that the subject exists in the link's tenant and that the caller can read it, and raisesSHARE_SUBJECT_NOT_FOUNDorSHARE_SUBJECT_UNKNOWNotherwise. Links takemaxUses, andresolve_share_linkcounts each use, so a spent link stops resolving.drive_linkandget_shared_ai_chatalso check the link's tenant.runImportmarks an importfailedwith the rows it inserted when a batch throws, instead of leaving itrunning. A newrunninghook (withmark_import_runningin SQL) marks it running before the first batch.- A number sequence refuses a number set by hand unless the service role sets it (
NUMBER_MANUAL). save_viewdropsisDefaultwhen the view moves to another scope, list or team.- The app tables pgTAP file inserts a row of another tenant or user before it checks that a signed-in user can't read it, so the check fails when a policy leaks rows.
- App table and column names are at most 58 characters, and a table is refused when a constraint or index name it derives would pass Postgres's 63-character limit. A column default must fit the column's options and bounds.
better-supabase/presetexports these checks (appIdentifierError,appNameLengthError,appDefaultError,isAppDefault,appReservedColumns,APP_NAME_MAX) so builders validate with the same rules.
-
toDbErrornow classifies PostgREST and Postgres error objects, and a thrownPostgrestError, throughmapDbError, so a unique violation becomesconflict,PGRST116becomesnot_found, and permission and check failures get their kinds instead ofunexpected. Other errors and unknown values map as before. -
diffAppTablesmarks every change that rows already in the table may not pass as breaking, with steps: a newuniquecolumn or unique set, a removed option, a raisedminor loweredmax, a checked format, a new reference target, a new scope, and removingtimestamps,rankorsoftDelete. These get their own kinds (column.unique,column.options,column.bounds,column.format,column.reference,table.scope,table.unique,table.columns). Indexes, comments, the subject andonDeletestay safe.applycompares the whole design withappTables. It reports the tables the design leaves out as kept (data.kept), and it refuses a table or column rename without--allow-breaking. With the flag it prints thealter table ... renamestatements to run beforesql sync(data.renamesunder--json). -
genmakes thecolumnandsequenceColumnof eachnumber-sequencesentity optional on insert, so adopters no longer list them intables.<table>.insertOptional. -
number-sequencesrefuses a client that writessequenceColumnwithNUMBER_MANUAL, as it already did forcolumn. A signed-in user could send the bare number on a draft, which stayed visible until the trigger overwrote it on issue. Only the trigger and the service role write it now. -
createNumberSequences().next()sendsp_entity, the namenext_numberdeclares, so the call reaches the function instead of failing to find it.
0.9.0 (2026-10-19)
-
A record's activity timeline now includes its notification deliveries (with the
notificationsmodule) and its workflow runs (with theworkflowsmodule), asdelivery.<status>andrun.<status>entries withsourceset todeliveryorrun. Deliveries needactivity.readandnotifications.send, the same as the notifications client'ssubjectDeliveries; runs follow theworkflow_runsread policy.createComments().history()takessourcesto pick which kinds of entry to return, andlist_activitygains a matchingsources text[]argument. The comments module moves to version 6, so re-runbetter-supabase sql sync. -
better-supabase adopt <block> --tables <schema.table>maps a block onto tables the app already has. It reads the tables likeintrospect, matches the block's logical tables and columns to them (including likely renames such asorganization_idfortenant, andnullfor optional columns the table lacks), prints the mapping with a doctor-style report of what can't map, and writesblocks.<block>in adopt mode when everything maps.--dry-runwrites nothing and--jsonprints the entry, the mapping and the report.apply --preset <code> --adoptproposes the same mapping for every block of the preset that has a table under its default names, shows it before the config diff, and writes nothing when one of those tables can't be adopted.applynow also takes--snapshot,--db-url-stdinand--project-ref, and--jsonprints the config it writes and the blocks it adopted. -
Agent actors match support sessions. An agent
actlevel readsread_only(readOnlyon the actor; a non-boolean value makes the chain invalid), andagentClaims(claims, { agent, tools, readOnly })writes it.toolsis now optional: a level without it delegates every tool andtools: []none.createAgentRuntime({ actor })drops the tools a delegating agent didn't list and denies a call to them withAGENT_TOOL_NOT_DELEGATED, whichassertToolDelegatedthrows too, and a read-only agent makes the run read-only.actor_may_write()decides bykindfirst: support writes only withread_only: false, an agent unlessread_onlyistrue, and impersonation or an unknownkindnever. An impersonation token withread_only: falsecould write before; allow it through the provider'sauthorization.functions.actorMayWritetemplate instead.read_onlyis compared as a JSON boolean.better-supabase/testing/act-cases.json(andactCasesfrombetter-supabase/testing) listsactchains with the expected verdict, so other parsers can run the same cases. -
An RFC 8693
actlevel may be{ kind: "agent", sub, tools }.agentClaims(claims, { agent, tools })frombetter-supabase/serverbuilds it on top of the user's claims, and agent runs carry it asrun.act. An agent writes with the user's row level security unless its level setsread_only: true, and ascopeon its token limits it like an OAuth client. The read-only check in every SQL module knows the new kind, sosql syncrewrites each installed module.inboxAdapter({ identities })resolves each inbox contact before the handlers run and issues a run ticket for a contact linked to a signed-in user, whichticketOf(message)returns forforContext({ ticket }).testAuthorizationHooksalso checksautomation.mayPublishand that a support start cannot approve itself. -
createAgentRuntimefrombetter-supabase/ai-sdk/agentstakescaller(the invoking user, always the principal; the agent is only the actor),authorizeModel(checked before every model call, refusing withforbiddenbefore tokens are spent),results(filters knowledge hits before the model sees them),operations,permissionsandauthorizeTool(each tool is the operationai.tool.<name>, the provider's entry wins, andhighrisk waits for approval), andgateway(AI Gatewayuserand tags from the caller).searchToolandrecallTooltakeresultstoo. Breaking:gatewayOptionsdrops auserpassed in its second argument, souseronly ever comes fromcontext.userId; pass the caller's id there.GatewayContexttakestags. -
AI chat sharing moves onto the
share-linksblock.share_ai_chat,revoke_ai_chat_share,list_ai_chat_sharesandget_shared_ai_chatstay callable and useshare_links. Existingai_chat_sharesrows are copied, including the leaf. New links are stored only as a hash. -
API keys have a
kind. List the allowed kinds inblocks.api-keys.options.kinds(a check constraint enforces them) and passkindtocreate.create_api_keytakeskindas its last argument; the module's upgrade drops the old signature.apiKeyResolver,apiKeyClaimsandwithApiKeytake aclaims(key)hook that adds claims but cannot setsub,role,audorapi_key, andserviceRolesandclaimsreceive the key with thefieldscolumns. -
A Bearer token that starts with the API key prefix and
_now counts as an API key even when the rest is malformed.apiKeyResolverandwithApiKeyverify it, andverifyanswersinvalid, sobs_bad_keygetsINVALID_API_KEYlike a revoked or unknown key instead ofAPI_KEY_REQUIREDor a JWT error.createApiKeysreturnsisApiKey(token)for code that routes a Bearer token to either API key or JWT verification. Akeysobject withoutisApiKeykeeps the old rule. -
App table columns take
format(email,url,phone,long_text,color,rating,percent,currency),optionsfor a single or multi-select,minandmax,commentandidentity. Tables takeid: "bigint", compositeuniquekeys,indexesand acomment.sql syncrenders each as a named constraint, index or comment, and the pgTAP file checks them;email,url,rating,percent, options and bounds add a check. No key takes free SQL.A Create design that uses one of these keys gets
version: 1in its JSON (designFormat,DESIGN_FORMATfrombetter-supabase/preset); older designs encode to the same code as before, and a code newer than the installed release fails with a message to update. Create's column type picker is grouped (Text, Number, Date and time, Choice, Relation, Other) with Single select, Email, Rating, Autonumber, Person and Currency, which splits into<name>_minorand<name>_currency. -
A reference between two app tables scoped to the same tenant (a table that references itself included) now checks the tenant.
sql syncadds a unique(tenant, id)index on the target and a composite foreign key(tenant, column), so a row can no longer point at a row of another organization or workspace;on delete set nullclears only the referencing column. The pgTAP file checks each composite key.Migration: run
better-supabase sql syncand generate a migration. If an existing row already references a row of another tenant, the new foreign key fails to apply; fix or delete those rows first.Create can link two tables many to many from a table's menu ("Add many-to-many with…"), which adds a junction table with two required references,
on delete cascadeand a unique pair. A Tree primitive adds a table with aparent_idthat references itself. When you select a table, its edges show the delete action, and a reference that is unique ends in a one-to-one marker. -
App tables take
rollupsandlookups(ADR 0044). A rollup counts, sums or takes the minimum, maximum or average of a column of another app table that references this one, optionally only for the rows whose select column equals one option. A lookup reads a column of the row a reference points at. Both are structured keys, so a design never carries SQL, andresolveConfiglists the valid tables and columns when a key is wrong.sql syncwritespublic.<table>_viewwithsecurity_invoker = true, so each rollup counts only the rows the caller can read. Onlyauthenticatedandservice_rolecan read the view. The pgTAP file checks that the view runs as the invoker and shows a stranger no rows.genreads it as a read-only model (db.projectsView.findMany()).A design with rollups or lookups writes design format 3.
diffAppTablesreports a change to them as the safetable.computed. Create shows rollups and lookups as computed rows on the table and edits them in a Computed section of the table inspector.better-supabase/configexportsAPP_ROLLUP_AGGREGATESand theAppRollupConfig,AppRollupAggregateandAppLookupConfigtypes. -
An app table can be a subject:
appTables.<name>.subjecttakes atype, atitleandurl,search,permissions,rankandsoftDelete, and is merged intosubjects. Comments, attachments, tags, versions, watchers, activity and search then reach its rows.rank: trueadds arankcolumn with an index andsoftDeleteaddsdeleted_at. A design that usessubjectwrites design format 2.Migration: none for existing configs. A type in
subjectthat is already insubjectsfailsresolveConfig; remove one of the two.Create gets a Features tab on the table inspector: turning on comments, attachments, tags, versions or search adds the block and makes the table a subject, and the table shows a badge for each feature.
-
appTablesdeclares the tables your app owns.better-supabase sql syncwrites them into900_better_supabase_app_tables.sqlwith the scope column (per tenant, per user or open to signed-in readers), row level security, grants, indexes and theupdated-attrigger, plus a pgTAP test that checks each table's policies and that a stranger can't read or insert outside their scope. Columns take a closed list of types, defaults from an allowlist and references to another app table,auth.usersor a block's table, which follows the block's renames.better-supabase/presetencodes a Create design (app tables, extra columns on block tables and canvas positions) into a code that rides on the/createURL as&design=:encodeDesign,decodeDesign,designOf,designConfig,designConfigSource,designInstallCommandanddesignApplyCommand. The preset catalog lists the table each block'sextraColumnsextends.init --preset <url>writes the design'sappTablesandextraColumnsinto the new config, andapply --preset <url>merges them into the config you have. -
approval_eligiblealso asks the provider'sisApproverfor the kind<type>.<action>, and never for the requester.createApprovalstakesapproverOf,wakeOnApprovalfrombetter-supabase/workflow-sdkresumes a run waiting on a request id when the request is approved, rejected, expired or cancelled, and a workflow-builder approval node can file an approvals request and wait on its id. -
With the
approvalsSQL module installed, AI-chat tool calls that wait for approval (ai_tool_approval, actionrun) and support access requests for a tenant (support_request, actionstart) also file an approval request. Deciding either side decides the other:decide_approvalapproves or denies the tool call and approves or closes the support request, anddecide_ai_tool_approvalorapprove_support_requestsettles the approval request. The owning module still decides who may approve, these requests can't be delegated, andapprovals.readalone doesn't list them, so tool inputs and support reasons stay with their approvers. -
AsyncAPI channels now come from the same
defineTopicdefinitions thatsql syncturns into Realtime policies. PasstopicsFrom(module)(frombetter-supabase/asyncapi) todefineApi({ topics }). Each channel gets its broadcast events, its presence schema and anx-better-supabase-realtime-statusofbetafor private topics (Realtime Authorization is still in public beta) orgafor public ones. A topic gets a send operation only when it setsclientSend: true; before, every topic got one.defineTopictakes the newpresenceSchema,clientSendandstatusoptions, and a topic exposesevents,clientSend,permissionandstatus.better-supabase specloads therealtime.policies.frommodules with the loadersql syncuses. It warnsasyncapi-topic-undocumentedfor each topic the AsyncAPI document leaves out, and--watchrenders again when a topic module changes.The new
dataApioption documents the Supabase Data API next to your routes:/rest/v1/<table>operations and/rest/v1/rpc/<function>calls, with database column names, the API key and JWT schemes, the PostgREST error body and their ownserversfromsupabaseUrl. Operations take an optionalserverslist, which the OpenAPI formats render. New diagnostics:data-api-server-missing,data-api-table-unknownanddata-api-function-unknown. -
The audit block reverts row changes:
audit.revert(entryIds)(SQLrevert_audit_entries) writes the old values back as the caller, newest entry first, all or nothing, and refuses withROW_CHANGED_SINCEwhen a row changed after the entry. Members need the newaudit.revertpermission, which admins have by default. The result carries an undo token that reverts the revert. The saved-views read policy now evaluatesauth.uid()once per query when the teams module is installed. -
Fixes from an audit of the blocks, the jobs worker, the commerce adapters and the CLI.
Breaking:
fromStripeAmountreturns aResult<Money>. It refuses an amount that isn't a safe integer, or an ISK or UGX amount with a fraction of the minor unit, withinvalid_inputand the hintSTRIPE_AMOUNT_PRECISION, where it used to truncate. The Stripe payments and tax adapters return that error instead of a wrong amount.The notifications and settings blocks split their own-row
for allpolicies into read, insert, update and delete policies, soactor_may_write()guards writes only and a read-only support session can still read. Runbetter-supabase sql syncand generate a migration.- The data-lifecycle purge checks the legal hold and the due date before it deletes storage objects or calls a webhook.
- A jobs worker aborts a job's signal when its lease can't be extended, and reports
JOB_LEASE_LOSTthroughonErrorinstead of completing a job another worker may hold. A failedcompleteis reported too. - The idempotency middleware answers
409withIDEMPOTENCY_KEY_LOSTwhen the lock expired before the response was saved, and the request fingerprint includes the query string. - The webhook inbox passes its handler an
AbortSignalthat aborts when the lease can't be renewed, and then leaves the message to the next worker. - The outbox treats a handler that returns a failed
Resultas a failure, so the event is retried. deleteAccountsucceeds on a retry for a user that Auth already deleted, and still removes the listed storage objects.- Invoice deposits are computed in
numeric, so line totals round half away from zero past 2^53. - The search block adds a partial index for rows waiting for an embedding.
env --out,env.outputandenv --fromrefuse a path outside the project root.- A
42501error says "permission denied" to the client, and keeps the object name and PostgREST's grant recipe indetails. queueBackend({ client, schema })calls the wrappersblocks.jobs.apiwrites into that schema, for the full feature set over the Data API.clientalone still uses thepgmq_publicRPCs.supabaseCollectionfrombetter-supabase/tanstack-db/supabaseworks withcasing: 'camel'and with tables outsidepublic: it renames filters, bodies, rows and Realtime payloads, and runs requests and Realtime listeners in the table's schema.- A subject's
deletedAtcolumn becomes the table'ssoftDeleteflag ingen(it wins overplugins.softDelete.column), and declared metrics skip those rows unless the metric setsincludeDeleted: true.
-
createServer(betterSupabase, { authorization })takesAuthorizationHooks(defineAuthorizationHooksfrombetter-supabase/server): optionalautomation,support,delivery,identities,chat,approverOfandticketshooks, so one authorization provider decides publishing, support sessions, fan-out, identity links, chat actions, approvals and run tickets.testAuthorizationHooksfrombetter-supabase/testingchecks that they fail closed.The
authorizationconfig gainsfunctions.isApprover({kind},{subject},{tenant}),functions.permittedfor checks on one instance, andoperations, one table of the permission each workflow node, MCP tool, AI tool and inbox command needs.Breaking: with
authorizationset,blocks.access.modeldefaults toprovider, socan(),tenant_ids_with()and every module check answer from the provider. Setmodel: "roles"to keep the built-in roles; doctor BS414 then reports policies and functions that call the access contract.functions.canApproveis deprecated in favour ofisApproverand still read whenisApproveris unset; doctor BS415 warns while a provider sets it, andbetter-supabase codemod 0.9lists each use. -
Add client controllers and hooks for the
billing,usage,entitlementsandsettingsblocks, each with/react,/vue,/svelteand/solidentries.usePlanPicker()(better-supabase/blocks/billing/react) lists your plans with the current one and starts Checkout through a server action you pass, so Stripe is only called on the server.useUsageMeter()(better-supabase/blocks/usage/react) reads this period's usage per meter with its fraction of the quota.useFeatureGate()(better-supabase/blocks/entitlements/react) tells whether the active organization's plan includes a feature from the session's features claim, andhasEntitlement()now also takes the client'suseAuth()snapshot.useSettings()(better-supabase/blocks/settings/react) edits one scope of adefineSettings()definition withfieldsgenerated from each key's Standard JSON Schema, andsetField()for generated forms. The plan picker, usage meter, feature gate and settings layout recipes show them in the Next.js and Expo examples. -
Blocks sit in 16 categories instead of 10, so the catalog,
blocks list --categoryand/blocksgroup them the way an app is built.BlockCategorytakes the new ids:Old category New category foundationidentity(access, actor, identities, mfa, sessions, sso, subjects),tenancy(tenant, organizations, teams, profiles, settings, reserved-slugs) anddatabase(updated-at)collaborationcollaboration, andmessaging(notifications, push, inbox)workwork,people(employees, hiring),identity(access-requests) anddatabase(rank)schedulingscheduling, andpeople(time-tracking)operationsgrowth(onboarding, waitlist, announcements, flags),admin(audit, data-lifecycle, metrics, support-sessions) andautomation(workflows, workflow-builder, workflow-sdk-world)platformdeveloper(api-keys, credentials, service principals, signing keys, shared signals, the webhook blocks, rate-limit, idempotency),automation(jobs, outbox, streams),identity(grants) anddatabase(ensure-rls, pgtap, jsonb-schemas, number-sequences, read-sets, realtime-tables)aiai, andautomation(connectors)crm,commerce,contentunchanged better-supabase/presetadds 14 named presets, so/createandinitoffer 22 in five groups (PRESET_GROUPS,NamedPreset.group):consumer(per-user data withscope: "user"),helpdesk,marketplace,people,drive,docs,invoicing,forms,ai-chat,ai-agents,developer-api,automation,enterpriseandadmin. Every preset after the starters builds onsaas. The existing presets keep their blocks, andNamedPreset.conventionsholds the conventions a preset sets over the defaults.The UI recipes in the skill's
references/ui-recipes.mdgrow from 15 to 32, with 46 more listed as planned, each naming what it waits for. A recipe now has akind(screenorcomponent), can span several blocks, and lists only the platforms it has code for. Each block manifest'srecipesnames the recipes that use the block. -
More blocks meet the block contract.
createAuditLogis nowcreateAudit. The clients of agents, ai-cache, ai-chat, ai-files, ai-providers, ai-tasks, announcements, api-keys, attachments, audit, billing, bookings, bulk, calendar, comments, connectors and custom-fields takehooks(andlogger) and run them around every method, and audit's purge calls andactivitySinkgo throughblockCall, so error mappers apply.Access-requests, agents, ai-chat, ai-files, ai-tasks, announcements, api-keys, approvals, attachments, bookings, calendar, catalog and collections take
options.extraColumnson their main table and afieldsStandard Schema on the client. The module adds the columns, its writes take them (columns a write leaves out keep their value or default) and its reads return them underfields; the client validates them on writes, parses them on reads and merges them into the rows it returns. WithoutextraColumnsthe SQL is unchanged. -
comments,connectorsandrate-limitfollow the block contract.createRateLimittakes one options object:createRateLimit({ sql: postgres.admin })orcreateRateLimit({ transport: rpcTransport(adminClient) })replacescreateRateLimit(source, options), withschema,mappers,hooks,loggerandtemporalnext to it.createBlocksbuilds therate-limitblock from its sharedtransport.commentsandconnectorstakeoptions.extraColumns(oncommentsandconnector_servers) and a Standard Schemafieldsoption oncreateCommentsandcreateConnectors.createandeditof comments, andservers.createandservers.updateof connectors, validate thefieldsthey get and write them; every comment and server read returns the columns parsed underfields, andcomments.copycopies them.create_commentandedit_commenttake afields jsonbargument only when extra columns are configured;save_connector_servertakes them in its existingfieldsobject.Every SQL module that takes a
fields jsonbargument for its extra columns now names itfields:request_access,reserve_ai_file,store_ai_file,create_api_key,request_approval,create_attachment,save_product,create_collectionandrename_collectiontookextra_fieldsbefore. Each module drops the signature it doesn't create, so turningextraColumnson or off never leaves two overloads a call matches, and the module contracts list the argument when it exists. -
Blocks from
notificationstosettingsfollow the block contract.onboarding,outboxandsettingshave acreate<Name>(options)creator, and their manifests build it.createOnboarding({ transport })replaceschecklist.connect(...): its methods take the checklist first (onboarding.complete(gettingStarted, "invite", organizationId)), andcreateOnboardingControllertakesclientandchecklistinstead ofscope.createSettings({ settings, transport })replacessettings.connect(...), with flat methods (getUser,setUser,resetUser,getOrganization,setOrganization,resetOrganization,getPlatform,setPlatform,resetPlatform);defineSettingsreturns only theschemas.createOutbox({ transport, source })replacescreateOutbox(source, options): passsqlTransport(postgres.admin)for a server connection, andservicefor the consumer calls whentransportacts as a user.hooks(andlogger) now work oncreateNumberSequences,createPush,createRank,createRateLimit,createRelations,createReminders,createSavedViews,createServicePrincipals,createOnboarding,createSettingsandcreateOutbox; job handlers call their methods through the hooks.createNotificationssends its delivery calls throughblockCall, sodeliver()rejects with the mappedDbError.options.extraColumnsand a typedfieldsoption cover the main table ofinvitations(asinvitationFieldsoncreateOrganizations),notifications,orders,pipelines,promotions,push,relations,reminders,saved-viewsandservice-principals, andfieldsnow types the columnspartiesandquotesalready took. Writes takefieldsand validate them before the call; reads return them infields, built withjsonb_build_object, and parse them with the schema. WithoutextraColumnsthe SQL is unchanged. -
The 14 blocks with a headless controller (ai-chat, announcements, bookings, calendar, forms, inbox, notifications, onboarding, reactions, saved-views, search, undo, workflows and workflow-builder) get
better-supabase/blocks/<name>/vue,/svelteand/solidentries. Each exports the React hook names (useInbox,useUndoStackand so on) over the same controllers: Vue returns a shallow ref of the snapshot, Svelte a readable store and Solid an accessor fromfrom, with the controller's actions next to it. They take the controller's options;authandportscome frombetterSupabase(bs),setBetterSupabase(bs)or<BetterSupabaseProvider>unless you pass them. The work starts on mount, never during server rendering, and the controller is disposed with the component.testControllerBindingfrombetter-supabase/testingchecks that a framework binding renders a controller's snapshot, follows its changes, passes its actions through and stops it on unmount. The React, Vue, Svelte and Solid bindings run it. -
Every block exports a manifest built with
defineBlock(commentsBlockfrombetter-supabase/blocks/comments): its SQL modules, option keys, its own events, the ports it provides and consumes, its creator, category and UI recipes.createBlocks(options, blocks)takes manifests and wires them on their ports (notifier,files,attachments,workflows,sink) instead of on names.block.with(options)sets a block's own options, andblock.using(create)builds it with your own call to its creator.defineBlocks(blocks, ...appEvents)types the events of every block and the app's.Breaking:
createBlocksno longer takes factories or theaiTaskNotification,reminderNotification,metricEventsandmetricTimeoptions. UseaiTasksBlock.with({ notification }),remindersBlock.with({ notification })andmetricsBlock.with({ sink: { on, time } }).- The closed
BlockEventMapis gone. Each block exports its own event map (CommentsEventsandcommentsEvents),onBlockEvent(betterSupabase, events, pattern, handler)takes the events to type by,blockEmitter,emitBlockEvent,BlockEvent,BlockEventSchemasandSubjectEventTypetake an event map, anddefineEventsdeclares app events. createDrivetakes the attachments block asattachmentsinstead of building one (attachmentsSchema,requireScananddownloadTtlmove to that block), and the workflow builder takes the workflows block asworkflowsfor schedule triggers.createBuilderis renamedcreateWorkflowBuilderandcreatePushDevicesis renamedcreatePush.
-
Blocks are configured under a top-level
blockskey inbetter-supabase.config.ts, the foundation blocks (tenant,access,updated-at,ensure-rls, ...) included.sql.modulesis removed;sqlkeeps the SQL-wide settings (workflow,dir,prefix,testsDir,schema,api). The resolved config carriesblocksandblockNames,sql addeditsblocks, andschemas/config-v1.jsondescribes the new key. The config types are renamed to match:BlocksConfig,BlockConfig,AccessBlockConfigandBlockMode. Code that readsconfig.sql.modulesfrom a loaded or resolved config must readconfig.blocksinstead. -
More blocks meet the block contract.
createFlagAdminis nowcreateFlags.createJobs({ queues, sql })replacescreateJobs(source, queues, options), taking its store asbackend,sql,clientortransport, and the jobs block is built bycreateBlocks.createIdempotency({ sql })andcreateIncomingWebhooks({ sql })take their connection as an option, and the entitlements block getscreateEntitlementswithhasandvalue.Deals, drive, employees, engagements, flags, forms, hiring, inventory and invoices take
options.extraColumnson their main table and a Standard Schema asfields, which types and parses the columns on reads and validates them on writes.create_form,update_formandsave_locationtake afieldsargument. Data-lifecycle, entitlements, flags, idempotency, identities, imports, inbox, incoming webhooks, jobs, knowledge and memory accepthooks; inbox, knowledge and memory also take hooks per method group. Calls over a transport go throughblockCall, somappersapply to them. -
SQL module comments and error messages name the
blocksconfig key instead of the oldmoduleskey, for exampleblocks["support-sessions"].options.allowWritesin theSUPPORT_WRITES_DISABLEDerror. -
Add the bookings block (
better-supabase/blocks/bookingsandbetter-supabase/blocks/bookings/react): bookable resources with weekly hours, exceptions and a capacity, services with a duration and buffers, open slots from theavailable_slotsSQL function, holds that abookings.expire-holdsjob cancels, an exclusion constraint that refuses double bookings (the module installsbtree_gist), public booking through a share link with a rate limit and an access token, confirmed bookings copied into the calendar block, customer reminders, and auseAvailableSlotshook typed for headless time pickers such as ReUI's. -
The bulk module adds a
trash.trashaction when the trash module is installed, so a list's bulk bar can move many rows to the trash in one call or a background run, each row through the trash block's own checks. -
Add bulk actions (
better-supabase/blocks/bulkand thebulkSQL module).bulk.runappliestags.set,stateMachine.transition,relations.linkor an app's own action to up to 500 rows in one call with a result per row, andbulk.startputs larger sets on the jobs queuebulk, where each step runs as the user who started the run and broadcasts its progress on a Realtime topic. -
Adds the calendar block (
better-supabase/blocks/calendarandbetter-supabase/blocks/calendar/react, SQL modulecalendar). It stores calendars, events with RFC 5545 recurrence, overrides and attendees.occurrences()expands series with the reminders block'sexpandRule,editOccurrenceandeditFollowingoverride one occurrence or split a series,importIcsandexportIcsread and write iCalendar files, and a share link to a calendar serves an iCal feed.useCalendarreturns events in the shape an event calendar renders.expandRuletakes awindowso long-running series expand only the occurrences in a range, andrevoke_share_linkno longer fails with an ambiguousidcolumn. -
Close the gaps CentraKit hit while adopting better-supabase:
- Support sessions work with an app-owned request context, and the proxy prunes stale cookie chunks and takes an auth-outage hook.
createJobs,createIdempotencyandwithLeaseaccept a block transport (rpcTransport), so job stats, dead jobs, retries, idempotency keys and leases work through theblocks.<name>.apiwrappers without a direct Postgres connection.- Jobs, idempotency, rate limits, outgoing webhooks and usage get TypeScript
purgemethods andpurgeJobhandlers for thepurge_*functions;purgeAuditLogand the webhook inbox purge accept a transport. - Behaviour change:
cancel_organization_deletionasks the access contract for thecancelDeletepermission (organization.deleteby default) through the newmember_can_while_deleting(), instead of hard-coding theownerrole. With the default roles nothing changes; with an authorization provider, any member the provider grants the key can cancel. An access module incustommode keeps the owner check. - Attachments take
subjects.<type>.permissions(read,upload,manage), and attachments and comments takesubjects.<type>.scope: a scope the authorization provider declares, so a grant on the subject record counts next to one on the tenant. Comments'readableByalso takes{ sql, enforce: true }, which applies it to the read policy. - The
realtime-tablesmodule addsbetter_supabase.broadcast_topic(), a row trigger that fills a topic's{column}placeholders from the row and sends the change.topic.trigger(table, options)returns thecreate triggerstatement, andrealtime.triggersmakessql syncwrite them next to the topic policies. - Incoming webhooks hand verified deliveries to an
IncomingDestination(apiVersion: 1, checked bytestIncomingDestination):inboxDestinationstores them in the webhook inbox as before, andjobsDestinationenqueues them on a jobs queue once per endpoint and message id, with the endpoint's tenant and metadata.jobs.enqueueOnce(enqueue_job_oncein SQL) is the queue side: a key stays taken after its job completes. webhooks-inandwebhook-inboxgainmode: "adopt"over an app's own endpoint and message tables, with renamed columns and optional ones mapped tonull. Their functions stay inbetter_supabase. In managed mode a column mapping is an error.credentialsgainsmode: "adopt"over an app's own secrets table (provider,nameand optionaltenant,scope,vaultId,secret,updatedAtcolumns), withsecretStorage: "vault"(a Vault id per row, deleted with its row) or"column".credential_get,credential_setandcredential_deletekeep their signatures, sovaultCredentials()reads the table unchanged; avaultref names another provider's row as<provider>:<name>. Doctor reports a table or column an adopt-mode module maps that the live database lacks (BS330).
-
supabaseClaimFixturesaddsagentRunReadOnly, an agent level withread_only: true. The newsupabaseInvalidClaimFixtures(with theSupabaseInvalidClaimFixturetype) lists the claims better-supabase refuses, each expecting{ kind: "invalid", reason: "actor", code: "ACTOR_INVALID" }: a 0.5.0 support token (session_idwithoutkind), a support or agentread_onlythat is not a boolean, an agent with asession_id, an empty tool name ortoolsthat is not a list, an unknownkind, and a nested level withoutsub. They are plain data, so other libraries can run the same cases. -
The CLI has an agent mode. When a coding agent runs it (Cursor, Claude Code, Codex, Gemini CLI, GitHub Copilot and the others
@vercel/detect-agentknows), it prints the JSON result envelope by default, never prompts, and answers what it can't decide alone with exit code 3 andstatus: "action_required".--agent auto|yes|noand$BETTER_SUPABASE_AGENToverride the detection, and--no-jsonkeeps text output.A missing value returns
input_requiredwithmissing,choicesand anextcommand that fills them in. Destructive work returnsconsent_requiredwith atoken:--forceover files the CLI didn't write, andseed --applyagainst a database that isn't on this machine. Rerun with--confirm <token>once the user agrees;--yesdoesn't replace it.initat a workspace root without--packagenow exits 3 withinput_requiredinstead of 2, andskills install --agentis nowskills install --for, so the global--agentkeeps one meaning. -
The CLI's command groups (
sql,blocks,preset,skills,spec,scaffoldandcodemod) are real subcommands, each with its own help, and a flag has one meaning everywhere.openapi emitmoves tospec emit openapiandspec checktospec emit --check. These flags are renamed:0.8 0.9 init --withinit --integrationadd --frameworkadd --integrationadopt --fromadopt --tablesgen --tasksgen --onlygen --out(a directory)gen --out-dirintrospect --formatintrospect --kinddoctor --strictdoctor --fail-on warningenv --printenv --out -env --fromenv --status-fileskills install --fromskills install --sourceskills install --agentskills install --forsql add --force(hook overlap)sql add --allow-hook-overlapAn old command or flag exits with code 2 and a
command_movederror whosesuggestionis the new call.better-supabase codemod 0.9rewrites these calls inpackage.jsonscripts and GitHub workflows and lists them in other shell files. The package adds absbbin next tobetter-supabase. -
Add
better-supabase completion bash|zsh|fish. It prints a script that completes commands, subcommands, options and their values (block names, presets,gen --onlytasks, doctor rule codes) for bothbetter-supabaseandbsb. Addeval "$(better-supabase completion zsh)"to~/.zshrc, or the line for your shell from the shell completion page. -
better-supabase/cliexportscreateCli({ commands })in place ofregisterCommand. It returns a CLI with your commands next to the built-in ones, so two CLIs in one process share no state.defineCliCommandnow marks each command withapiVersion: 1, andcreateClirefuses a command without it or one that takes a built-in or reserved name (login,logout,whoami,link,projects,deploy,cloud).The 0.2 command form,
(context) => CommandResult, and theCommand,CommandContextandParsedArgstypes are removed. Wrap such a command indefineCliCommand:// Before registerCommand("schemas", ({ args }) => ({ code: 0, output: args.rest.join(" "), })); // After const cli = createCli({ commands: { schemas: defineCliCommand({ meta: { name: "schemas" }, args: {}, run: async (args) => ({ code: 0, output: args._.join(" ") }), }), }, }); await cli.run(process.argv.slice(2), { cwd: process.cwd(), env: process.env });doctor --metadatanow reports a conflicting flag with the same message asgen --metadata, anddoctorlists--snapshot,--db-url-stdinand--project-reffirst in its help. -
The CLI reports three more specific problem codes, all exit 2:
unknown_flagfor an option the command does not take,invalid_valuefor an option or environment value it does not accept (an enum,--agent,--cwd), andflag_renamedfor a renamed flag, which wascommand_movedbefore. A script that matchedusagefor these cases should match the new codes.ExitCodenow includes65and143. On SIGINT or SIGTERM a run gets 2 seconds to clean up before the process exits, and a second signal exits at once. -
The CLI reports every failure with an error code and a matching exit code. The errors page lists each code, and
--jsonputs it incode.- Exit code 3 means you have to act first, 130 means a cancelled prompt or Ctrl-C, and 143 means SIGTERM. A cancelled prompt no longer counts as "no".
- A path flag outside the project root (
outside_root) exits 2, like other usage errors, instead of 1. --cwdhas to name an existing directory.--db-url-stdinandgen --metadata -fail at once when stdin is a terminal, instead of waiting for input.$CI=falseand$CI=0no longer turn prompts off.- The CLI never downloads the Supabase CLI through
npx --yes. It runs$SUPABASE_BIN, thennode_modules/.bin/supabase, thensupabaseon thePATH, and fails withsupabase_cli_missingotherwise. The child process gets the run's environment and stops on Ctrl-C. - Install commands quote version ranges and directories that the shell would split or expand.
tsconfig.jsonandpackage.jsonare read as JSONC, so comments inside strings and trailing commas parse correctly.- The config file is discovered once per run, and the local stack's database URL is looked up once.
- The package no longer ships
dist/cli/bin.d.ts.
-
Every CLI command that writes files now goes through one file plan. Each file gets one line:
Created,Updated,Unchanged,Skipped(with the reason) orRemoved, andWould createorWould updateunder--dry-run. These lines replaceWrote,KeptandWould write, so update any script that matched the old words. Under--json,data.fileslists every file with its outcome;seed,envandopenapi emitno longer returndata.wrote, andgenno longer returnsdata.removed.Every writing command takes
--dry-run, which prints a diff and writes nothing, and--check, which exits 1 on drift.gen,introspect,scaffold,seed,env,keys,skills,spec,codemod,apply,adoptandopenapi emitgain the flags they were missing. A command writes its files together, so a failed run leaves none half written. It refuses paths outside the project root and never prints the contents of.env.localor the signing keys in a diff.A generated file without the
Generated by better-supabaseheader was written by hand.genused to overwrite it; now every command skips it and exits 1 with the newfile_conflicterror code. Pass--forceto overwrite it. -
The CLI keeps stdout for the command's output. Prompts, spinners, warnings and notices go to stderr, and each stream is colored only when it is a terminal. Outside a terminal, progress prints one plain line instead of a spinner.
--no-colorturns colors off on both streams, likeNO_COLOR.--debugprints the stack trace of an error, each child command the CLI runs with its exit code, and how long the run and each step took, all on stderr.gen --watch --jsonandspec emit --watch --jsonprint one result envelope per run on its own line (NDJSON) instead of text.spec emit --watchnow waits for a config that fails to load, the waygen --watchdoes, instead of running with the old one.- Commands registered with
defineCliCommandgetlog(info,warn,error,debug,progress),paintandemitin their context.CliIotakesstderrColorandspinner, andPrompterno longer has aspinnermethod.
-
Breaking for scripts that read
--json: every command now prints one result envelope that followsschemas/cli-result-v1.json. It hasstatus(success,errororaction_required), the command's result underdata, Problem Details undererror, and the commands to run next undernext. Read.data.stalewhere you read.stalebefore, and.error.codewhere you read.code. A failed--checkkeeps itsdata, so the stale files and the error come in one document.Every command returns data now, including
init,add,env,keys,skills,openapi,scaffold,seedandsql.--checkdrift reports thecheck_failedcode, doctor and spec findings reportfindings, and a usage error keeps theusagecode and prints the command's usage in a terminal. In a terminal,init,add,sql addandsql upgradelist the commands to run next underNext:. -
The CLI checks its arguments before a command runs. An unknown option, a value outside an option's choices, or an argument a command doesn't take is now a usage error (exit code 2) with a suggestion, such as
Unknown option --chek for better-supabase gen. Did you mean --check?. Under--jsonthe error is a Problem Details document with theusagecode.Help is grouped by task (set up, generate, local stack, inspect, maintain), and each command's help lists its arguments, options, examples, side effects and docs page.
better-supabase --help --jsonprints every command, option and side effect as one document that matchesschemas/cli-commands-v1.json, andbetter-supabase <command> --help --jsonprints one command. -
better-supabase codemod 0.9movessql.modulesto the top-levelblockskey inbetter-supabase.config.ts(and.mts,.js,.mjs,.json), keeping the comments around it and droppingsqlwhen nothing else is left in it, and renamesModulesConfig,ModuleConfig,AccessModuleConfigandModuleModetoBlocksConfig,BlockConfig,AccessBlockConfigandBlockMode. A config that sets both keys, or keepssql.modulesin an environment block, is listed for review. A config that still setssql.modulesfails to load withconfig_invalidand names the codemod. -
Add the
access-requestsblock (better-supabase/blocks/access-requestsand theaccess-requestsSQL module): members ask for a role, for a set time if they like, and the request goes through the approvals module. The final approval grants the role,end()andexpire_access_grants()put the previous role back, and the module recordsaccess.requested,access.request_approvedandaccess.ended. With theprovideraccess model the adapter grants the role from the events. Approvals gains an internalopen_approvalthat files a request under an explicit policy. -
Add the
approvalsblock (better-supabase/blocks/approvalsand theapprovalsSQL module): approval requests with steps per subject type and action, approvers by permission, role, team or user, a required count, delegation, self-approval off by default, expiry and reminders. The final approval runs a state-machine transition or enqueues a job, approvers and requesters are notified through the notifications module, and the module recordsapproval.*events. State machines gainrequiresApproval, which reserves transitions for an approved request (STATE_APPROVAL_REQUIRED). -
Add the
documentsblock (better-supabase/blocks/documentsand thedocumentsSQL module) and thebetter-supabase/yjsprovider. A document is a Yjs update log and a compacted snapshot attached to any subject, with a privatedocuments:<id>Realtime topic for edits and presence under the subject's read and write rules.createDocumentProviderconnects aY.Doc: it loads the stored state, stores and broadcasts each edit, and catches up after a reconnect.compactDocumentmerges the log for thedocuments.compactjob, and with the versions module a document's state can be saved as a version.yjs(>=13.6 <14) is a new optional peer. -
Add the
reactionsblock (better-supabase/blocks/reactions,better-supabase/blocks/reactions/reactand thereactionsSQL module): emoji reactions on any registry subject, comments and inbox messages, checked against each subject's own read policies, with counts,reactedand the first actors per emoji, custom emoji per organization, areactions:{organizationId}realtime topic anduseReactions(). The module recordsreaction.addedandreaction.removed. With it installed, the inbox'sreact_to_messagestores reactions in the table and keeps the message'sreactionscolumn as a copy; installing it copies existing message reactions. -
Add the
trashblock (better-supabase/blocks/trashand thetrashSQL module): soft delete through each subject'sdeletedAtcolumn, children trashed in the same batch, restore with unique column checks, a list per organization,purge(),purge_expired_trash()afterretentionDays, andis_trashed()for policies. The module recordssubject.trashed,subject.restoredandsubject.purged. -
Add the
versionsblock (better-supabase/blocks/versionsand theversionsSQL module): numbered snapshots of any subject with a content hash, labels, debounced auto snapshots, versions frozen when a status column changes, retention, restore through columns or an apply function, anddiff()as an RFC 6902 JSON Patch.createPatch()andapplyPatch()are exported for any JSON value. The module recordsversion.created,version.restoredandversion.deleted. -
The
collectionsSQL module andbetter-supabase/blocks/collectionsadd favorites and lists on any record registered inconfig.subjects. Favorites are a member's own stars, ranked for a sidebar (star,unstar,starred,reorderStar). Lists are named, static collections of one record type owned by a user, a team or the organization (create,rename,archive,add,remove,reorder, keyset-pagedentriesandlistsOf); an entry is visible only when the caller can read its record, and deleting a record withcascade: truedeletes its entries and stars. A saved view can keep to a list throughstate.collectionIdandcollections.where(id), and the bulk module gains thecollections.addaction. -
The comments module (version 4) filters activity per record when the
subjectsmodule is installed: the read policy onactivity_entriescheckscan_subject(subject_type, subject_id, 'read')for every registered subject type, andlist_activityreturns an empty timeline for a subject the caller can't read. Members no longer see entries on records they can't read, or on deleted records. Entries without a subject, or on a type the registry doesn't list, keep the tenant check alone.With the audit module installed with
options.readPolicy: true, a subject's timeline also returns the audit log entries for its row, gated by the audit read policy.ActivityEntryhas a newsourcefield (ActivitySource,"event"or"audit"), so code that buildsActivityEntryvalues by hand needs to set it.With the notifications module installed, the author of a comment and the users it mentions follow the subject as
participatingwatchers innotification_subscriptions; an existing row, such asignore, is kept.options.follow: falseturns this off. Runsql syncto rewrite the installed module. -
Add client controllers and hooks for the
commentsandorganizationsblocks.createCommentsControlleranduseComments()(better-supabase/blocks/comments/react,/vue,/svelteand/solid) load one subject's thread and keep it current afteradd,editandremove, which return aResult.createOrganizationsControlleranduseOrganizations()(better-supabase/blocks/organizations/react,/vue,/svelteand/solid) list the caller's organizations, read the active one from the tenant claim, and switch withswitchTo(), which refreshes the session whenswitch_organizationasks for it. Both hooks run in React DOM and React Native, and the comment thread and organization switcher recipes show them in the Next.js and Expo examples. -
Add the
catalogblock and SQL module (better-supabase/blocks/catalog): products with a draft, active and archived status, options and variants with per-organization SKUs, prices in bigint minor units per currency and price list with validity windows, a category tree, manual and rule collections, and an opt-in public storefront.catalogSubjects()registers products and variants as subjects. Grantcatalog.readandcatalog.manageto the roles that use it. -
Add
better-supabase/blocks/commerce. It holds money as abigintcount of the currency's minor units, using ISO 4217 List One (pinned asSPEC_PINS.iso4217), with arithmetic, half-to-even rates, allocation, parsing, formatting and JSON. It also defines the versionedPaymentProviderandTaxProviderinterfaces.stripePaymentsimplements the first on Stripe PaymentIntents and webhooks.stripeTaxandfixedRatesimplement the second.better-supabase/testingadds their conformance kits,testPaymentProviderandtestTaxProvider. -
Add the inventory block (
better-supabase/blocks/inventory) and itsinventorySQL module: locations, stock levels per catalog variant and location kept by an append-only movement ledger, reservations that expire (lazily and through a service-onlyexpire_reservationsjob), transfers between locations and purchase orders with partial receiving and backorders. It emitsstock.*,reservation.*,transfer.*andpurchase_order.*events, and the catalog refuses to delete variants with stock history. -
Add the
ordersblock and SQL module (better-supabase/blocks/orders). Carts belong to the signed-in user, anonymous users included, andmergeCartsmoves them to the account the shopper signs in to.checkoutprices the cart from the catalog, quotes tax through aTaxProvider, places the order with a number fromnumber-sequences, reserves inventory and creates the payment through aPaymentProviderwith an idempotency key. Paid orders turn their reservations into sale movements and get an invoice number. Fulfillments, returns and refunds (with a proportional tax reversal) follow, and orders emitorder.*,fulfillment.*andreturn.*subject events. Grantorders.readandorders.manageto the roles that run the shop.sqlTransportnow sends an array of objects as JSON, sojsonbarguments that take a list work over it. -
Add the
promotionsSQL module andbetter-supabase/blocks/promotions. Promotions take a percentage or a fixed amount off, or ship for free, for the whole cart or for products, categories (with their children) or manual collections. They apply automatically or by code, with single codes or generated batches, a minimum subtotal, a start and end, usage and per-customer limits, stacking rules and a priority.ordersprices them intopriceCart, lists the applied promotions, reports a code that doesn't apply as a cart problem, and redeems them at checkout with a row lock; cancelling an order releases its redemptions. Applied promotions inPricedCartandOrdernow carry theirkind, and cart problems carry thepromotionIdandreason.merge_cartsmoves the promotion codes of an anonymous cart to the account's cart. -
Breaking: share-links, signatures, sla, tags, targets, teams, templates, time-tracking, trash, versions, waitlist, webhook-inbox, work-items and workflow-builder take
options.extraColumnson their main table and a Standard Schemafieldsoption on the creator; reads return the columns parsed underfields. share-links, sso, state-machine, tags, teams, undo, usage, waitlist, webhooks, workflow-builder and workflows takehooks(grouped by namespace for workflows and workflow-builder).createWebhookInboxtakes{ transport, ... }instead of a SQL client: it no longer takes the client as its first argument, socreateWebhookInbox(postgres.admin, { source })becomescreateWebhookInbox({ transport: sqlTransport(postgres.admin), source }), andreceive_webhook,claim_webhooksandlist_webhooksreturn jsonb (webhook-inbox module version 7).shareLinks.listreturns typed links. The money and payment helpers move frombetter-supabase/blocks/commercetobetter-supabase/commerce. -
createBlocksreturnssinks: asearchSinkover the search block, so trashed, purged and restored subjects update the index, and ametricsSinkover the metrics block for the events in the metrics block'ssinkoption. Pass them tooutbox.relayRoute({ consumers: { ...app.sinks } }). -
Create, the config and the CLI now offer the same conventions under the same names.
initandapplytake--casing,--scope,--tenant-name,--access,--id-typeand--api. With a preset, a flag changes that field and the CLI writes the new preset code, sopreset infoand Create still read it. Without a preset,initwrites the matching config keys, and it asks for each convention in Create's order and with Create's labels;--yesand CI use the defaults.casingdefaults tosnakeeverywhere, as it does on Create. With--access provider,initwrites the sameauthorizationcomment Create's config does.applytakes--package, and both commands readpackage=from a Create URL. A URL withauthz=prints a note that the authorization library isn't part of the preset.plugins.tenant.columnand the tenant column of a subject withouttenantnow default to<sql.naming.tenant>_id, such asworkspace_id, instead of alwaysorganization_id. Set the column to keep the old name.The config check now rejects what the types reject: a
jsonentry withoutimportortype, a malformed bucket (path,policy,lifecycle) and an unknownsql.workflow.schemas/config-v1.jsonis generated from the same schema, so the editor checks match the CLI, and it dropstriggerPrefixanddisabled.tenantKey, which the config never read. -
The custom-fields client gains
listDefinitions(organizationId, entity), which returns an entity's field definitions in rank order with their rank keys, so a settings page can show and reorder them. It calls the new SQL functionlist_field_definitions(tenant, entity), which needscustom_fields.read. Runbetter-supabase sql syncto install it. -
The
dealsSQL module andbetter-supabase/blocks/dealsadd deals on pipelines. Installing deals binds thedealtype in the pipelines module with a Qualified to Closed won or Closed lost ladder. A deal has an amount in minor units, a company and contacts fromconfig.subjects, a team, line items, a motion, a priority, a forecast call, flags and a next step.update(changes)applies grid edits one by one and returns the refused ones with their hint. The table refuses edits to a locked deal, keeps the open date, counts close-date slips and stampsclosedAtwithdeal.closed.win,loseandreopenmove a deal through its pipeline's stages,forecastreturns won, commit, best case, pipeline, not called and later with attainment and gap, andhealthflags rotting, slipped, missing and overdue next steps.Line items share one shape across blocks:
set_<record>_linesreplaces a record's lines and a trigger keeps its list, discount, subtotal, tax and total. -
Delegated tokens are narrowed inside the access functions. A token with a
client_id, or anactchain that is not a support or impersonation session, passesmember_can,member_can_while_deleting,platform_canandtenant_ids_withonly for the permission keys its scopes map to, through the newbetter_supabase.cap_allows(permission). Map scopes inblocks.access.scopesorauthorization.delegation.scopes(a scope without an entry grants the key with its own name,["*"]grants every key).forContext(context, { permissions })sets abs_permission_capclaim that caps the work the same way, and a provider can map scopes at runtime, per client or from RFC 9396authorization_details, with thedelegation.permissionshook.Breaking: an OAuth client or MCP server whose scopes map to no permission key is now refused where it used to pass with the user's roles. The 0.8 to 0.9 guide lists the mapping to add.
-
session.delegation.scopesanddelegationOf(claims).scopesleave out the OpenID Connect identity scopes, exported asIDENTITY_SCOPESfrombetter-supabase/server(openid,email,profile,phone,address,offline_access). They grant no permission. A token whosescopenames only identity scopes still has a delegation, withscopes: [], so an agent on it stays limited to its scopes. Code that looked foropenidindelegation.scopesshould readclaims.scopeinstead. -
Delivery fails closed on records under an authorization provider. Without
delivery.subscribersordelivery.audience, webhooks, notifications and reminders deliver an event about a registered subject only to users and service principals who may read it, through the newcan_subject_for(user, type, id, action)in thesubjectsmodule andsubjectReaders(transport). Webhooks check each delivery against its stored subject, and a share link never counts.Breaking: realtime
fanOutunder a server with authorization hooks and no subscriber policy sends an event with asubjectto no one and returnsforbiddenwith the hintREALTIME_SUBSCRIBER_POLICY_REQUIRED; passpolicy: subjectReaders(transport). -
doctorreports BS223 (info) for functions in an exposed schema that return a scalarint8ornumeric, or an array of them. PostgREST sends those as JSON numbers, so values past 2^53 lose precision before$rpcsees them; return them astextinstead. -
Doctor warns with BS416 when the
support-sessionsblock runs under the provider access model andauthorization.functions.isApprovernever handles{kind} = 'support-session', in the template or in a function it calls. Such a template answers false, so no admin can approve a support request. BS413, which warns when support sessions run under a provider withoutactorMayWrite, now looks for thesupport-sessionsblock; it checked a block name that doesn't exist and never fired. -
New block
better-supabase/blocks/domains(better-supabase add domains): the hostnames an organization serves your app on. A custom domain is verified by a DNS TXT record thatcreateDomainsAdmin().verify()looks up over DNS-over-HTTPS, and withblocks.domains.options.platformDomainset, one label below your domain is a subdomain verified when added (checked againstreserved-slugswhen that module is installed). Each organization has at most one primary hostname, only one organization can hold a verified hostname, andresolve(host)returns the organization behind a request'sHostheader for the proxy. Theaccessmodule addsdomains.read(admins and members) anddomains.manage(admins); re-runbetter-supabase sql syncto pick up the new default permissions. -
Adds the drive block (
sql add drive,better-supabase/blocks/drive): folders and files on attachments, with grants to users, teams or roles that apply to everything under a folder. The same check runs in the drive functions, the attachment policies and restrictivestorage.objectspolicies. Moves and renames follow a name-conflict policy. With versions, trash and share-links installed, the drive also keeps revisions, a bin, starred and recent items and folder share links.driveTreeshapes nodes for a tree view, anddriveSubject()lets other blocks attach to nodes. Adopt mode runs the drive on an existing tree and grant table. A SQL module can now setbeforeto render ahead of another module without renumbering the generated files, anddrive_sharetakes a team id from the teams table, so an adopted uuid team column accepts it. -
The
employeesSQL module andbetter-supabase/blocks/employeesadd the people an organization employs, with or without an account. An employee has a manager, team, job title, employment type, start and end date, and a status of preboarding, active, on leave or offboarded; the database refuses a manager who reports to the employee.updateapplies batched cell edits,orgChartandreportsOfread the tree (managers read their own reports), andoffboardsets the end date and moves the reports up.fromApplicationmakes one employee from a hired application of the hiring block. Private details and a contract history with salaries in minor units sit behindemployees.view_sensitive, declared todata-lifecyclefor exports and anonymize rules.employeesSubjects()registers employees inconfig.subjects. -
The
engagementsSQL module andbetter-supabase/blocks/engagementslog calls, emails, meetings, notes and tasks on one or more records registered inconfig.subjects, with an owner, a due time, an outcome and an external id that makes a repeat log an update.of(subject)reads a record's engagements,next(subject)its next planned step with an overdue flag, andopen(organizationId)a member's open tasks. An engagement is visible to callers who can read one of its records, and assigning it to someone else notifies them. -
The
entitlementsmodule reads the Stripe customer from thebillingororganizationsmodule through their configured names: a renamedbilling_customerstable, itscustomerandtenantcolumns, or anorganizationstable in another schema or with another id column now resolve correctly instead of falling back tostripe_customer_id,organization_idandbetter_supabase.organizations.entitlementslists both modules inintegrates. -
evaluateFilterQuery(query, record, fields, clock)frombetter-supabase/listtests aFilterQuerytree on one record in memory, with the same operators, case rules, relative dates and null handling asfilterWherecompiles to SQL. It returnsmatchedand the result of every rule and group by node id (nullwhen a comparison met a missing value). A field'scolumnmay be dotted to read a nested value, andFilterRecordFielddescribes fields that aren't table columns. -
actorOf(claims)anddelegationOf(claims)are exported frombetter-supabase/server, with theActorOutcometype, so another library can read anactandscopeclaim the waytoSessiondoes without building anAuthState. -
blocks.data-lifecycle.options.omitPatternleaves columns out of data exports by name.truematchestoken,secret,_hash,password,api_keyandlicense_key, and a string is a Postgres regular expression;data_lifecycle_tables()then appends the matching columns of each listed andautoTablestable to itsomitwhen an export runs. It is off by default, so existing exports don't change. Doctor's new BS341 warns about exported columns that match the built-in pattern and that noomitoromitPatternleaves out. -
exposeprivileges can grant every column but a few:select(*, -token_hash).sql syncturns the list into the columns the table'screate tabledeclares, in order, and fails when no schema file declares the table or the exclusions leave nothing.better-supabase/sqlexportsresolveExposeColumnsfor apps that render the grants module themselves, and the module refuses an unresolved*. Doctor's new warning BS339 reports an excluded column the table no longer has. -
Custom fields gain six types:
email,url,multi_option,user,ratingandcurrency.CUSTOM_FIELD_TYPESandCustomFieldTypeare exported frombetter-supabase/blocks/custom-fields, andsaveDefinitiontakes aCustomFieldType. A form field that names a custom field reads the matching forms type:multi_optionbecomesmulti,ratingbecomesintegerfrom 1 to 5,currencybecomesinteger(minor units) anduserbecomestext.App table formats and custom field types now come from one list.
FIELD_FORMATSfrombetter-supabase/configgives each format its column types, its check and the input a form renders, andscaffold screensreads the input from it.Migration: run
better-supabase sql syncand generate a migration. The custom-fields module replaces the inlinefield_definitions_type_checkconstraint with a namedbs_field_definitions_typecheck that lists the new types. -
Add
better-supabase/flags-sdk, a Flags SDK adapter over the flags block.betterSupabaseAdapter()evaluatesflag()declarations from the flags table with the same rules asflag_enabled(),createIdentify()returns the user, the tenant and custom contexts from verified claims (the same entitiesvercelAdaptertargets), andgetProviderData()feeds Flags Explorer. See Flags SDK.The flags module moves to version 3. Run
better-supabase sql upgradeto add:- Custom contexts, such as a brand: declare them in
blocks.flags.options.contexts, target them with a rule'scontextsor an override withcontextandcontextKey, and pass their values throughflagContext({ contexts })orcontextClaims.flag_evaluation()takes a fourthcontextsargument and reads a missing value from the tenant. descriptionandarchivedon flags. An archived flag serves its default variant;saveandFlagInputaccept both.createFlagsProvider().definitions(), which returns the cached definitions.
better-supabase doctorwarns about flags past theirexpires_atextra column that aren't archived (BS336), andexpiredFlagsQuery()inbetter-supabase/sqlreturns the query it runs. - Custom contexts, such as a brand: declare them in
-
Add the
formsblock (better-supabase/blocks/forms). A form has numbered versions of steps and fields withshowIfconditions, and each version stores a JSON Schema 2020-12 thatpg_jsonschemachecks on every submission. Submissions can be saved as drafts, linked to a record, or turned into one by a handler per form key. Withshare-links, arespondlink opens the form to anyone who holds it, rate limited per caller withrate-limit, andbefore_public_form_submissionreceives a bot-check token.useQuestionnairefrombetter-supabase/blocks/forms/reactdrives a multi-step form from a version, andvalidateAnswerschecks answers in the browser with the same schema. -
The frameworks the adapters support are now optional peer dependencies:
react-router(7.9 to 8),@sveltejs/kit(2 and 3),h3(1 and 2),nuxt(3 and 4),astro(7),@solidjs/start(2),@tanstack/react-start(1),elysia(1),express(5),fastify(5) andkoa(3). Nothing new is installed, but your package manager now warns when a framework is outside the majors the conformance tests cover. The ranges are on the Peers page.The conformance tests found these fixes:
better-supabase/h3andbetter-supabase/solid-startread the Cloudflare bindings fromevent.req.runtime.cloudflare.env, where Nitro 3 puts them. Before,getEnvfound no bindings on Cloudflare with H3 2 or SolidStart 2.- The SvelteKit
handletype-checks as SvelteKit'sHandle(SvelteKit 2 and 3), so it works insidesequence(). - The SvelteKit adapter calls
error(status, message)instead of theerror(status, { message })form SvelteKit 3 deprecated. A customkit.errornow receives the message as a string. - The TanStack Start middleware accepts a
next()that returns its result without a promise. - The Astro image service accepts any
qualitystring. A string other thanlow,mid,highormaxuses the default quality. - The Nuxt module type-checks as a module for Nuxt 3 as well as Nuxt 4.
-
Block hooks now wrap headless controllers, so they run in React DOM and React Native alike. Each block with a
/reactentry exportscreate<Name>Controllerfrom its main entry (createNotificationsController,createCommandSearchControllerand the rest), withsubscribe,getSnapshot,actionsanddispose; the hooks areuseSyncExternalStorewrappers over them.Controllers reach the platform only through ports on the client,
bs.ports: realtime topics (topicPortfrombetter-supabase/realtime), storage, the keyboard, file picking and upload, push tokens and deep links.createClientfrombetter-supabase/clientfills the web ports (webStorage,webKeyboard,webFilePicker,webDeepLinks,storageUpload, andwebPushTokenon request), andnativePorts()frombetter-supabase/client/nativebuilds the React Native ones from the Expo modules you pass tocreateNativeClient(betterSupabase, supabase, { ports }).Breaking changes:
useCommandSearchlistens for Cmd+K through the client's keyboard port instead ofwindow, so React Native has no shortcut.useInboxWidgetkeeps the conversation id in the storage port instead oflocalStorage, and reads it after the first render.groupHitsand its types moved fromblocks/search/react/groups.tstoblocks/search/groups.ts(still exported frombetter-supabase/blocks/search/react). -
The
hiringSQL module andbetter-supabase/blocks/hiringadd an applicant tracking system on pipelines. Installing hiring binds theapplicationtype in the pipelines module with one pipeline per job (Applied, Screening, Interview, Offer, then Hired, Rejected or Withdrawn). Jobs open and close, a candidate is any record inconfig.subjects(a person by default) and applies once per job, and interviewers score the application at its current stage.hire,rejectandwithdrawend an application, andapplication.hiredcarries the candidate for the app to turn into an employee. -
httpSinkaborts a request aftertimeoutMs(10 seconds by default) instead of waiting on an endpoint that never answers.doctorgives up on the splinter download and the Management API advisors after 30 seconds. -
createIdempotency().handlenow renews the key's lock at half its length while the handler runs, so a handler slower thanlockkeeps its key instead of losing it to a retry. The newextend(key, holder, scope)does the same for callers of the lower-level protocol. Rerunbetter-supabase sql syncand generate a migration to addbetter_supabase.extend_idempotent. -
Add the
identitiesSQL module andbetter-supabase/blocks/identities:identityResolvermaps an email address or chat user to an app user or contact, linked only through a one-time code frombeginLinkthat the service redeems withredeemLink, or a confirmedauth.usersaddress.better-supabase/chat-sdkaddsbotJobs, which enqueues a linked author's job with a ticket and an unlinked author's with none,chatActions, which decides buttons throughchat.onActionand refuses unlinked authors, andapprovalLinkandapprovalPrompt, which link to the app's approval page without approving. -
The inbox no longer owns
inbox_teamsandinbox_team_members. It requires theteamsblock and assigns a conversation to ateamsrow. Installing both copies the old rows and drops the old tables.create_inbox_teamandset_inbox_team_membercall the teams functions. Team ids stayuuidwhile the inbox is installed. -
Jobs and workflow runs that an OAuth or MCP client queues keep the client's limits: the envelope records the token's
client_id,scope,authorization_detailsand full RFC 8693actchain, andbs.forContextruns with them instead of the user's full rights. The new SQL helperbetter_supabase.token_scope_allows(scope)in theactormodule checks a delegated token's scope in policies.enqueuefails withforbiddenfor a context with an invalidactchain or malformed delegation claims, andforContextrefuses such a stored context.ServerOptions.claimsForcan no longer setact,client_id,scopeorauthorization_details. A job'sdelaymust be a whole number of seconds, elseenqueuefails withvalidation.Jobs and workflows take an opaque
ticket: theticketenqueue option,startFor(ctx, workflow, args, { ticket }),workflowContext(ctx, { ticket })andstartOnEvent({ ticket }). Runs carry it as thebs.ticketattribute, andforContextresolves it throughForContextOptions.ticketor the provider'stickets.subjecthook, failing withforbiddenwhen nothing resolves it.startOnEvent'sargsnow gets the event's context as a second argument.better-supabase/workflow-sdkexportsapprovalWaiter:wait(token, { expiresAt })pauses a run untilwake(token, payload)or the RFC 3339 deadline. -
New block
better-supabase/blocks/leave(better-supabase add leave): leave types in days or hours, requests that go through theapprovalsmodule, and a balance ledger per member and year. A request books the working days inblocks.leave.options.workingDays(Monday to Friday by default) or a half day, can't overlap another pending or approved request, and can't exceed the available balance unlessallowNegativeis on. The final approval books it as taken leave, and cancelling approved leave gives the days back.createLeave()addsaccrue(idempotent with a key, for a monthly cron),adjustandclosePeriod, which carries each balance up to the type'scarryoverMaxinto the next year and expires the rest. Theaccessmodule addsleave.request(members),leave.read,leave.approveandleave.manage(admins); re-runbetter-supabase sql syncto pick up the new default permissions. -
Add
filterstodefineListQuery: an allow-list of typed fields that a ReUI FiltersFilterQuerytree may name.parsechecks each rule's operator and value against the field type, caps depth and rule count, drops unfinished rules, and takes atimeZonethat relative dates resolve in. The tree compiles to repositorywhereinput, so it runs through PostgREST, the Postgres executor and SQLite.filterFields(labels)returns ReUIFilterFieldobjects, the URL keeps the tree in one base64urlfilterparameter thattoSearchParamsand the nuqs parsers handle, andopenapiandjsonSchemadescribe it. -
Add client controllers and hooks for members, invitations, the audit log, API keys and tags.
useMembers()anduseInvitations()(better-supabase/blocks/organizations/react) list an organization's members and open invitations;setRole()shows a role change at once,remove()removes a member, andinvite()keeps the token for the accept link insent.useAuditLog()(better-supabase/blocks/audit/react) pages through the audit trail withsetFilters()by actor, action or text andloadMore().useApiKeys()(better-supabase/blocks/api-keys/react) lists, creates and revokes keys and shows a new token once.useTagInput()(better-supabase/blocks/tags/react) adds, removes and creates a record's tags. Each has acreate<Name>Controllerin the block's main entry and/vue,/svelteand/solidbindings, and runs in React DOM and React Native. The tags module gainslist_tagsandsubject_tags, whichtags.list()andtags.forSubject()call. The members table, invite dialog, API keys table, audit log table and tag input recipes are now available in the Next.js and Expo examples. -
Adds the
metricsblock (better-supabase/blocks/metrics).defineMetricdeclares a count, sum or average over a table with dimensions, a time zone and a permission. Metrics roll up intometric_pointsper grain through ametrics.rollupjob ormetricsSink, or are read from the table directly.series()andkpi()compare with the previous range, andtoChartDatareturns Recharts rows. Usage events can be a metric's source. -
Add the
better-supabase/blocks/mfaandbetter-supabase/blocks/sessionsentries, with React, Vue, Svelte and Solid bindings.useMfaenrols, verifies and removes TOTP factors, anduseStepUpraises a session toaal2after anINSUFFICIENT_AALrefusal (needsStepUp).useOAuthConsentserves the consent page of the Auth OAuth server, anduseOAuthGrantslists and revokes the clients a user approved. -
Breaking: every amount with a currency in the deals, quotes, invoices, pipelines and employees blocks is a
Moneyvalue ({ amount: bigint, currency }frombetter-supabase/commerce) instead of a barebigint. Build one withmoney(amount, currency). Line inputs, totals, payments, aging buckets, forecasts, board totals and contract salaries all change, and the separatecurrencyinput of a contract is gone becausesalarycarries it. Target goals and progress staybigint.Old New deals.create(org, { amount: 4_800_000n, currency: "EUR" })deals.create(org, { amount: money(4_800_000n, "EUR") }){ description, unitAmount: 9_500n }{ description, unitAmount: money(9_500n, "EUR") }invoices.recordPayment(id, { amount: 137_940n })invoices.recordPayment(id, { amount: money(137_940n, "EUR") })deals.forecast(org, { currency: "EUR", target: 60_000_000n })deals.forecast(org, { currency: "EUR", target: money(60_000_000n, "EUR") })employees.addContract(id, { salary: 5_400_000n, currency: "EUR" })employees.addContract(id, { salary: money(5_400_000n, "EUR") })invoice.totals.total,invoice.balance:bigintMoney; read.amountfor thebigintboard totals: [{ currency, amount: bigint, weighted: bigint }]totals: [{ currency, amount: Money, weighted: Money }]Breaking: an amount in another currency than its record returns an
invalid_requesterror with hintCURRENCY_MISMATCHbefore any database call, and an unknown ISO 4217 code returnsCURRENCY_INVALID. A deal, quote or invoice created without acurrencytakes it from its amounts. The SQL checks the same rule: the line-items setters refuse a line in another currency (LINES_CURRENCY),update_dealsrejects an amount change in another currency (DEAL_CURRENCY_MISMATCH), andrecord_invoice_paymentis now(invoice, amount, currency, paid_at, method, reference)and refuses a payment in another currency (INVOICE_CURRENCY_MISMATCH). The old five-argument function is dropped.Breaking: the block SQL functions return every
int8as text, and the clients read amounts only from an integer string or abigint. Amounts past 2^53 now round-trip exactly, and a missing or malformed amount is an error instead of0n. Code that calls these functions through$rpcorqueryRawgets strings where it got numbers. Rerunbetter-supabase sql syncand generate a migration to install the new functions. -
The notifications module tracks what an email provider reports after a send.
notification_delivery_eventsstores eachdelivered,opened,clicked,bounced,complainedordelayedevent once per provider event id, and deliveries gainprovider_status,provider_status_atandtemplate_key.notifications.recordDeliveryEvent(input)calls the service-onlyrecord_delivery_event, which moves the status forward, suppresses the address on a hard bounce or a complaint, and emitsnotification.<kind>with the notification's subject.notifications.subjectDeliveries({ subject })lists the deliveries of every notification about one record. AtemplateKeyreturned from the email channel'scomposeis stored on the delivery.resendWebhooknow records every Resend delivery status before it writes suppressions, andresendDeliveryEvent(event, id)maps one event without the handler.notification.deliveredandnotification.failednow carrysubjectType,subjectId,organizationIdanddeliveryId, and the five new events are subject events.complete_notification_deliverytakes a seventh argument,template_key, and the six-argument signature is dropped. Runbetter-supabase sql syncto install module version 6;resendWebhookanswers 500 against a database withoutrecord_delivery_event. An adopted module tracks delivery events only whentables.deliveryEventsnames your table. -
sendacceptspermission(with a tenant) and reaches the users who hold that key. A provider supplies them throughauthorization.functions.holdersOf. The roles and catalog models derive holders from memberships. A provider model withoutholdersOfraisesNOTIFICATION_PERMISSION_AUDIENCE_UNAVAILABLEinstead of notifying every member. -
The
notificationsmodule takesoptions.subjectslike the other subject-bound modules. A subject type withcascade: truegets anafter deletetrigger on its table that deletes the subject's notifications, with their recipients and deliveries, and the subscriptions to it. Withoutoptions.subjectsthe module readsconfig.subjects, so a registered type withcascade: truenow cleans up its notifications too. The keys may contain hyphens (time-off-request), becausesubject_typeinnotification_eventstakes any text. -
createNotificationstakesemail: { transport, from, compose?, unsubscribe? }, an email channel over aDeliveryTransport(apiVersion: 1) that sends with the delivery id as the idempotency key, setsAuto-Submitted: auto-generatedon all mail andList-Unsubscribewith one-clickList-Unsubscribe-Poston notification mail only.better-supabase/blocks/notificationsexportsresendTransport(fetch-based,Idempotency-Keyheader),resendWebhook(verifies the Svix signature and records bounces and complaints),mailHeadersandresendSuppressions, andbetter-supabase/testinggetstestDeliveryTransport.The notifications module (version 5) adds
notification_suppressionswith RLS andsuppress_notification_address,unsuppress_notification_addressandlist_notification_suppressions; the block getssuppress,unsuppressandsuppressions, anddeliverskips a suppressed address.createNotifications({ audience })checks recipients before sending and falls back toserver.authorization.delivery.audience.defineTopictakespermission(an instance permission from a topic segment, checked with the provider'spermittedtemplate or the access contract) andsubscribers, and topics getfanOut.Breaking: run
better-supabase sql syncand create a migration for the module upgrade; an adopted module honours suppressions only whentables.suppressionsis mapped.deliver()counts suppressed and audience-denied deliveries inskipped. A hand-writtenTopicobject needsfanOut. -
genreads@notNulland@notNull(a, b)from a function's comment, so a function can say its result is never null next to its SQL instead of infunctions.<name>.notNull. A config entry still wins. Snapshots record the comments that carry the tag (extras.functionComments), and doctor's new info rule BS338 lists thenotNullentries a tag could replace or already matches. -
accessTokenResolver({ jwks, issuer, audience })frombetter-supabase/serververifies RFC 9068 access tokens that another authorization server issued, next toapiKeyResolver. A verified token resolves to a user withsource: "oauth", and itssub,client_idandscopereachctx.sqlandforContextas claims, so the request runs as the user under row level security and ascopelimits it like any OAuth client. The resolver fails closed on a wrong issuer or audience, an expired token, a missing required claim, aservice_rolerole or a sender-constrained token, and can check a revocation list keyed byjtiand grant. JWS verification also accepts RS256 and PS256 keys.The new
oauth-serverblock (better-supabase/blocks/oauth-server) stores what an authorization server needs: an RFC 7591 client registry with hashed secrets and registration tokens, authorization codes bound to an S256 PKCE challenge, RFC 8628 device codes, grants per user and client, and the revocation list. A replayed authorization code revokes its grant. The block issues no tokens; sign them withcreateSigningKeys. Install it withbetter-supabase add oauth-server. The pins areSPEC_PINS.rfc9068,rfc7591,rfc7636,rfc8628andrfc9700. -
A block's SQL and TypeScript halves now read one config.
better-supabase genwritesblocks.generated.tsnext togenerated.ts: each installed block's schema, API schema and the options both halves share (attachments.requireScan,bulk.limit, the realtime topics of notifications, announcements, inbox, reactions and ai-chat,time-tracking.timeZone,waitlist.codeField,webhooks-out.allowHttp), with the module defaults filled in.defineBlocks(blockConfig, blocks, ...appEvents)takes it as its first argument and passes each block its schema (the API schema when there is one) and those options, so the app no longer repeats them.createBlockstakes it asconfig, and its sharedschemaoption is removed.generatedOptions(entry)gives a creator you call yourself the same values, andfillTopic(template, values)fills in a topic template such asnotifications:{userId}.blocks.<name>.optionsis typed from each block manifest's options schema: an unknown block, an unknown option or a value of the wrong kind is a type error, and the SQL renderer refuses it too. Manifests describe their options withblockOptions({ key: option.string(), ... })in place ofoptionKeys([...]), which is removed, andschemas/config-v1.jsonis generated from the same schemas.BlocksConfigis the typed input; the resolved config and the SQL renderer useAnyBlocksConfig. Preset wiring (init --preset) and theblocksregistry item build ondefineBlocks(blockConfig, ...), andaddedits adefineBlockscall as well as acreateBlocksone. -
Every action a module checks is an operation named
<module>.<action>, andbetter_supabase.operation_permission(op)returns its permission key in SQL, afterblocks.<module>.permissionsrenames and with the provider'soperationsover them. MCP tools take an optionaloperation, agents taketoolOperations, and workflow-builder step library entries takeoperation, each naming the entry to check in place ofmcp.tool.<name>,ai.tool.<name>orworkflow.run. -
@openfeature/server-sdk,@supabase-labs/middleware-openfeature,@vercel/connect,@ai-sdk/anthropic,@powersync/commonandflagsare now optional peer dependencies. better-supabase still imports none of them, so nothing new is installed, but your package manager now warns when one of them is outside the major versions the conformance tests cover. The ranges are on the Peers page. -
otel()records aBATCHspan for the round trip when an executor runs the reads of onedb.$manycall together, as the direct Postgres executor does. The span carriesdb.operation.batch.sizeand is marked failed when any read fails. Plugins that wrapexecutor.batchnow see these batches too. -
The
partiesSQL module andbetter-supabase/blocks/partieskeep the companies and people an organization works with: lifecycle stages, owners, who works where with a role and one primary contact, dedupe by domain and email,mergeCompaniesandmergePeople, and keyset-pagedlistCompaniesandlistPeople.partiesSubjects()registers both tables inconfig.subjectsso comments, tags, files and pipelines attach to them, and the owner watches the record when notifications is installed. -
With the inbox module installed, the parties module links inbox contacts to people.
personForInboxContact(contactId)returns the linked person, links the person with the contact's email when there is none, and withcreate: truesaves an unknown contact as a new lead.linkInboxContactandunlinkInboxContactchange the link by hand. -
The
pipelinesSQL module andbetter-supabase/blocks/pipelinesput any record inconfig.subjectson pipelines an organization edits. Bind a type inblocks.pipelines.options.subjectswith its categories, each mapped toopen,successorfailure, and the module keeps several pipelines per type (or one per scope, such as a job), checks every stage change, stamps the time a record entered its stage, writes a stage history and recordspipeline.stage_changedwith the record as its subject. A binding can set a status column from the stage category through the state machine, and the owner watches the record when notifications is installed.createPipelinesmanages pipelines, stages and transitions, and reads the board (counts and per-currency totals weighted by probability), stats (entries, time in stage, win rate) and health (days in stage, rotting). -
Lists and resources page by cursor by default.
defineListQueryand the default list ofdefineResourceanddefineApiread the same number of rows however deep the page is, and rows inserted between requests don't shift it. Setpagination: "offset"to keep page numbers and totals; the 0.9 codemod adds it to calls that set no pagination in files that read page numbers, and lists the other calls for review. A table or view without a primary key stays on offset.0.8 (offset default) 0.9 (cursor default) ?page=3&size=50?after=<nextCursor>&size=50page.page.number,.total,.pagespage.hasMore,page.nextCursorListPage<R, F, C>is anOffsetPageListPage<R, F, C>is aCursorPagelist.args(query)returnspage,countlist.args(query)returnsafterOpenAPI and MCP list pageOpenAPI and MCP list afterThe World's
world.analyticslists return(created_at, id)keyset cursors instead of offsets. Pass back the cursor the previous page returned; an offset number from 0.8 fails with "not an analytics cursor".Time tracking rates are
Money(ADR 0037). An entry'srateis an hourly amount in minor units with its currency, and the timesheet totals returnamounts, oneMoneyper currency, instead ofamount. The client returnsCURRENCY_INVALIDbefore any database call for an unknown code, andtime_entry.*events carryrateas text withrateCurrency.0.8 0.9 time.start(org, { rate: 120 })time.start(org, { rate: money(12_000n, "EUR") })entry.rateis120entry.rateismoney(12_000n, "EUR")sheet.totals.amountis480sheet.totals.amountsis[money(48_000n, "EUR")]The module upgrade turns
rateinto abigintwithround(rate * 100), addsrate_currency, and drops thenumericsignatures ofstart_timerandlog_time. Setrate_currencyon existing rows after the upgrade; the 0.8 to 0.9 guide has the statements.Tagging a record needs
tags.applyortags.manage. In 0.8 any signed-in user could tag or untag a record. Therole_permissionsdefaults givetags.applyto members; apps with their own roles grant it to the roles that tag.0.8 0.9 tag()anduntag()check the subject onlythey also need tags.applyortags.manageon the tenantAudit, webhooks and notifications write a batch in one call.
audit.recordMany(events),webhooks.publishMany(events)andnotifications.sendMany(items)take up to 1000 items each, run the single-item checks per item, and return oneResultper item in order, so a bad item never drops the others. The audit, webhook and notification sinks use them, one call per batch.auditSinktakes the batch function:0.8 0.9 auditSink(record, options)auditSink(recordMany, options)record: (event) => AsyncResult<string>recordMany: (events) => AsyncResult<readonly Result<string>[]>The outbox, usage, notifications and webhooks modules take
partitioned: true, as the audit module does. It partitions a new events,usage_history,notification_delivery_eventsor deliveries table by month on its time column, with a primary key of(id, created_at), and retention drops whole months. It applies to new tables only; the default stays unpartitioned (ADR 0038).Direct Postgres (
better-supabase/postgres) honorscount: "planned"andcount: "estimated"the way PostgREST does:plannedreads the row estimate fromexplain, andestimatedcounts exactly up toestimatedCountThreshold(default 1000) and uses the estimate above it. Counts are cast tobigint.0.8 0.9 plannedandestimatedran an exact countplannedreadsexplain;estimatedswitches at 1000 rowsidleInTransactionTimeoutunsetdefaults to 15000 ms; 0turns it offan idle connection error crashed the process it arrives as an errorevent, or the logger without handlerscreatePostgrestakeseventsandloggerfor those errors. The World's pool has limits now:maxConnections(10),connectionTimeout(30 s),idleTimeout(10 s),statementTimeout(30 s) andidleInTransactionTimeout(15 s), also read fromWORKFLOW_POSTGRES_MAX_CONNECTIONS,WORKFLOW_POSTGRES_CONNECTION_TIMEOUT_MS,WORKFLOW_POSTGRES_IDLE_TIMEOUT_MS,WORKFLOW_POSTGRES_STATEMENT_TIMEOUT_MSandWORKFLOW_POSTGRES_IDLE_IN_TRANSACTION_TIMEOUT_MS.Realtime trigger functions include the schema, so tables with the same name in two schemas no longer replace each other's function. The trigger keeps its name. Drop the old functions in the migration; grants on them don't carry over.
0.8 0.9 bs_broadcast_<topic>_<table>()bs_broadcast_<topic>_<schema>_<table>()The key payload of
broadcast_topic()reads only the primary key and the placeholder columns and looks the key up once per statement.Doctor has five new rules:
Code Severity Finds BS117 warning a policy without a torole, so it applies topublicBS224 warning anonorauthenticatedwithoutstatement_timeoutoridle_in_transaction_session_timeoutBS225 info pg_stat_statementsnot installedBS226 warning postgres.js without prepare: false, or Prisma withoutpgbouncer=true, next to a:6543URLBS227 info pagination: "offset"in a list or resource config, orcount: "exact"on a listBS216 accepts a
where col is not nullpartial index as the foreign key's index. BS335 now also checks the outbox, usage history, webhook deliveries and notification delivery events tables, not only the audit log.calendar_attendees.roleis checked against the RFC 5545 roles,notification_events.priorityagainst the configured priorities, andreminders.offset_minutesis limited to a year either way. Each check is addednot validand then validated, so existing bad rows leave it unvalidated with a warning instead of failing the migration.comments.listtakescursorIdwithcursor, so comments with the same timestamp no longer repeat or skip between pages. The audit list ignoresoffsetwhen it gets a cursor.Line totals on quotes, invoices and deals are recounted once per parent per statement instead of once per line. Trigger functions and
broadcast_changes()are no longer executable byanonorauthenticated, and the storefront helpers are revoked frompublicand granted to the roles that call them.bs_reserved_slugs_readnames its roles, andscope.platform()checks the platform permission once per statement. The reminders, calendar, bookings, imports, bulk, share-links, tags, memory and workflow-builder modules index the columns their policies and lookups filter on. Search writes embeddings in one statement, the pgmq backend archives a batch in one call, andmetrics_rolluplocks per tenant. -
createPostgres()session options takestatementTimeout, which overrides the role's timeout forasUser,executorForandtransaction.transaction()without claims now appliessettings,readOnlyandstatementTimeouttoo, and anadminquery with no timeout to set runs withoutbeginandcommit. -
Breaking: the CLI uses
@supabase/postgrest-typegen0.6.0, and the optional peer now accepts>=0.6.0 <0.7instead of>=0.4.0 <0.5. Upgrade it withpnpm add -D @supabase/postgrest-typegen@0.6.0.database.types.tsagain matchessupabase gen typesfrom Supabase CLI 2.121, which writes the sameComputedFieldskeys. View columns are typed with the nullability postgrest-typegen 0.6 reads from the view definition, so runbetter-supabase gento regenerate.The
GeneratorMetadatatype gains the optionalrpcFunctionscollection that postgrest-typegen 0.6 derives fromfunctions, and theRpcFunctiontypes it uses are exported next to it. Snapshots andgen --metadataleave it out, and the generator resolves it again from the ordered, stable functions of the generated schemas only. -
watchanduseWatchfrombetter-supabase/powersynctakerefresh: { everyMs, onReconnect }, so a read that runs on the executor's serverfallbackreruns without waiting for a local change: on an interval (skipped while PowerSync reports it is offline) and when PowerSync connects again.PowerSyncDatabaseLikegains the optionalcurrentStatusandregisterListenermembers thatrefreshreads. -
The CLI starts and changes projects from presets.
init --preset <name|code|url>writes the config withpreset, the module files of every block it installs and alib/blocks.tsthat wires their clients, and prints the registry glue for the framework.apply --presetsetspresetin an existing config (or, with--only blocks, lists its blocks; with--only conventions, takes the conventions alone), shows the diff and writes the modules.preset decodeandpreset infoprint what a code holds and how the config differs from its preset, andblocks list,blocks viewandblocks searchread the block catalog.add <block...>now adds blocks: it lists them inblocks, writes their modules and what they require, wires their clients intolib/blocks.tsand names their registry glue. The framework glue moves toadd --framework <integration,...>;addwithout arguments still sets up the integrations the config lists. In a terminal,initfirst asks for a preset.better-supabase/presetaddspresetApplyCommand,presetGlueandglueCommand, andpresetInstallCommandnow returnsinit --preset <code>. -
better-supabase/presetdescribes an app as a preset: a block selection plus its conventions (framework, platforms, casing, id type, scope, tenant name, access model, API schema and integrations).encodePresetanddecodePresetturn one into a short code, andresolvePresetreturns every block to install with the reason it is there, the soft integrations between them and the conflicts. It reads a generated catalog of the blocks, so it runs in the browser. The named presets areminimal,saas,crm,projects,commerce,scheduling,aiandeverything.defineConfig({ preset, blocks })takes a named preset, a code or a/create?preset=URL and expands it intoblocksand its conventions first; the keys you set win. The docs Recipes section is now Presets, at/docs/presets. -
The
promotionsmodule callsbefore_promotion_activate(promotion uuid)when you define it, after every write that leaves a promotion active:set_promotion_active(id, true)and eachsave_promotionof an active promotion. Raising refuses the change, which holds a promotion for approval. The commerce recipe uses it to hold discounts above 30 percent, and now also indexes products for search and saves order grid views. -
The
quotesandinvoicesSQL modules and their blocks add the sales documents after a deal. A quote has lines and totals the database keeps and a revision chain. It is sent as a link the customer opens without an account and answers with accept, reject or changes requested, and it expires after its valid date.quotes.fromDealmakes one draft per deal. An invoice gets a gapless number when it is issued and collects payments (a payment reference is recorded once, and a refund larger than the amount paid fails withINVOICE_REFUND_TOO_LARGE). Credit notes reduce its balance, and it can be voided, written off and aged per currency.invoices.fromQuotemakes deposit invoices and one final invoice that subtracts them. With the relations module installed, both link to their origin withcreated_from. -
Add fractional rank keys.
better-supabase/blocks/rankexportsrankBetween,rankKeys,isRankKeyandcreateRank, and the newrankSQL module addsrank_between,move()and arank.rebalancejob for subjects with arankentry inconfig.subjects.move()runs as the caller and can change the row's group, so a state-machine trigger on that column checks the change.Tags and custom fields now order definitions by a
rankkey instead of an integerposition. Both modules move to version 2: the upgrade backfills keys in the old order and dropsposition.tags.reorderandcustomFields.reorderDefinitiontake the neighbours' keys. Adopt configs that mappedpositionmaprankinstead. An adopted table without a rank column maps it tonull(columns: { tags: { rank: null } }, anddefinitionsandoptionsfor custom fields);sql syncnames the column until you do.A state-machine config without
initialnow namesinitialin its error instead ofcolumn. -
Add
rateLimit()middleware to the Hono and oRPC adapters, built oncreateRateLimit. Responses carry theRateLimitandRateLimit-Policyfields of draft-ietf-httpapi-ratelimit-headers-11, and a refused request gets a 429 withRetry-After.better-supabase/serverexportsrateLimitHeader()andrateLimitPolicyHeader(). -
A read-only support or impersonation session can no longer write. Every security definer function granted to
authenticatedoranonthat writes checksbetter_supabase.actor_may_write(), orauthorization.functions.actorMayWritewhen a provider sets it. The same check is added to generated write policies. Writes that succeeded during those sessions in 0.8.0 now fail withACTOR_READ_ONLY(42501).read_only: false, an agent actor and a signed-in user withoutactstill write. Reads are unchanged.start_support_session,end_support_sessionandexpire_support_sessionsstay callable so the session can be left. -
Topic triggers stop sending whole rows. This changes behaviour: the default message is now
{ operation, schema, table, id, values }, the primary key and the topic values, so subscribers refetch the row through the Data API and their column grants apply. Before, every subscriber of the topic received every column.topic.trigger(table, options)is the one trigger API. PassbetterSupabasefor typed table keys and parent-row lookups,payloadfor a custom object or"row"to keep whole rows on purpose, andtopicsto send the same change to more topics.triggerSql(betterSupabase, table, options)is deprecated and callstrigger(table, { ...options, betterSupabase }). Its default payload changes too.rowKeysreads the new message on the client.rowChangereads thepayload: "row"shape.realtime.triggersentries takepayload: "keys" | "row", and the config loader now acceptsrealtime.triggersat all.better_supabase.broadcast_topic()sends the key payload, takes a fourth'row'argument, accepts{name=column}placeholders, and refuses to run as abeforetrigger. A topic value with characters topics don't allow raises a warning and skips that send instead of failing the write; generated trigger functions do the same per topic.- Doctor BS337 warns about trigger functions that broadcast whole rows without the
payload: "row"marker, such as 0.8triggerSqlfunctions. Snapshots record trigger arguments, and the source and comment of broadcasting trigger functions.
Run
better-supabase sql syncand create a migration to updatebroadcast_topic(). See Realtime triggers. -
Glue for your app now installs with the shadcn CLI from the
@better-supabaseregistry athttps://bettersupabase.com/r/{name}.json: block wiring (blocks,postgres,outbox,onboarding-checklist), Next.js server actions for notifications, theuse-current-organizationandpush-nativehooks, route handlers for the outbox relay (Next.js and Hono), Stripe webhooks and the jobs drain, the Expo config, and thesaas-nextandsaas-expobundles. The registry holds no UI components, config or SQL.The UI comes from recipes instead: the notification bell, notification list, command search and onboarding checklist show the shadcn components to add and the web and React Native code side by side, with the same hook call. They are on bettersupabase.com/recipes, in the docs at
/docs/registry/ui-recipesand in thebetter-supabaseskill (references/ui-recipes.md).SPEC_PINS.shadcnRegistrypins the shadcn registry schema the items follow. -
The
relationsmodule declares a fourth default kind,created_from(inverseconverted_to, one origin per record, no cycles), for records that turn into other records.converted_into(tenant, origin_type, origin_id, into_type)and the client'sconvertedIntoreturn the record an origin was already converted into, so a conversion runs once, andlineage(organizationId, subject)returns a record's origins and conversions.sql syncrewrites the relations module. -
Add the
relationsblock (better-supabase/blocks/relations). It links two subjects with a declared kind (blocks,parentandrelatesby default), stores inverse names from one end, refuses cycles for acyclic kinds under an advisory lock, replaces the target of one-target kinds, and reads ancestors, descendants and rollups.linkandunlinkreturn an undo token, andtoGanttTasksandtoTreeItemsshape links for a Gantt chart or a tree. -
Retention policies and legal holds in
data-lifecycle:createRetentionsets how long each kind of record is kept (audit,outbox,webhook_deliveries,webhooks,inbound_events,job_archive,usage,notifications,workflow_runs), for every tenant, a plan's tenants or one tenant, and places and releases legal holds that every module purge andpurge_organization(ORGANIZATION_LEGAL_HOLD) respect, including chats and trash. Holds emitlegal_hold.placedandlegal_hold.released. Withoutdata-lifecycle, each purge keeps itsolder_than.The audit module (version 8) gains
options.chain, which hash-chains each tenant's entries, andcreateAuditChaininbetter-supabase/blocks/auditverifies the chain and records signed checkpoints of its heads with anysignJwtsigner. Without ato, verification runs up to the latest checkpoint, so deleting the newest entries reports a gap.options.partitionedcreates a new managed log partitioned by month,better_supabase.maintain_partitions()adds the months ahead, andpurge_audit_logdrops expired months when no hold oraudit_retentionhook applies.better-supabase doctorreports a log that asks for partitions but isn't partitioned (BS335). -
New block
better-supabase/blocks/reviews(better-supabase add reviews): ratings and reviews of catalog products and other subjects. Any signed-in user can review an active product on a public storefront, a product in a catalog they read, or a registered subject in an organization they belong to, once per subject; a new review replaces their earlier one.verifiedis true when theordersmodule shows a paid order for the product, andblocks.reviews.options.requirePurchasemakes that a requirement. Reviews wait for a moderator undermoderation: "pre"(the default) or publish at once under"post".createReviews().summary()returns each product's count, average and histogram, which anonymous visitors can read for a public storefront. Theaccessmodule addsreviews.manage(admins); re-runbetter-supabase sql syncto pick up the new default permissions. -
Under the provider access model,
member_organization_ids(),has_organization_role()andorganization_member_role()read membership from the provider'smemberIdsandmemberIdsFortemplates, so a user the provider no longer lists stops counting as a member. Doctor rule BS334 (info) reports app policies and functions that still call them and points attenant_ids_withormember_can. -
db.$rpcnow casts result columns that have a codec totext, as repository reads do, over both PostgREST and the Postgres executor. Anint8above 2^53 in areturns tableorreturns setofresult now reaches itsbigintcodec intact, and anumerickeeps its digits.{ raw: true }calls send no column list. Executors receive the list asRpcContext.select; an executor that ignores it returns the full row, as before. -
New block
better-supabase/blocks/rules(better-supabase add rules): saved, versioned condition trees over the fields you register per subject type.defineRuleFields()declares each field's type, column type and operators, andcreateRulesAdmin().syncFields()stores them for the database. A rule has a trigger, aFilterQuerycondition, ordered actions, a rank andstopProcessing.matching()evaluates every enabled rule for a subject in Postgres (better_supabase.rule_matches), andtest()evaluates one rule locally withevaluateFilterQuery; both give the same answer for every operator.createRuleDispatcher()runs the matched actions through your handlers, andapprovalsAction()opens an approval request from a rule. Every save keeps a version, every evaluation can be logged, andrule.saved,rule.enabled,rule.disabled,rule.removedandrule.matchedgo to the outbox. Theaccessmodule addsrules.read(members),rules.edit,rules.publishandrules.admin(admins); re-runbetter-supabase sql syncto pick up the new default permissions. -
The rules block has an editor controller.
useRuleBuilderfrombetter-supabase/blocks/rules/react(and/vue,/svelte,/solid) loads a subject type's fields and a rule, edits its condition tree, reports the problemscheckRuleConditionsfinds and whether anything changed, and saves the rule with its version. Nodes named inlockedcan't be changed, moved or removed.createRuleBuilderControlleris the same state without a framework, and the tree helpers it uses (findNode,insertNode,moveNode,removeNode,setRuleField,setRuleOperatorand others) are exported frombetter-supabase/blocks/rules. -
The Rule builder UI recipe renders a rule editor with shadcn components: field, operator and value rows, nested And and Or groups, drag handles and a locked first condition. The
use-rule-editorregistry item installsuseRuleEditor, which reads the organization from the session and the rules schema fromblocks.generated.ts, and the preset catalog lists it. -
Add eight blocks, each with managed, adopt and custom modes:
number-sequences(gapless numbers assigned in the document's transaction),teams,tags,state-machine,custom-fields,share-links,reminders(RFC 5545 expansion) andimports(RFC 4180 CSV). Subject link and history tables can be adopted per subject. -
diffAppTablesanddiffDesignsfrombetter-supabase/presetlist what changes between two sets of app tables. Added tables and optional columns are safe. A dropped or renamed table or column, a type change (of a column or of the table's id) and a column made required without a default are breaking, and each comes with its expand-and-contract steps.apply --presetwith a design now lists the breaking changes to tables the config already has, writes nothing and exits 1. Pass--allow-breakingto write them anyway;--dry-runshows them without it.Doctor gains BS228 (warning): a column of an app table whose type or nullability in the database differs from
appTables.Create shows the changes since the page loaded its link on a Changes tab in Get code.
Migration: a script that runs
apply --presetwith a design that retypes, drops or renames app table columns now needs--allow-breaking. -
blocks.tenant.options.sameTenanttakes{ auto: true, entries? }.sql syncthen derives an entry for every single-column foreign key between two tables with the tenant column, fromreferences,foreign keyconstraints andalter table ... add constraintin the schema files. A listed entry for the same column wins, and a derived entry renders the same trigger as the listed one. The list form is unchanged. Doctor's new BS340 lists tenant foreign keys without abs_same_tenant_<column>trigger.better-supabase/sqlexportssameTenantLayout,sameTenantColumnandsameTenantTrigger. -
Saved views keep the whole view state and per-user preferences.
useSavedViewstakesgetStateandonApplyState, sosaveCurrentstores the columns, grouping, density and layout with the URL's query,applyrestores them, andactiveandisDirtycompare them; thesavecallback now also receivesstate, the valuesavedViews.save()takes. Thesaved-viewsSQL module adds asaved_view_preferencestable andset_view_preference, so a member can make a shared view their own default, hide it or pin it without the right to change it, andlist_viewsreturns the caller'spreferencewith each view.defaultViewopens the caller's preferred view first and skips hidden views.duplicate_viewandsavedViews.duplicate()copy a view the caller sees into a new view, with the same checks as saving one. The client addssetPreference()andduplicate(), and the hook addsduplicateandsetPreference. Runbetter-supabase sql syncto install module version 2. -
Add the
saved-viewsblock. The SQL module stores named list views per user, team or organization, with one default per slot and rank order; sharing a view with a team or the organization needsviews.share, and team views use theteamsmodule.better-supabase/blocks/saved-viewsexportscreateSavedViews, which checks a view's query against itsdefineListQuerydefinition before saving, plussavedViewStateSchema,defaultViewand helpers that convert between nuqs URL state and a stored query.better-supabase/blocks/saved-views/reactexportsuseSavedViews, which opens the default view and saves the URL's query. The default roles gainviews.readfor members andviews.*for admins. -
better-supabase scaffold screens <table>writes Next.js pages for an app table: a list, a create form with an input per column (from its type,format,options,minandmax, and a select of rows for a reference to another app table) and a detail page. The pages read and write through the generated repository withbs, so RLS checks every request, and each file is written once and then kept as yours.--base-pathsets the route,/<table>by default. The command refuses a table outsideappTables, a table withscope: "none"and a required column the form has no input for.The UI recipes gain an App tables group:
record-grid,record-form,record-page,record-board,record-calendar,record-timelineandrecord-gantt, built on projects and tasks in the Next.js example. Create lists thescaffold screenscommand for each app table in Get code, and its AI instructions link the record recipes once the design has an app table.Migration: none.
-
scimHandlertakes astore: a versionedScimStorewithlist,get,saveanddeletefor users and groups, which may apply the filter and paging itself.sqlScimStore(transport)is the default, andtransportstill works. The store gets the raw resource, extension schemas included.blocks.sso.options.syncLogadds ascim_sync_logtable; passsqlScimSyncLogas the handler'slogto record each write. -
Blocks run per tenant, per user or in one shared space.
sql.scopesets the scope of every block andblocks.<name>.scopethe scope of one. Outsidetenantscope a block needs neither thetenantmodule nor the access contract, its scope column is nullable (the user's id by default inuserscope), and its functions set the scope id themselves.tagsandcommentsrun in every scope, the blocks without tenant data (such asnotifications) run anywhere, and blocks that need tenants declarescopes: ["tenant"], sosql addandresolvePresetrefuse them in another scope.sql.naming.tenantrenames the tenant concept in the tables, columns and functions the blocks write:workspacegivesworkspaces,workspace_id,create_workspaceandmember_workspace_ids.blocks.<name>.functionsrenames single functions. A tenant name that would collide with a block's own names is refused.genwrites the names into each block'snaminginblocks.generated.ts, anddefineBlockswraps the block's transport with the newblockNames()middleware, so the block clients call the renamed functions. The preset model'stenantNamefield takesworkspaceandteam, and presets writesql.scopeandsql.naming.The SQL modules check access only through
ctx.scope(can,ids,check,canUser,platform,members), andcanInandtenantInare removed from the module helpers.tags.update_tagno longer fails with an ambiguousnamecolumn. -
Adds the
searchblock (better-supabase/blocks/search). Triggers generated from eachsearchentry inconfig.subjectskeep asearch_documentsindex, andsearch(q)runs as the caller with websearch, prefix and trigram matching, filtered bycan_subject, and ranked hybrid when the index keeps embeddings. Recents and favorites come from the share-links user state, trashed rows drop out,searchSinkhandles trash events, anduseCommandSearch(better-supabase/blocks/search/react) drives a Cmd+K dialog. -
Add the
service-principalsblock (better-supabase/blocks/service-principalsand theservice-principalsSQL module): organization members that are not people, each anauth.usersrow that cannot sign in and holds its role through a membership.create,setRole,disable,defaultForandlistmanage them; a member who asks for the change needsservice_principals.manageand may only assign a role they could assign. A workflow-builder version the organization owns runs as its default principal, capped to the permissions the version stored, and a service webhook endpoint gets an event only when the default principal may read it. -
Users can now manage their own sessions and reminders. The
sessionsmodule addslist_my_sessions()andend_my_session(id), which list the caller's unexpired sessions (with the current one marked) and end one of them. Theremindersmodule addslist_my_remindersanddelete_reminder, and the reminders client addslist(organizationId, subjectType, subjectId)andremove(id). Runbetter-supabase sql syncand generate a migration to install the new functions. -
create_share_linktakes aversion_idthat pins the link to a version of its subject and must belong to it, andshareLinks.create(..., { versionId })passes it.shareLinks.resolve(token)is typed and returnsversionId. Theversionsmodule addsget_shared_version, granted to anon, and the client gainsversions.getShared(token), which reads a pinned version through its link. -
Share links expire.
shareLinks.create(..., { expiresAt })takes aTemporal.Instant(SHARE_EXPIRY_INVALIDwhen it is not in the future), andresolvereturns the link'sorganizationIdandexpiresAt. Every module that reads through a link (calendar feeds, booking pages, public forms, drive links, shared AI chats) now checks expiry the same way; shared AI chats used to ignore it.create_share_linktakesexpires_atas a sixth argument and drops the five-argument signature.revoke_share_linklets only the link's creator or a member withshare_links.createrevoke a link, and returnsSHARE_NOT_FOUNDto anyone else.list_share_linksreturns the caller's own links and those in organizations where they holdshare_links.read.record_viewrefuses a caller who is not a member of the organization (SHARE_FORBIDDEN), and no longer fails with an ambiguoussubject_typecolumn.authorization.functions.isApprovertakes an optional{requester}placeholder: the uuid of the user who asked (the approval'srequested_by, the support admin, the chat's owner), so a provider that resolves out-of-office covers can refuse the requester's own delegator. Under theprovidermodel,delegate_approvalchecks the delegate's membership through the provider'smemberIdsFor. -
New
shared-signalsblock (better-supabase sql add shared-signals,better-supabase/blocks/shared-signals): an OpenID Shared Signals Framework 1.0 transmitter and receiver, with every CAEP 1.0 and RISC 1.0 event type.createSsfTransmitterserves the well-known metadata, stream management, status, verification and RFC 8936 poll routes, and itsauthorizeoption names the receiver behind each request.emitmints one Security Event Token (RFC 8417) per stream that delivers the event, signed by anysignJwtsigner such as asigning-keyssigner. Withwebhooks-outinstalled, a push stream (RFC 8935) gets an endpoint with the newsetformat, so SETs go through the outbox with its retries and dead letters. Poll streams queue SETs until they are acknowledged, and a paused stream holds its SETs until it is enabled again.createSsfReceiververifies SETs against the transmitter's JWKS, drops replays through the service-onlyssf_receivedtable, runs a handler per event type, and serves the push endpoint or polls. Stream changes are recorded asssf_stream.*events. The pins areSPEC_PINS.rfc8417,rfc8935,rfc8936,ssf,caepandrisc. -
Add the
signaturesSQL module andcreateSignaturesinbetter-supabase/blocks/forms: simple electronic signatures on a frozen version of a record, signed by click, typed name or drawn image, in parallel or in order. Each signature stores a hash over the version's content, sogetreports whether the signed content or a signature changed and whether the record has a newer version. With the approvals module, a signer's signature can approve the step of a linked approval request. -
New
signing-keysblock (better-supabase sql add signing-keys,better-supabase/blocks/signing-keys): Ed25519 and ES256 keys per owner, with the private key in Supabase Vault and the public JWK in a service-onlysigning_keystable.createandrotatekeep one active key per owner and retire the previous one. A retired key stays injwks(owner)until the lastexpthatsignJwtnoted plusjwksGrace(5 minutes).jwksResponseserves the set asapplication/jwk-set+json, andpurge()deletes keys no token can still need.signer(owner)signs raw bytes or compact JWTs in TypeScript with WebCrypto, andverifyCompactchecks them against a JWK Set. Ed25519 keys sign asEdDSAby default, or asEd25519(RFC 9864, pinned asSPEC_PINS.rfc9864).Outgoing webhooks can sign with Ed25519 (Standard Webhooks
v1a).webhooks-out4 addssigning(v1orv1a),formatandcredential_refcolumns towebhook_endpoints. Av1aendpoint is signed by the newasymmetricSigneroption, which takesstandardWebhooksAsymmetric({ signer }). It needs no secret and is dead-lettered when no signer is set.verifyWebhookaccepts awhpk_public key, whichwebhookPublicKey(jwk)builds, in place of awhsec_secret. -
The
slaandtargetsSQL modules and their blocks add service levels and goals. A service-level policy per record type and priority sets first response, next response and resolution minutes, optionally in business hours with a time zone. Binding a record type's status and priority columns starts, pauses, resumes and resolves its clocks,record(subject, "responded")meets a response clock, andcheck()recordssla.warnedandsla.breachedand notifies the record's watchers. A target is a goal per period for a member, a team or the organization. Its progress is computed for won deal amounts and counts, completed work items and paid invoices, or read from a value the app keeps. -
functionRoute(name, fn, options?)frombetter-supabase/specdocuments adefineFunctionEdge Function asPOST /functions/v1/<name>, with its input as the request body and its output as the 200 response.defineFunctionnow keeps itsinput,outputand a new optionalsummaryon the handler it returns, andTypedFunctionrequires them, sofunctionRouteaccepts onlydefineFunctionhandlers. -
better-supabase sql addlists the new modules inblocksof the config file, asname: {}in an object or a name in a list, and editsbetter-supabase.config.jsontoo. Whenblocksisn't a literal it can follow, it leaves the file alone and prints the entries to add.--dry-runsays what it would add. -
sql.apiandsql.schemaset the Data API schema and the module schema for every module that leaves its own unset, so a config no longer repeatsapi: "api"per module. A module'sapi: falsekeeps it out of the API schema whensql.apiis set. -
The SQL modules support three workflows through the new
sql.workflowconfig key:pg-delta(Declarative Schemas 2.0, the default),migra(declarative schemas 1.0 withsupabase db diff) andmigrations. When the key is unset, the CLI readssupabase/config.tomland keeps a project that already uses migra on migra. Undermigrations,sql add,sql syncandsql upgradewrite the modules into one<stamp>_better_supabase_modules.sqlmigration instead ofsupabase/schemas,genwrites the read sets into a migration, and doctor compares against the newest module migration.better-supabase init --workflow <name>picks the workflow, andsql addandsql syncturn pg-delta on inconfig.tomlunder the pg-delta workflow. Doctor BS316 stays silent when the config choosesmigraormigrations, and the BS404 grant hint names a new migration undermigrations. -
A
state-machinemachine can keep a lifecycle row per record withlifecycle: true:pause(subjectType, id, { until, reason }),resume()andsetFlag(subjectType, id, flag, enabled)oncreateStateMachine(), a pinnedversionand a list of allowedflags. While a pause holds, the trigger refuses transitions withSTATE_PAUSED; a pause with an end clears on the next transition after it. The module recordsstatus.paused,status.resumedandstatus.flaggednext tostatus.changed.The block reads as the caller:
state()returns the status with itsstepandprogressthrough the machine's neworder, and the lifecycle;history()pages status changes newest first;stages()returns the stages timeline.status_history,status_stagesand the newsubject_lifecyclestable have select policies that show a row when the caller can see its record. A machine withouttabletakes its table, id type and tenant fromconfig.subjects, andidTypecompares ids in their own type. -
Breaking:
better_supabase.transition()in thestate-machinemodule now runs as the caller instead of as a security definer function. Before, any signed-in user could change the status of any record of a machine, in any tenant. Now the subject table's row level security decides: a caller who can't update the record getsSTATE_SUBJECT_NOT_FOUND(P0002, anot_founderror fromcreateStateMachine().transition()) instead oftrue. Give members an update policy on each machine's table, or calltransition()with the service role where a server action moved records on their behalf. Approval-gated transitions andbulktransitions keep working; a bulk row the caller can't update now fails. The stages timeline only clears and numbers stages within the record's own tenant and machine. Runbetter-supabase sql syncto install module version 2. -
New
better-supabase/stripeentry withstripeFromKey({ secretKey, apiVersion }). It returns astripesource forcreateBilling,reportUsageToStripe,stripePaymentsandstripeTaxthat creates the client once, on first use, from a literalimport("stripe"), so Next.js, Vite and worker bundlers resolve the package and file tracing ships it.stripestays an optional peer.Bundled apps that passed
stripe: { secretKey }got an empty module, because the loader'simport(specifier)was too dynamic for the bundler, and every Stripe call threw that the stripe package was missing even when it was installed. The optional peer loader now carrieswebpackIgnoreand@vite-ignorecomments, so bundlers leave a native import that resolves in Node, Bun, Deno and apps that keep the package external, and the error names the fix: passstripe: stripeFromKey({ secretKey })frombetter-supabase/stripe, or a Stripe client.{ secretKey }keeps working as the plain Node shortcut. -
Add
config.subjects, an app-wide subject registry. Modules that takesubjects(tags, comments, attachments, reminders and the others) use the registered types when their own option is unset, accept a list of registered names, and merge an object entry onto the registered one. The newsubjectsSQL module writessubject_title,subject_urlandcan_subject, which run as the caller.genemitssubjectTypes,SubjectTypeandSubjectRef, and doctor reports a registered table or column the database lacks (BS331) and a registered table without RLS (BS332). -
Breaking:
@supabase/supabase-js2.118.0 is the new minimum, and the@supabase/postgrest-jsdependency moves to^2.118.0. It is the first release that reads theComputedFieldskey and the no-argument function overloads in the types postgrest-typegen 0.6 writes. -
Repository calls on
ctx.postgresandctx.postgresAdminnow return@supabase/server's pool errors (POSTGRES_POOL_BUSYandPOSTGRES_CONNECT_PAUSED) as anetworkerror with status 503 instead ofunexpectedwith 500.networkerrors carryretryAfterin seconds when the pool reports how long it is paused, and the problem response sends it asRetry-After. A pool failure at the start of a$manytransaction now returns an error for each operation instead of rejecting. -
Support sessions now deny by default.
supportSessionsrefuses every start unlessauthorizeor thesupport.authorizeauthorization hook allows it, andauthorize: "store"leaves the decision to the store. A start also needs a second admin by default (policy.approval: "distinct"and thesupport-sessionsmodule optionapproval: "distinct"): the admin callssupport.request, a different admin callssupport.approve, and the SQL module refuses self-approval inapprove_support_requestand in a check constraint on the newsupport_requeststable. Set both options to"none"to keep the old behaviour.approverOfand the SQLisApprovertemplate decide who may approve, with kindsupport-sessionfor support requests and kindai-tool(subject the tool's name) fordecide_ai_tool_approval, whereisApproveralways refuses the approval's owner. The ai-chat module still readscanApprovewhenisApproveris unset. -
ctx.storagewrites in a writable support session.upload,update,remove,copy,moveandpurgeCachefirst run the row change Storage would make as the target, inside a savepoint that is rolled back, so the policies onstorage.objectsdecide withowner_idset to the target. A refused dry run resolves to Storage's403error (AccessDenied) with the policy's message. Then the service client writes, the admin Postgres connection makes the target the owner of the stored object, and itsuser_metadatarecordssupportSessionIdandsupportAdminId.removedeletes only the paths the target may delete. Signed uploads still resolve toSUPPORT_STORAGE_WRITES, and a read-only session still refuses every write withSUPPORT_READ_ONLY.supportStoragetakesadminSqlandsessionfor writes.attachments.putno longer creates a signed upload URL before it uploads, so it works in a writable support session. -
The tags module's
untagqualifies its columns, so its delete no longer fails with "column referencetag_idis ambiguous" against the function's owntag_idparameter, on the polymorphictaggingstable and on adopted link tables. -
Add the
templatesSQL module and thebetter-supabase/blocks/templatesblock: typed, versioned templates that create records.createTemplates({ types })takes a Standard Schema for each type's settings and body and anapplythat creates the record.apply(templateId, { into })uses the newest published version, records which version made which record (template.applied), and starts the workflow-builder workflows attached to the template on the new record. System starters are kept by key withsync(starters), andfork(source, organizationId)copies one into an organization withforkedFrom,forkedFromVersionand abehindflag. Each organization, type and language has at most one default.renderMergeFields(text, values, { escape })anddefineMergeFields(subjectType, fields)render{{ field }}placeholders with no dependencies, andcomposeTemplateEmailrenders an email template for the notifications email channel. Thetemplates.applyworkflow step (TEMPLATES_APPLY_STEP,templatesApplyStep) creates recurring records from a scheduled workflow.Workflow-builder versions can store an input JSON Schema:
versions.save(definition, graph, { inputSchema })setsinput_schema, whichWorkflowVersion.inputSchemareturns and a fork copies.save_workflow_drafttakes a thirdinput_schemaargument. Templates check the inputs of the workflows they attach against it. -
Time tracking and orders ship metric definitions. Time entries get a generated
secondscolumn and carrystartedAtin their events;timeTrackingMetrics()sums tracked seconds per start day, andtimeEntryMetricTimebuckets entry events by that day.orderMetrics({ currency })defines orders placed, revenue and average order value, withORDER_METRIC_EVENTSfor the sink.metricsSinktakes atimeoption andcreateBlocksametricTimeoption for events whose rows sit at another time. -
Add the
time-trackingSQL module andbetter-supabase/blocks/time-tracking: timers and logged time on any record, with one running timer per member and no overlapping entries enforced by an exclusion constraint. A member submits a week as a timesheet that goes through the approvals module; the week is locked while the request is pending and once it is approved, andreopenunlocks it.toWeeklyGridturns a week's entries into rows per record and day for a weekly data grid. -
New
better-supabase/blocks/undoapplies the undo tokens thatrelations.link,relations.unlinkandaudit.revertreturn, checking that every call is an accepted inverse, andbetter-supabase/blocks/undo/reactaddsuseUndoStack, a stack of tokens for a toast's Undo button or a Cmd+Z handler. -
Subject events share one shape, and watchers can follow them.
- Every subject event (
comment.*,subject.tagged,subject.untagged,status.changed,field_value.set,share_link.created,subject.viewed,reminder.sent) carriesorganizationId,subjectTypeandsubjectId, typed asSubjectEventDatafrombetter-supabase/events. watcherHandler(notifications, { types })frombetter-supabase/blocks/notificationsturns outbox rows (outbox.consume) into notifications for the subject's watchers, keyed by the event id, and leaves out the actor the row records.watcherSinkdoes the same for CloudEvents, leaving out an actor the event data names.status.changednow carries the subject's tenant, the previous status infromand thereason. The table trigger records it, so a direct update orrank.move()into a new status emits it too, and an update that keeps the status emits nothing.transition()clears its reason when it returns, so a later direct update in the same transaction no longer writes that reason to the history row.reminder.sentnow carriessubjectType,subjectIdanduserId.mark_reminder_sentno longer fails with an ambiguousoccurrence_atreference, and a second delivery of the same occurrence returnsfalseand records no second event.reminders.deliver(payload)andreminders.jobdeliver one occurrence. WithreminderNotification,createBlockswires them to thenotificationsblock (REMINDER_DELIVERY_QUEUEnames the queue).
- Every subject event (
-
Outgoing webhooks write each endpoint's
formatwith a versionedWebhookEncoder.cloudEvents()stays the default;otlpLogs()sends OTLP/HTTP JSON logs to a collector andsplunkHec()sends Splunk HTTP Event Collector events. An endpoint'scredential_refadds the token from the newcredentialsoption, and an encoder'sclassifyreads responses such as an OTLP partial success or an HEC error code inside a 200. -
Outgoing webhooks pick the body per endpoint. The new
standardformat (standardEnvelope()) writes the 0.8 body,{ type, timestamp, data }or an array of them for a batch endpoint, signed per Standard Webhooks likecloudevents.sql upgradefrom 0.8 gives existing endpointsformat = 'standard', so their receivers keep working, and new endpoints getblocks.webhooks-out.options.defaultFormat(defaultcloudevents), which also covers an adopted table that doesn't mapformator holdsnull. Set an endpoint'sformattocloudeventsonce its receiver reads CloudEvents. -
Breaking: outgoing webhooks send a CloudEvents 1.0 event in structured mode (
content-type: application/cloudevents+json) instead of{ type, timestamp, data }, andtransformnow returns the event'sdata. The event'sidis the delivery id;source,subject,time,dataschemaandtraceparentcome from the newsource,appUrl,typePrefix,dataschemaandtraceparentoptions and frompublish({ subject }). An endpoint withbatch = truegets a CloudEvents batch (application/cloudevents-batch+json) per delivery run.Breaking:
publish_webhook_eventis now(event_type, payload, tenant, event_id, subject, read_permission), and the old four-argument function is dropped. It queues an event only for endpoints whose owner may read it: a user owner needsread_permission(else the module's view permission) through the authorization provider or the access contract, and a service endpoint (created_bynull) needs it in its newpermissionscolumn. User endpoints get nothing when neither the provider nor the access contract is installed.createWebhooksandcreateOutboxtakesubscribers(aSubscriberPolicy) and fall back toauthorization.delivery.subscribers; deliveries it leaves out are canceled, and outbox events it leaves out are counted asrefused. Adopted webhook tables keep working: the newpermissions,batchandsubjectcolumns are used only when mapped. Rerunbetter-supabase sql syncto install version 3 of thewebhooks-outmodule.Breaking: Problem Details for
invalid_request,unauthorized,forbidden,not_found,conflict,rate_limitedandunexpectedat their default status use"type": "about:blank"and the HTTP status phrase as the title. Other kinds keephttps://bettersupabase.com/problems/<kind>.better-supabase codemod 0.9does not rewrite these strings, so update clients that compare ontypeortitle.Old title New title Invalid requestBad RequestNot foundNot FoundToo many requestsToo Many RequestsUnexpected errorInternal Server ErrorverifyWebhookandverifyStripeWebhooktake aseen(id, until)hook and refuse a replayed message id with aconflicterror (WEBHOOK_REPLAYED); a throwing hook givesWEBHOOK_DEDUPE_FAILED. A malformedwhsec_secret now fails withWEBHOOK_INVALID_SECRETinstead of throwing. -
The
work-itemsSQL module andbetter-supabase/blocks/work-itemsadd issues and tasks on pipelines. Installing work-items binds thework_itemtype in the pipelines module with one pipeline per team, Linear's categories (triage, backlog, unstarted, started, completed, canceled) and the stage's category as the item'sstate. Items have an identifier, a parent the table keeps free of cycles, several assignees (capped bymaxAssignees), a priority from 0 to 4, an estimate, progress, start, end and due dates, a lock that keeps the dates, and optional projects and iterations.update(changes)applies grid edits and Gantt drags one by one, closing stampsclosedAtand a close reason,assignnotifies new assignees and makes each watch the item, andtreerolls progress up for a Gantt group. -
A workflow-builder
conditionnode can test a filter tree:config: { filter, fields }, wherefilteris aFilterQuery(the format of list filters and the rules block) and each field'sidis the path it reads underinput,resultsorsubject. The single-path form ({ path, op, value }) keeps working. Event triggers take the same shape inconfig.when, overtype,tenantandpayload...:triggers.onEventskips a trigger whosewhendoesn't match, andtriggers.saverefuses one it can't use withinvalid_input. New exports:filterConditionOf,matchesFilter,triggerMatchesand the typesWorkflowFilterCondition,WorkflowFilterField,WorkflowNodeConditionandTriggerEvent.conditionOfnow returns aWorkflowNodeCondition. -
The workflow builder adds record-bound runs, test runs, system workflows and restricted definitions. A definition lists
subjectTypes, andrun({ subject })starts it on a record throughworkflow_subject_start_target, which checks the type andcan_subject; event triggers attach the event's record and conditions read asubjectroot.test({ definition, stubs })runs the draft with stubbed steps, skipped sleeps and stubbed approvals, filling missing stubs from each library step'soutputSchemaexample. A graph may have several trigger nodes: a trigger picks one withconfig.node, and the run starts there.scope: "system"definitions belong to the app; organizations see them,definitions.forkcopies one into the tenant (lists showupstreamVersionandbehind), anddefinitions.optOutstops its runs there (newworkflow_opt_outstable).restricted: truelimits running and editing toworkflow.adminanddefinitions.grants(newworkflow_definition_grantstable). Static executors spreadgraphRunFields(meta)and setexecutorRunsTestsongraphStarter, which refuses test runs otherwise.Breaking:
save_workflow_definition,workflow_definitions_list,workflow_start_targetandworkflow_run_principaltake new arguments,versions.runAs(version, tenant?)takes the tenant for system definitions, andvalidateGraphno longer reports a second trigger node. Runbetter-supabase sql syncto install module version 2. -
Published workflow-builder versions now run with their publisher's rights.
publish_workflow_versionrecordspublished_by,owner_kindand thepermissionsthe version's steps need, and refuses a publisher who lacks one (WORKFLOW_PUBLISHER_FORBIDDEN). WithcreateWorkflowBuilder({ authorization }),automation.mayPublishalso decides eachversions.publish(version, { claims }).Breaking: each step must call
builder.versions.runAs(call.version), which fails withWORKFLOW_PUBLISHER_REVOKEDonce the publisher loses a permission or their membership, or whenautomation.runAsreturnsnull. Versions published before this release have no recorded publisher and fail until they are published again. An organization-owned version, published by the service role, runs only as the service principalrunAsreturns.GraphStepCall.versionandGraphRunMeta.versionIdcarry the version id to each step.Workflow nodes, MCP tools and inbox commands read the provider's operations table first:
workflow.node.<step>,mcp.tool.<name>(through the newcreateMcp({ operations })) andinbox.command.<name>. Doctor reportsadmin()in a file that runs workflow-builder steps (BS333). -
startOnEventand the schedule starts ofworkflowStartertakerunAs: a publisher and the permission keys the run may use, or a function of the event or start call that returns them. The run starts as the publisher, capped to those keys, and the event's actor or the schedule's creator is recorded asbs.triggerfor audit only.WorkflowStartCallgainssource, andWORKFLOW_PUBLISHER_FORBIDDENerrors carry the missing keys aspermissions, in theDbErrorand in Problem Details.Breaking: a schedule start without
runAsthrows, so a schedule no longer runs with the rights of the member who created it. -
Workflow runs can belong to a record.
workflow_runsgainssubject_type,subject_id,principal_kind,principal_id,mode(liveortest) andtrigger_node.runs.list({ subject, mode })filters by them,admission.request({ subject })queues a start for a record, outbox events carrysubjectTypeandsubjectId, andstartFor(ctx, workflow, args, { subject })stores the record as thebs.subjectattribute (subjectAttributebuilds it). Test runs emit no outbox events and are left out of run lists by default.Breaking:
record_workflow_run,workflow_runs_listandrequest_workflow_starttake the new arguments, andsql syncdrops the old signatures. Runs thatstartOnEventandworkflowStarterstart withrunAsnow record the user who triggered them asbs.actor(andactor_id), not the publisher; the publisher is inprincipal_kindandprincipal_id, andrunAstakesprincipalKind.startFordropsbs.principal_kindandbs.principalfrom caller attributes. Runbetter-supabase sql syncto install version 2 of theworkflowsandworkflow-sdk-worldmodules. -
better-supabase add <block>is the documented way to install a block: it writes the module files likesql add, then wires the block's client intolib/blocks.tsand prints the glue command.addnow takes--tests-dir, so it accepts every optionsql adddoes.sql addstays as the low-level command that writes only the SQL files and the config entry. The header of generated module files, the doctor hints for grants, MFA and realtime triggers, and the Data API grant error now namebetter-supabase add. Re-runbetter-supabase sql syncto refresh the header in existing module files; it is a SQL comment, so the schema doesn't change. -
CLI fixes.
doctor --claimswithout--explainexits with code 2 instead of being ignored. A failed database connection suggestssupabase startonly when a local host refused or dropped the connection, not for a remote host or a rejected password.openapi emit --check,seed --check,skills install --check,scaffold api --checkandspec checkprint the diff of each stale file.codemod --helplists the 0.9 codemod.bs.resourceinbetter-supabase/honomatches paths with the same rules asresourceRouter: a malformed id returns a 400invalid_inputproblem, and an unknown path under the resource returns a 404 problem instead of Hono's plain-text 404. -
clientIp(request)reads the lastx-forwarded-forhop, the one your own edge appended, instead of the first. A client controls the hops to the left, so it could send any IP asSb-Forwarded-Forto Auth on a refresh and dodge Auth's per-IP limit or spend another IP's. Behind more than one proxy, pass your ownclientIpreader. -
better-supabase configno longer printssource.accessToken. Every string under a key that names a credential (token,secret,password,apiKey,privateKey) prints as<redacted>, and the password in any URL is replaced, in text and in--json. -
better-supabase envwrites.env.local(or the--outfile) with mode0600, and tightens an existing file's mode even when its contents didn't change. The file holds the secret key, the database URL and the JWT secret, and it used to be created readable by every user on the machine. -
Every CLI request to the Management API and GitHub now goes through one HTTP client. It sends a
better-supabase/<version>user agent, times out after 30 seconds, and logs each request under--debug. A request that gets no response fails with the newnetwork_errorcode. A command that reads a hosted project withoutSUPABASE_ACCESS_TOKENnow fails withauth_required(exit code 3) instead ofmissing_value. -
better-supabase introspect --snapshot <file>now converts a saved snapshot without connecting to a database, and rejects--snapshotnext to--db-url-stdinor--project-refwith a usage error. -
A missing positional (
preset decode,blocks view,sql add,sql print) now fails withinput_requiredand exit code 3, with the positional inmissingand its values inchoices, instead of a usage error. A bare group, or no command under--json, returns ausageenvelope that lists the subcommands inchoices["<command>"], and--agentis checked before the root help prints. -
The CLI starts faster. The bin turns on Node's module compile cache and answers a bare
better-supabase --versionwithout loading the CLI. -
better-supabase codemodruns when the config file fails to load, socodemod 0.9can migrate a config that still setssql.modules. It walks the directory that holds the discovered config file, or--cwdwhen there is none. Commands built withdefineCliCommandopt in to the same behaviour withrunsWithInvalidConfig: true. -
better-supabase codemod 0.9puts the movedblockskey in sorted position when the config's top-level keys are already sorted, so a config checked by asort-keyslint rule stays valid. A config with unsorted keys still getsblocksright aftersql. -
The comments block docs say that
options.notify: falseleaves following on, thatoptions.follow: falseturns it off, and that an adopted subscriptions table must accept the commented subject types while following is on. -
encodeDesignnow throws aDesignTooLongError(still aTypeError, with the code'slength) when a valid design is too long for a URL, so a caller can tell it apart from an invalid design.better-supabase/presetalso exportsappReservedColumns(tenant), the columns every app table can get from its scope, andisAppDefault(type, value), the default checkappTablesruns, so an editor can refuse a column name or a default before encoding.Create uses them: a key to
auth.usersgetsowner_idinstead of the reserveduser_id(which made the design fail to encode with a misleading "too large for a link" message), the Default field says which defaults a type takes, and changing a column's type drops a default the new type can't take. A table can now reference itself (parent_id,on delete set null) and reference the same table twice (owner_id,assignee_id, or<table>_2_id). Create also starts without blocks, from "Draw your own tables"./create/prompt.mdtakes&design=<code>, and the AI instructions link to it with the design. -
Doctor BS330 no longer reports an adopted module's opt-in tables that
blocks.<name>.tablesdoes not map: the notificationsdeliveryEventsandsuppressions, the auditrestrictedtable and the invitationsplatformInvitations. The generated SQL uses those tables only when they are mapped, so the check now matches it and still reads a mapped table's columns.ModuleTableSpecgainsadoptOnlyWhenMappedto mark such a table. -
Doctor's BS213 check no longer counts a subject's
deletedAtcolumn fromconfig.subjectsas a column that grants access.can_subjectruns as the caller and only hides soft-deleted rows, so a user who may write that column could already read the row. A column the authorization provider lists indecidingColumnsstill counts. -
Doctor BS213 no longer flags a single-column primary key, or a tenant column that every write policy pins to
better_supabase.current_tenant_id()without anor, because neither lets a caller grant itself access. A column the authorization provider lists indecidingColumnsis still flagged. -
Doctor's BS321 check no longer reads
create extensioninside a string literal as a statement. The jobs module's error message that tells you to createpg_cronwas reported as an extension no migration creates. -
Doctor BS208 no longer warns about temporary files written by better-supabase's own catalog reads.
introspect,genanddoctornow start each query they send over a database connection with the comment/* better-supabase */, and BS208 leaves those statements out, so runningintrospectbeforedoctor --stricton a large schema no longer fails the check. -
Doctor BS208 no longer warns when the only statements that spilled to temporary files ran as Supabase's service roles, such as PostgREST's schema cache query on a large schema. With
pg_stat_statementsinstalled, the top statements it lists are the app's own. -
doctorreports fewer false warnings on block schemas. BS206 no longer counts a policy that already calls a security definer helper as(select helper())with no arguments, such assession_active(). BS213 counts a tenant column pinned bybetter_supabase.can('tenant', column, ...)orcolumn in (select better_supabase.tenant_ids_with(...))like one pinned tocurrent_tenant_id(), and leaves out a block's soft-delete column that a write can set but never clear, such ascomments.deleted_at. Blocks declare those columns with the newSqlModule.hidingColumns, andbetter-supabase/sqlexportsmoduleHidingColumns.The generated app-tables pgTAP test now expects the
bs_session_activepolicy on the tables thatblocks.sessions.options.policiescovers. -
doctorno longer reports BS204 for a view's tenant column, since a query on a view uses the indexes of its tables. BS213 now counts a tenant column that every write policy holds tocolumn in (select better_supabase.member_organization_ids())as pinned, the same astenant_ids_with(...), so app tables that are subjects no longer warn. -
The drive module drops
drive_insert_nodebefore it recreates it, so moving drive from a managed table to an adopted one (or renaming the table) no longer fails with "cannot change return type of existing function". -
The Flags SDK adapter serves a
nullvariant when the declaration'sdefaultValueisnullor left out, and treats a default variant that is missing from the variants as a missing flag instead ofnull.evaluateFlagreturnsfound, so callers can tell the two apart. A flag row with an unknowntypealways serves its fallback: the OpenFeature provider resolves it withPARSE_ERROR(orGENERALwhen theerrorCodesmap has none), andgetProviderDatashows it as a hint in Flags Explorer. -
better-supabase genwrites the read-sets module again whensql.dirpoints outside the project, as in a monorepo whose apps share one Supabase stack. It failed with "is outside the project root" whilegen --checkpassed. -
Fix
finish_importin theimportsSQL module: itsidparameter clashed with the runs table'sidcolumn, so finishing a run raised "column reference is ambiguous". -
Three SQL modules pass
supabase db lintagain when more blocks are installed.save_viewandset_user_stateno longer fail with an ambiguous column reference, and the forms module reads an adopted custom field options table without a constant query that plpgsql_check rejects when the table is missing. The saved-views indexes are now named after their tables, so renamingviewsorpreferencesno longer collides with another install's index names. Runbetter-supabase sql syncand generate a migration. -
The HMAC and HS256 helpers type their imported keys from
crypto.subtleinstead of the globalCryptoKey, so the published types check under@types/node24 without the DOM lib. -
bs.middleware()frombetter-supabase/orpcnow type-checks in.use()on a single contract procedure with a typed output, so a contract-first router can guard one procedure withpermission,rolesorrequireTenant. The oRPC docs show the pattern and explain that theauthorizerpassed tocreateOrpcdecides every permission. -
The optional
@supabase/mcp-server-supabasepeer now accepts 0.14 as well as 0.13 (>=0.13.0 <0.15).supabaseMcp()andsupabaseMcpHandler()are tested against 0.14.0. -
The direct Postgres executor runs a counted read's rows and count queries in one transaction, so both see the same snapshot. On
createPostgres()clients this also halves the round trips offindMany({ count: "exact" }). -
The direct Postgres executor looks a function up in
pg_proconce per executor instead of on every call without generated metadata (block calls included), and looks it up again after an error that says the function changed. Arguments forOUTandTABLEparameters are dropped from the call, as PostgREST drops them. -
The teams module's
update_teamfunction qualifies its column references, so plpgsql_check no longer reportsnameas ambiguous and the update no longer fails at runtime. -
move()in therankmodule now writes the group column as its own type, so a board grouped by auuidstage id or an enum column moves rows instead of failing withcolumn ... is of type uuid but expression is of type text.sql syncrewrites the rank module. -
The block manifests and the
ui-recipesskill reference list 46 new UI recipes, from the CRM deal board and the quote builder to the drive explorer, the form builder and the webhook endpoints table. Each one points to working code in the Next.js example. -
sql syncno longer stops withblocks.share-links.api: found no definition of share_ai_chat(uuid, text) to wrapwhenshare-linksandai-chatare installed together withsql.apiset. The four ai-chat sharing functions in the share-links module now putreturnson its own line, so the Data API wrappers are written for them. Re-runbetter-supabase sql syncand generate a migration; the function bodies don't change. -
The
better-supabase-apiskill now shows the filesbetter-supabase initwrites: the Expo native client issrc/lib/supabase/client.native.ts, and each Edge Function createsbsin its ownserver.ts. -
gen,doctor,seedandsnapshotnow find a local stack that runs on the Supabase CLI's stack engine ([experimental] stack = true), which picks its ports per checkout. When no database URL is configured andsupabase/config.tomlsets no[db] port, they readDB_URLfromsupabase statusbefore falling back to port 54322. -
Moving a time entry to another day now rolls up both days.
time_entry.updatedcarriespreviousStartedAt, a metric'stimefunction may return several times, andmetricsSinkrolls up one window per day they fall on. -
toSessionrefuses an invalidactclaim on a hand-builtAuthStatethe same wayresolveAuthdoes: the session is{ kind: "invalid", reason: "actor" }with codeACTOR_INVALID, never the user without an actor. Before, a malformed agent level (asession_id, an empty tool name,toolsthat is not a list) read as the plain user there. TheACTOR_INVALIDmessage now namesagentamong the accepted kinds. -
The
updated-atblock is now titled "Update timestamps" in the preset catalog, in place of "updated_at triggers", so it reads like the other block titles. The block's key staysupdated-at, so configs and preset codes keep working. -
The outgoing webhooks block's default retry backoff uses equal jitter: each wait is at least half its step and at least a second. Full jitter could schedule a retry for the same instant as the failure, so a struggling receiver got hit again at once.
-
The
workflow-sdk-worldSQL module follows@workflow/world-postgres5.0.4: its DDL adds theseq_in_bandcolumn toworkflow.workflow_event_slots, from the0026_add_seq_in_bandmigration.
0.8.0 (2026-10-12)
-
New
better-supabase/arazzosubpath:createArazzoandarazzoFormatrender Arazzo 1.0 and 1.1 workflows from the API model, with source descriptions that point at the OpenAPI and AsyncAPI files.defineWorkflowtypes each step by theoperationIdit calls, andpaginationWorkflows,createThenGetWorkflowsandauthWorkflowbuild common workflows from your resources' operations. -
New
better-supabase/asyncapisubpath:createAsyncApiandasyncapiFormatrender AsyncAPI 3.0 and 3.1 from the same API model as OpenAPI. The document describes Realtime table changes and broadcast topics on the websocket server, CloudEvents with a header trait (CLOUD_EVENT_TRAIT) and adataschema, outgoing webhooks, and the events that resource actions emit. -
audit_eventandaudit_event_trustedtakesupport_session,impersonated_byandimpersonation_reason, stored ahead of the values in the caller'sactclaim. The service role may pass any values; another caller only itself asimpersonated_by, from a token without anactclaim.sql syncdrops the previous signatures. Module actions pass them throughModuleAudit.supportSession,impersonatedByandimpersonationReason, so thesupport-sessionsmodule'ssupport.startedandsupport.endedentries now carry the session id, the admin and the reason in the impersonation columns instead of only in metadata.AuditEventInputgainssupportSessionId,impersonatedByandimpersonationReason, andauditEventOffills them forsupport.*events fromsessionId,adminIdandreason. -
createServertakes anauthorizer: a runtime decision point (apiVersion: 1) that receives each request in the AuthZEN information model (subject, action, resource and context) and returnsgranted,deniedorapproval-required. better-supabase builds the subject from the verified request only (subject.properties.claimscarries a read-only copy of the verified access-token claims, so an adapter can read memberships and roles without a database read) and refuses anything butgranted.defineAuthorizerand its types (Authorizer,AnyAuthorizer,AuthorizationRequest,AuthorizationOutcome,AuthorizationSubject,AuthorizationResource,PermissionRef) are exported frombetter-supabase/server, andbetter-supabase/testingaddstestAuthorizer,staticAuthorizerand thetestDocumentFormatconformance kit.Routes, actions,
bs.requireand the guards in every adapter take apermissionoption that the authorizer checks.defineResourceaddshooksthat run around the repository call andactions(defineAction) on an item or a collection, served next to the collection and item routes by Honoresource(), edgeresources()and the new Next.jsbs.resources(), which returns the handlers for a catch-all route. MCP tools take apermissiontoo, andtools/listhides the tools the authorizer denies. -
The CLI reads its options from
better-supabase.config.ts, sobetter-supabase genis the one command a project runs.genruns every generator the config sets up, in order: the typed client,sql sync,spec emit, the seed client,scaffold apiand, when listed,env.gen.tasksor--taskspicks the list,gen --checkchecks them all, andgen --watchreruns the steps whose inputs changed.gen.watchIntervalsets the watch interval.- New config keys give each repeated flag a default:
env.outputandenv.prefix,doctor.only,doctor.formatanddoctor.output,specs.manifest,scaffold.api,skills.agentsandkeys.output. A flag still wins for one run. $env.<name>and the$development,$production,$testand$ciblocks override the config per environment. The CLI applies the one named by the new global--envflag, then$BETTER_SUPABASE_ENV, thenciwhen$CIis set.better-supabase configshows the active environment.initrecords the integrations it set up underintegrations, andaddwithout an argument sets up the listed ones whose files are missing.scaffold apiandaddprint the config entry for the flags you passed.
-
A
Dbcarries Storage as the same caller:db.$storageis the newstorageoption ofconnect(client, context, { storage }), or the client'sstorage, and it throws on a connection with neither.bucket.connect(db.$storage)and blocks givendb.$storagethen follow whatever theDbruns as. In a support session,ctx.db.$storageandctx.sql.$storagearectx.storage, which is now typedStorageApi, so the same code reads Storage as the caller in a normal request and as the target in a support session. -
dbTransport(db, { schema })frombetter-supabase/blocks(and every block entry) calls block functions through aDb's executor, so a block follows whatever theDbruns over: the Data API forctx.dbin a normal request, and direct Postgres as the target user in a support session or for an API key. It rejects with the raw database error likerpcTransportandsqlTransport, so block error mappers see the same codes and hints, and aDbErrorthat a transport rejects with now passes through block calls unchanged. -
Table and column comments now reach the generated meta as
descriptionanddeprecated, and the JSON Schema output marks deprecated tables and columns.jsonSchema()takes atarget(draft-2020-12,draft-07oropenapi-3.0, typed asJsonSchemaTarget). MCP tools take ajsonSchemaTarget, andtools/listconverts tool schemas to draft-07 for clients on protocol revisions before 2025-11-25.zod()takesflavor: "mini"(typed asZodFlavor) to generate Zod Mini schemas, and CloudEvents take adataschemaoption that receives aDataschemaContext. -
New
better-supabase/overlaysubpath for OpenAPI Overlay 1.0, 1.1 and 1.2 documents.applyOverlayandapplyOverlaysapply them to any JSON document, with RFC 9535 JSONPath targets, a diagnostic for each target that matches nothing, and the 1.2 reusable actions (expandReusableActions).defineOverlaytypes an overlay in code, andoverlayFromDiffwrites the overlay that turns one document into another. JSONPath comes from the optionaljsonpath-rfc9535peer, loaded on first use, or from an engine you pass. The subpath imports no Node built-in, so it runs on every WinterTC runtime. -
A cleanup of shared code inside the package, with a few fixes.
-
Fix
doctorBS303 comparing generated files with a different line-ending rule thangen, fixsql upgradeignoring the provider defaults for modules, and flush pending events infinallyin the React Router, SvelteKit, Hono, Edge and oRPC adapters when a handler throws. -
Bound the HS256 key cache and the verified-token secret ids, and strip the event type prefix the same way in every block.
-
Move the Standard Webhooks code to
core/signaturesand the HMAC helpers tocore/hmac, share one optional-peer loader and one bounded TTL cache, and addmethodNotAllowed()tocore/problem. None of these paths are public exports. -
Split
config/config.tsintoconfig/types/*,expose.ts,json.ts,resolve.tsanddefaults.ts.resolveConfignow resolvesgen.watchInterval(default 2000), the SQL registry and the CLI read their fallbacks fromCONFIG_DEFAULTS, andGenTask,IntegrationNameandSkillsAgentderive from the newGEN_TASKS,INTEGRATION_NAMESandSKILLS_AGENTStuples, whichbetter-supabase/confignow exports. -
Split
sql/registry.tsintomodule-types.ts,registry.ts,module-context.ts,render.ts,paths.ts,markers.ts,upgrade.ts,introspect.tsand one file per inline module undersql/modules. A module declaresextrasfor SQL that depends on the whole layout, replacing the name switch in the renderer, and the tenant and provider entitlement checks share one template. -
Share one cron route guard (
core/cron-route), one time budget (budget), one lease heartbeat, oneblockEmitterand onetoBlockErroracross the jobs, outbox, webhooks, notifications, organizations and billing blocks. -
Split the jobs, billing, notifications, data-lifecycle and webhooks blocks into type, helper and per-factory files; the public subpaths are unchanged.
-
Split
server/resource,server/server,core/repository,core/define,next/create,testing/conformance,ai-sdk/mcp,ai-sdk/messagesandworkflow-sdk/worldinto type, helper and per-kit files, and share oneisRecordfromcore/guards. -
Share the AI SDK HTTP helpers, add
withFlushto flush events after a response, and run the React hooks on the same bindings as Vue, Solid and Svelte (ClaimsOfandProfileOfnow live in the bindings). -
Build the MCP table tool schemas from the same page schemas as the OpenAPI document, so list pages describe their page counts, and share
integerandwhereClausebetween the Postgres and SQLite compilers. -
Split server client construction into
server/clients.ts(with an injectablecreateClient),db.$searchintocore/db-search.ts, the topic SQL intorealtime/topic-sql.tsand the page helpers intocore/paginate.ts. The incoming webhook endpoint now shareshitRateLimitandreceiveWebhookwith the rate limiter and the inbox, andgenbuilds the spec step withspecOptionsFromConfig.
-
-
powersyncExecutortakes afallbackexecutor. Reads that SQLite can't run (an include, full-text search, a function source) anddb.$rpcgo to the fallback, usuallypostgrestExecutor(supabase); writes never fall back.checkSqlite(betterSupabase, list, { all: true })returns every unsupported feature a list uses instead of the first.db.$rpcon an executor withoutrpcnow returns aDbErrorof kindunsupported(HTTP 501) instead ofinvalid_request. The PowerSync docs add a guide to porting a PostgREST list. -
New
better-supabase spec emit,spec checkandspec validatecommands.spec emitrenders every output in the newspecsconfig key (format, version, output file, overlays, JSON or YAML, and an optional reference page), applies the overlays and caches renders by content hash.spec checkfails when a file on disk is out of date,spec validatechecks each document against the official JSON Schema for its version, and every run writes a diagnostics manifest.--fail-on,--ui,--watchand--manifestcover CI, reference pages and local work.openapi emit --checknow compares text the same wayspec checkdoes.better-supabase scaffold apiwrites the resource routes and an OpenAPI route for Hono or Next.js:lib/<name>.generated.tson every run andlib/<name>.tsonce, for your own changes.The
openapiconfig key is deprecated. It still works and maps ontospecs; move it tospecs.outputswithformat: "openapi". -
New
better-supabase/specsubpath:defineApibuilds one API model from the schema, resources, routes and plugindescribehooks, and renders it in any registered document format and version, with transforms, overlays and lint diagnostics.defineDocumentFormatadds a format of your own (apiVersion: 1),serializeDocumentandspecResponseserve a rendered document with a strong ETag, andspecReferenceserves a reference page for Scalar, Swagger UI, Redoc, Stoplight Elements or RapiDoc, from jsDelivr at pinned versions with SRI hashes or from your own assets, with a CSP nonce.better-supabase/openapinow renders OpenAPI 3.0, 3.1 and 3.2 from that model, and3.3-previewwhen you ask for it.createOpenApikeeps its signature and takes aversionoption. It now emits OpenAPI 3.1.2 by default (it emitted 3.1.1), so a snapshot of theopenapifield changes. 3.0 output lowers schemas to the 3.0 Schema Object, and the 3.2 fields travel asx-oai-*extensions below 3.2.openapiFormatlints a document for duplicate operation ids, path parameters that don't match the template, unknown security schemes and$refs that don't resolve. The tenant, soft delete and timestamps plugins describe their columns and headers in the document. -
Add the
standardSchema()generator. It writes<output>.standard.tswith a Standard Schema per table for its Row, Insert and Update shapes, built on the newtableSchema()runtime helper, so apps can validate writes without installing zod or valibot. Each schema also implements Standard JSON Schema for thedraft-2020-12,draft-07andopenapi-3.0targets, and the file exportsvalidatorsfor the validation plugin.gen --metadata --emit standard-schemaprints it. Generators now receiveruntimeImportin their input. -
bucket.connect()andbuckets.connectStored()take anyStorageApi, not only a supabase-js client:StorageClientis nowStorageApi | { storage: StorageApi }, whereStorageApiis an object whosefrom(bucket)returns aStorageBucketApi, the file methods ofsupabase.storage.from(bucket)typed structurally with the supabase-js{ data, error }results. A supabase-js client and itsstoragestill type-check unchanged.bucket.apply(),defineAnalyticsBucket().connect()anddefineVectorBucket().connect()call the admin API, so they take the newStorageAdminClient(a supabase-js client) instead. -
Supabase Lite support.
createServer(betterSupabase, { backend: "lite" })verifies Lite's HS256 tokens locally againstSUPABASE_JWT_SECRET(a newenvsetting, at least 32 characters), skips the JWKS prefetch, and withliteDriverset tosqlite-postgresorsqlitereturns anunsupportederror for$rpcwithout sending a request.liteStack()inbetter-supabase/testingruns Lite in the test process on in-memory SQLite or PGlite, applies migrations, schemas and seed SQL, and signsasUsertokens with the Lite secret.genanddoctorread a Lite project's[db] driver: thepostgresdriver's[db] url, or the migrations and declarative schemas replayed into an in-memory PGlite (source.lite: falseturns this off). Doctor adds BS328 ($rpcon a Lite SQLite driver) and BS329 (Realtime or Edge Functions on Lite), and skips BS403 on Lite projects.init --liteprints Lite's install and CLI steps.@supabase/liteis an optional peer (>=0.11.0 <0.12). -
Connect agents to Supabase's MCP server and serve it from your app.
supabaseMcp()inbetter-supabase/ai-sdk/mcpreturns the server URL for a project and the tool schemas from@supabase/mcp-server-supabase, andconnectToolstakes them asschemasto type each tool's input and output.supabaseMcpHandler()inbetter-supabase/mcp/sdkserves Supabase's MCP server behindcreateMcpAuth: it checks the caller withauthorize, reads the Management API token through aCredentialProviderand stays read-only unless you passreadOnly: false.@supabase/mcp-server-supabaseis an optional peer (>=0.13.0 <0.14) loaded on first use. -
Support sessions that pass their expiry are now ended and recorded. The
support-sessionsSQL module addsexpire_support_sessions(), for the service role only, which ends every running session pastexpires_atthroughend_support_session(id, 'expired')(so each gets itssupport.endedaudit entry) and returns them.bs.support.expire()runs it through the store's new optionalexpire()(the SQL store calls it overpostgres.admin) and emitssupport.endedwithendedBy: "expired"for each session, andbs.support.expireRoute({ secret })serves it to a cron caller. A store withoutexpire()fails withSUPPORT_EXPIRE_UNSUPPORTED, andtestSupportSessionStorechecks thatexpire()leaves running sessions alone. -
supportStorage()andctx.storagereturn aStorageApi, the file API ofsupabase.storage, sobucket.connect(ctx.storage)and blocks that takestoragework in a support session.listandlistV2callstorage.searchandstorage.search_v2over Postgres as the target, so RLS filters each page as Storage would: a page is no longer shorter thanlimitwhen some entries are hidden (which endedbucket.listandsweepearly), and the prefix matches without case, as Storage matches it.existsandinforeadstorage.objectsas the target, anddownload,createSignedUrlandcreateSignedUrlscheck visibility there before the service client serves the object, now withtransform,versionId,cacheNonceanddownloadpassed through. A hidden object answers like a missing one (NoSuchKey), and paths are normalised as storage-js normalises them before the check.getPublicUrlis built without a check. Every write resolves to a403error withSUPPORT_READ_ONLYorSUPPORT_STORAGE_WRITES, which a connected bucket maps toforbidden. TheSupportStorage,SupportStorageAdmin,SupportStorageBucket,SupportStorageEntryandSupportStorageListOptionstypes are removed. -
In a support session,
ctx.storagereads Storage as the target user, wherectx.supabasethrows.supportStorage({ admin, sql, readOnly })is exported frombetter-supabase/serverfor the same reads outside the server context. -
better-supabase/tanstack-db/supabaseaddssupabaseCollection(betterSupabase, supabase, table, options), a TanStack DB collection on@supabase-labs/tanstack-db(a new optional peer,>=0.1.0 <0.2). Live queries load on demand through PostgREST,realtime: truekeeps them current throughpostgres_changes, and inserts, updates and deletes go through the table's repository, so RLS, hooks, events and plugins apply.writes: "direct"keeps the package's own handlers. It needscasing: "snake"and tables in thepublicschema;collectionOptions()frombetter-supabase/tanstack-dbstays the choice for camel casing. -
Call Edge Functions with a typed input and output.
defineFunction()inbetter-supabase/edgechecks the JSON body with a Standard Schema before the handler runs as the caller (422 with the issues when it fails) and can check the output too.ContractOf<typeof fn>exports its contract, andfunctions<Contracts>(supabase).invoke(name, input)inbetter-supabase/clientcalls it through supabase-js'sfunctionsclient and returns anAsyncResult: Problem Details come back as theirDbError, and network and relay failures asnetworkerrors. -
attachments.uploadandattachments.putdelete the record they created when Storage refuses the signed upload URL or the upload, such as a bucket policy or the read-only Storage of a support session, and return the refusal. Before, the record stayedpendingwith no object behind it. -
The CLI reads
$SUPABASE_DB_URLwhen$DATABASE_URLis unset, sogen,introspect,doctorandseed --applyconnect with the variable the Supabase CLI andbetter-supabase envwrite.$DATABASE_URLstill wins when both are set. Thegendocs now list the real source order: a configuredsource.snapshotcomes beforesource.dbUrl. -
bs.loader()without a request now namescreateStaticLoaderfromexpo-serverand the SDK 57unstable_useServerRenderingoption. The Expo docs say whichapp.jsonoptions SDK 57 needs and that SDK 58 needs none, and show how to callbs.requestinsidecreateServerLoaderor wrapbs.loader, which is anexpo-serverLoaderFunction. -
Bind
jsonandjsonbarguments ofrpc()correctly over direct Postgres whendatabase.types.tsis absent: argument types now come from the catalog, so string arguments are JSON-encoded like they are with generated types. -
bs.authed()inbetter-supabase/orpcnow checksroles(and the newpermissionoption) on their own. Before, it checked them only whenrequireTenantorauthorizewas also set, so a procedure guarded byrolesalone let every signed-in caller through. -
The
@supabase/postgrest-typegenpeer accepts>=0.4.0 <0.5instead of exactly 0.4.0, so an app that installs another 0.4 release no longer fails strict peer checks. The CLI is still tested against 0.4.0, andgenprints a notice when another release is installed. Doctor's new BS601 reports an installed peer outside the range better-supabase declares, and the new Peers page lists every peer, its range and the subpaths that need it. -
The Postgres executor (
better-supabase/postgres) now sends values forjsonandjsonbcolumns as JSON text in inserts, updates and upserts. Arrays, arrays of objects and plain strings failed before withinvalid input syntax for type json, because node-postgres sends a JavaScript array as a Postgres array literal. A string is stored as a JSON string, as it is over PostgREST,nullstays SQLnull, and each element of ajsonb[]column is encoded the same way. Postgres array columns such astext[]still receive arrays. Comparison filters (eq,neq,gt,gte,lt,lte) on ajsoncolumn send an array or object operand as JSON text too. -
Postgres error
25006(a write in a read-only transaction, such as in a read-only support session) maps toforbiddenwith code25006, the message "This connection is read-only, so the write was refused" and a hint, instead ofunexpectedwith the raw "cannot execute ... in a read-only transaction" text. The original text is kept indetails. -
Queries through
ctx.dbandserver.dbForwith credentials that did not verify now return the unauthorizedDbErrorinstead of running as anon, so a handler without a route guard cannot read data with a bad token. -
The README now names
@supabase/postgrest-typegennext to the runtime packages, and links the new Supabase packages page, which lists every Supabase package better-supabase uses, how it is installed and how the CLI relates to thesupabaseCLI. -
The
support-sessionsmodule's platform-target check honourssql.modules.invitations.options.platformRoles.through.whereunder theprovideraccess model: a target counts as platform staff only through a role that matches the condition, so a roles table that mixes tenant and platform scopes no longer blocks support sessions for users who hold only tenant roles. -
The support session store reads its time values with the definition's
temporal:createServerpasses it tosupportSessions(...).createand on to the store through the new optionalSupportSessionStore.withTemporal, andsqlSupportStore(postgres, { schema, temporal })takes an explicit namespace that wins over it, as block creators do. -
bucket.sweep({ olderThan })recognizes aTemporal.Instantfrom any copy of Temporal by its tag, so an instant from a second polyfill copy is no longer read as a duration.createJobs(source, queues, { now })takes a clock forrunAtdelays and schedule runs, and block events onbetterSupabase.eventstake theirtimefrom the definition'snowoption. The Temporal docs now lead withdefineSupabase(schema, { temporal })and keeptemporal-polyfill/globalas the alternative. -
New subpath
better-supabase/better-result:withBetterResult(db, toResult)returns a view ofdbwhose repository methods,$rpc,$run,$many,$searchand list queries ($list) return better-resultResultvalues, so call sites no longer convert each result.toResultis adefineBetterResultErrorsconverter or{ Result, mapError }. better-result is an optional peer (>=3 <4) that the subpath imports only for types.
0.7.1 (2026-10-11)
suspendAccountwithsuspended: truebans the user and keeps their sessions, so Auth answers refresh andGET /auth/v1/userwithuser_banned,sessionStatusreturns"banned"andbs.proxy({ endedSession })redirects withreason=account_banned. Deleting the sessions made Auth answersession_not_found, so a suspended user read as"ended". ThesessionsSQL module'ssession_active()already refuses a banned user's tokens.suspended: falsenow ends the sessions kept during the ban before it lifts it, so a reinstated user signs in again, andendedis0on a suspension. PassendSessions: trueto delete the sessions on suspension too, for apps without thesessionsmodule. Doctor's BS106 description and the docs now say thatfromPoliciesmakes only tables with RLS on service-only.
0.7.0 (2026-10-10)
sessionStatusreturnsbannedwhen Auth rejects a token witherror_code: "user_banned", a rejectedrefreshSessionoutcome carries the Authcode, and the resolution reportssessionEndedReason.bs.proxy({ endedSession })redirects banned accounts withreason=account_banned;endedSession.reasonsrenames thereasonvalues.SessionStatusgains"banned", so a switch over it needs a case for the new value.better-supabase/serverexportstoCsv,csvColumnsandcsvResponse, which answers with a CSV attachment. ThesessionsSQL module addsbetter_supabase.last_sign_ins(uuid[]), callable by the service role only, andbetter-supabase/serverexportslastSignInsto read many users' last sign-in in one query. Runbetter-supabase sql syncto write the function.- With
sql.modules.grants.options.fromPolicies, a table the schema files create that has no permissive policy and noexposeentry is now service-only:sql syncrevokespublic,anonandauthenticatedon it and grantsservice_roleevery privilege. BS106 no longer asks for aselectgrant on those tables. New doctor check BS115 reports such tables that still hold grants on the live database, and BS116 reportssecurity definerfunctions in an exposed schema thatanonorauthenticatedcan execute while noexposeentry or policy uses them. - Doctor's BS304 now renders the SQL module files with the same layout as
sql sync(grants from policies, session policies, audited tables and the vector schema), so the two no longer disagree about stale files. BS313 skips projects that setsql.modules["rate-limit"].options.preRequesttofalse.
0.6.1 (2026-10-10)
-
The attachment scanner's
sink()andjobno longer fail for an attachment that was deleted before its scan. A missing attachment made the sink throw, so the outbox relay retried the whole batch until it dead-lettered it and every later event for that consumer waited behind it. The sink now skips that event and the job completes; download, transport andscanerrors still throw and retry. The object scanner does the same for an object deleted from storage (NoSuchKey), while a missing bucket still throws.scanner.scan()andobjects.scan()keep returning thenot_founderror. -
Audit entries record the request and correlation ids of the action that made them, so an app can group an event with the row changes of the same request.
createServergives every context a request id (the incomingx-request-idwhen valid, else a new UUID) and a correlation id (the incomingx-correlation-id, else the request id), exposes them asctx.requestIdandctx.correlationId, sends them as headers onctx.dbrequests and sets them as the transaction-localbetter_supabase.request_idandbetter_supabase.correlation_idsettings forctx.sql. TherequestIdsserver option renames the headers, ignores the incoming ones or turns the ids off, andContextOptionstakesrequestIdandcorrelationIdfor jobs.The audit module (version 6) reads the ids from those settings, then from the request headers (
requestIdHeaderandcorrelationIdHeaderoptions), keeps only ids of 1 to 128 safe characters throughbetter_supabase.request_id_or_null, and indexescorrelation_idon a managed log. The ids are metadata and never grant access. Runbetter-supabase sql syncand generate a migration to pick up the module change. -
The data exporter's
sink()andjobno longer fail for an export they can't claim, such as one cancelled, deleted or already finished before itsdata_export.requestedevent arrived. The sink threwDATA_EXPORT_NOT_FOUND, so the outbox relay retried the batch until it dead-lettered it and held every later event for that consumer behind it. The sink now skips that event and the job completes; a failing export still throws and retries.exporter.run()keeps returning thenot_founderror.
0.6.0 (2026-10-09)
-
The
agents,connectorsandai-tasksSQL modules store assistants, their MCP servers and scheduled prompts, andbetter-supabase/everuns eve agents on Supabase.createAgentsinbetter-supabase/blocks/agentsstores agents with instructions, model, tools, connectors and knowledge scopes, private until published.createConnectorsin/blocks/connectorsstores an organization's MCP servers, a grant per user behind acredential_ref, and tool lists an admin approves.createAiTasksin/blocks/ai-tasksruns prompts on a cron.better-supabase/ai-sdk/agentsaddscreateAgentRuntimeandmoderationMiddleware, and/ai-sdk/mcpaddsauthorizeConnector,connectToolsandconnectAll(@ai-sdk/mcpis an optional peer).better-supabase/eve(Node only,eveis an optional peer) addssupabaseAuth,credentialAuth,supabaseMemory,persistSessionsandrouteInbox.- Only the service role sets a task's
next_run_at, a task's chat must be its user's and its agent the user's own or published, anddrain()runs every claimed task before it reports the first error.
-
The
ai-chatandai-filesSQL modules store AI conversations and their files, andbetter-supabase/ai-sdkconnects them to the AI SDK (ai,@ai-sdk/reactand@ai-sdk/workfloware optional peers).createAiChatinbetter-supabase/blocks/ai-chatkeeps chats, a branching message tree, runs, tool approvals, feedback, share links, a model catalog per plan and moderation events;/blocks/ai-chat/reactaddsuseAiChats,useAiChatTree,useAiModelsanduseAiShare. Messages use a canonical format (aiMessageSchema,schemas/ai-message-v1.json,SPEC_PINS.aiMessage).createAiFilesinbetter-supabase/blocks/ai-filesstores uploads in two steps with policies that follow the file row, and versioned documents./ai-sdk/filesaddsaiFileDownload,saveGeneratedFilesandproviderFile.better-supabase/ai-sdkadds message converters, AI Gateway helpers and job handlers,createAssistantin/ai-sdk/chatserves a resumable chat route, anduseAssistantin/ai-sdk/reactisuseChatwired to it./ai-sdk/workflowruns answers as Workflow SDK workflows withdurableChatanddurableTurn, anduseDurableAssistantis the client half.createAiChat(...).runsreads run steps, andcreateHarnessSessionsreads harness sessions.- Harness sessions are read on the server only, the idle-stop job skips a sandbox whose session a turn holds, and the chat list hooks keep every loaded page on a live update and ignore stale responses.
-
The AI blocks share one run-state vocabulary, one sandbox table and one set of permission keys. The ai-chat, ai-tasks, ai-providers and memory modules move to version 2;
better-supabase sql upgradebrings a database installed from an earlier build forward.- Runs end
completed,failedorcancelledin ai-chat, ai-tasks and workflows.RunState,FinalRunStateandFINAL_RUN_STATESfrombetter-supabase/blocksname them. createAiChat(...).runshas the run lookups, and durable chats read them from the context'schats.- ai-chat owns
ai_sandboxes. Harness sessions keep their sandbox there, andcreateAiChat(...).sandboxes.idleStopJobstops chat and harness sandboxes with one claim. Set the idle time withsql.modules.ai-chat.options.sandboxIdleAfter. - ai-files, knowledge, memory, agents, connectors, ai-tasks and ai-providers check
ai.*permission keys. ai-chat keeps itsai_chat.*keys, and the default roles grant both. MemoryScopegainsproject, withprojectIdon namespaces and memory rows.- eve sessions release runs with the new statuses, and the jobs page documents jobs cron, workflow schedules and ai-tasks as three scheduling layers.
- The eve, memory, ai-files, workflow-builder and ai-providers blocks keep their row decoders in
rows.ts.
- Runs end
-
The
ai-cacheandai-providersSQL modules cache model responses and keep each organization's provider keys, andbetter-supabase/ai-sdkmeters model calls.createAiCacheinbetter-supabase/blocks/ai-cacheandcacheMiddlewarein/ai-sdk/cachereturn a stored response or stream for a repeated call, per tenant with a TTL.createAiProvidersinbetter-supabase/blocks/ai-providerskeeps provider keys ascredential_refrows with batch and sandbox registries.byokOptionsandtenantGatewayOptionsturn them into AI Gateway BYOK options,trackedSandboxrecords sandboxes, andaiBatchesin/ai-sdk/batchesruns provider batches from a job.meterTelemetryrecords each call's tokens and cost on the tenant's usage meters, andspendReconciliationcompares them with the AI Gateway spend report.
-
The API keys block (
better-supabase/blocks/api-keys) issues keys with a checksum, reports their state and authenticates REST routes.- Keys end in a CRC-32 checksum, so
verifyand secret scanners reject a mistyped key without a lookup (parseApiKey). - Keys report
state(active,grace,revoked,expired) andsuccessorId(ApiKeyState). withApiKey({ keys })is a pipeline entry that verifies the key and contributesctx.auth, andapiKeyClaimsandapiKeyResolvertake aclaimshape so the authorization provider reads the key's scopes.options.scopes: "catalog"limits scopes to the provider's permission keys, and the provider model refuses the*scope unless listed.
- Keys end in a CRC-32 checksum, so
-
Every SQL module audits its security-relevant actions. Run
better-supabase sql sync.ctx.recordtakes a requiredaudit: one of the shared categories inAUDIT_CATEGORIES(membership,access,security,configuration,billing,data,ai,integration), orfalsefor content and status events. With theauditmodule installed, each action writes one audit entry in the same transaction as its outbox event.- Settings, flags, billing customers, credentials, connectors, agents, AI provider keys, tool policies and approvals, chat shares, incoming webhooks, webhook secrets, announcements, published workflows, API keys, invitations, the waitlist, SSO domains and SCIM changes now write an audit entry and an outbox event. The access catalog's tables are audited through the row trigger under
access. organizations,organizations-suspensionandsupport-sessionsrecord through the same path: organization entries move fromorganizationtoconfigurationormembership, support entries fromsupporttosecurity, and revealed audit details fromaudittosecurity. An adopted log with a category check maps the names withsql.modules.audit.options.values.category.options.auditCategoryis deprecated and still overrides every category of its module.sql.modules.<name>.audit: falsekeeps a module's actions out of the log; they still reach the outbox.support.startedrecords the session's tenant, likesupport.ended.
-
audit.sink()files events under the categories the SQL modules use:account.*andsupport.*events getsecurity, and acategoryoption maps any other event type to one ofAUDIT_CATEGORIES. -
createAuditLog({ transport })inbetter-supabase/blocks/auditlists, reveals and exports the audit log as the caller, and entries record who acted, from where and on what. Runbetter-supabase sql upgrade.list(list_audit_events) filters by tenant, event type, actor, target, record, category, outcome, source and correlation id, withsearch, a cursor oroffset, andcount: true.reveal(entryId)returns restricted details and recordsaudit.revealed.export({ format: "ndjson" | "csv" | "ocsf" })streams the log (CSV takescolumns,preambleandformatRow),exportToStoragewrites it to a bucket, andrecord(event)callsaudit_event.- Entries record actor kind and label, tenant and target labels,
summary,request_id,correlation_idandscope. Actor and request details are honoured only from the service role and admin connections;audit_event_trustedserves an app'ssecurity definerfunctions andoptions.trustedRoles. better_supabase.audit(...)keeps a table's settings on its trigger, so schema files need no data rows, andbs_audit_forget_droppedclears registrations of dropped tables. Adopted logs map their own values withoptions.values,tenantLabelandmetadataColumns.sql addwrites a pgTAP file per audited table. Doctor BS315 reports tables without an audit trigger and BS322 registrations of missing tables.
-
Authorization libraries plug in through a versioned
AuthorizationProvider(API v1, frombetter-supabase/config) in theauthorizationconfig key, and the access module'sprovidermodel renders the provider's SQL templates.- Under the
providermodel, the provider'sidsWithFor,isPlatformForandcanAssignFortemplates letcan_user()andmember_can()answer for any user, the invitations module check the inviter again at accept, and the notifications module filter recipients by their read permission.sql.modules.access.functions.canAssignFordefinescan_assign_asunder the provider and custom models. sql.modules.access.disableddefaults to the provider'ssuspensionrows.disabled.tenantanddisabled.useralso take an active-row shape ({ table, id, disabledAt, status, active }), where a missing row counts as disabled.testAuthorizationProviderfrombetter-supabase/testingchecks a provider, andtemplateFunctionsfrombetter-supabase/sqllists the functions a template calls. Doctor BS214 compares a Storage or Realtime policy's scope with the provider'spermissions[].scopesand reports keys not markedsqlComplete: true.- The CLI rejects a provider with an unknown scope or a parent cycle, a tenant scope without an
idType(SCOPE_ID_TYPES), adecidingColumnsentry that isn'tschema.table.column, or anotherapiVersion(providerApiProblem).testAuthorizationProvideralso checks thatrequireslists every function a template calls and that the token hook claims don't overlap. - Without
canAssign, only the service role assigns roles under theprovidermodel. Doctor BS411 names each installed module missing a template it needs. functions.permissionsForfillsmember_permissionsandpermission_claims, andfunctions.canApprovewithapprovals.distinctApproverdecides AI tool approvals. Bucket and topic policies takesql: "provider"to use the provider's templates,createAgentRuntimetakes atoolApprovalhook, the claims config has amembershipspath (claimPaths), and theapiKeycaller carriescreatedAtandcreatedBy.- Breaking: every PermDock-specific setting and export is removed.
sql.modules.access.model: "permdock"becomes"provider",entitlements.permdockbecomesentitlements.memberships, bucket and topicpermdockpolicies becomeaccesspolicies withscopeandsqltemplates,permdockVerifierand thepermdockclaim option ofapiKeyResolverbecome the provider package's job and the neutralclaimoption, and doctor reads the provider instead ofpermdock.config.ts, the manifest and the catalog. The 0.5 to 0.6 guide has the old-to-new table.
- Under the
-
The billing block (
better-supabase/blocks/billing) runs a tenant's Stripe subscription over the Stripe Sync Engine and gives platform staff typed lists across tenants.changePlan,cancelAtPeriodEnd,invoices,paymentMethods,voidInvoice,customerDetails,updateCustomerand tax ids (StripeTaxId).options.planspoints at your plan catalog with pricevariants, andcheckoutmergesparamsdeeply.- Staff with
viewAllreadallSubscriptions,allInvoicesandallCustomers, also asbilling_platform_*SQL functions. StripeSourceaccepts a function that returns a client, andensureCustomeris idempotent per organization.
-
Blocks can be extended without forking them: add your own columns and type them, steer methods with hooks, wrap the transport and add methods.
options.extraColumnson theorganizationsandprofilesSQL modules adds your own columns to the managed table, copies them on writes and returns them from reads.list_my_organizationsreturns the attribute and extra columns in a newattributes jsonbcolumn.- A Standard Schema
fieldsoption oncreateOrganizationsandcreateProfilestypes those columns, parses them on read and turns a bad write into avalidationerror.createNotificationsparses storeddatawith its type's schema onget,listandpage, soitem.datanarrows onitem.type(NotificationOf); data the schema rejects fails with the hintNOTIFICATION_DATA_INVALID. - A
hooksoption on those blocks, and oncreateBlockskeyed by block name, runsbeforehooks that refuse a call with aDbErroror replace its arguments, andafterhooks that observe a copy of the result.withBlockHooksdoes the same for any block. - New SQL hooks:
before_organization_update,after_organization_update,before_profile_update,after_profile_updateandbefore_notification_send. wrapTransportruns versionedBlockTransportMiddlewarearound every block call, checked bytestBlockTransportMiddlewareinbetter-supabase/testing, andextendBlockadds methods and refuses to redefine one.
-
createBlocksin the newbetter-supabase/blockssubpath builds several blocks from one set of options, and the blocks share their helpers, option names and page shape.createBlocks({ transport, service, schema, credentials, events, audit }, factories)builds the blocks you pass and wires their siblings: the AI files block into knowledge,credentialsinto connectors, ai-providers and the workflow builder, notifications into ai-tasks (withaiTaskNotification), and block events into an audit sink. The subpath also exportsrpcTransport,sqlTransportand theBlockOptionsandCursorPageOptionstypes.audit.sink()returns anEventSinkthat records each CloudEvent in the audit log, with its type, subject, tenant and data.createServer({ audit })sendsaccount.suspended,account.unsuspended,account.deletedandaccount.sessions_endedfromsuspendAccount,deleteAccountandendSessions, and forwardssupport.denied; a failing sink never changes a result.- Block lists page with
{ limit, cursor }, which replacesize,beforeandafter. - Notifications, organizations, profiles and outgoing webhooks take
mappersinstead oferrorMappers. CredentialProvidergains an optionalset(ref, value, { subject, description }), which Vault implements and the workflow builder uses.credentialRouter(providers)serves several providers as one, andrevokeIfConfigured(provider, ref, { subject, tenant })revokes only when a provider is configured, can revoke the ref and the ref is in the tenant.Embedder,EveDocumentBackend,AiTaskRunner,GraphCompilerandBuilderStartertake an optionalapiVersion: 1; a block refuses another version.better-supabase/testingaddstestEmbedder,testEveDocumentBackend,testAiTaskRunner,testGraphCompilerandtestBuilderStarter.- The block row decoders moved into the core and every block uses the same ones;
better-supabase/blocks/knowledgeno longer exportsvectorLiteral.
-
The CLI finds its config from any package in a workspace, pg-delta is the default diff engine, and doctor reports each problem once.
better-supabase.config.*andsupabase/config.tomlare found in the working directory or a parent up to.git, andinitat a workspace root asks for the package or takes--package <dir>.initturns on[experimental.pgdelta]unless it is set tofalse, and doctor BS316 warns projects still on migra.better-supabase configprints the resolved config.- Doctor skips findings the performance advisor already reports, runs splinter with the
[api] schemas, and adds BS222 (int8decoded asnumber), BS317 and BS318 (statements pg-delta can't order) and BS319 (SQL that alters a reserved role).tables.<name>.serviceRole: truemarks a server-only table for BS106 and BS107.
-
better-supabase/vue,/solidand/sveltebind the browser client with the features ofbetter-supabase/react, and new hooks and query helpers cover forms, uploads and optimistic updates.useActionanduseActionFormcall abs.action()and trackpending,data,errorandfieldErrors.better-supabase/reactaddsusePresence,useSignIn,useSignOut,useDebouncedSearch,useSignedUrlanduseUpload, andupload()takesonProgress.better-supabase/queryaddsoptimisticwith rollback,{ maxPages }for infinite queries andescapeLike, andcreateQueriestakes ascope.better-supabase/tanstack-dbaddscollectionOptions.clearOnUserChangealso resets queries when the token changes tenant, role or assurance level.bindClientreturnsdispose(), andliveQueryrejoins a failed channel with backoff.
-
genwrites tighter types from CHECK constraints, documents tables in the generated validators and can run from a metadata document. Runbetter-supabase gen.- A nullable column a CHECK requires is typed not null, and
tables.<table>.insertOptionalmarks columns the database fills on insert.relations: { nullableUnderRls: true }types to-one relations to RLS tables as nullable. zod(),valibot()andjsonSchema()add titles, descriptions and examples from comments, and enforce bounds from simple CHECK constraints.- The generated module exports
WhereOf<"table">,OrderByOf<"table">andOrderTermOf<"table">, and the metadata module is about 40% smaller. gen --metadata <path|->generates from aGeneratorMetadatadocument for@supabase/typegen, anddoctor --metadatachecks it.- Generators declare
apiVersion: 1and receivemodel.gendeletes files it no longer writes, fails on name collisions, andgen --watchreloads the config and retries. - Breaking: colliding
_by_relations are named by every key column (customerByCustomerOrganization) instead of ending in_, and view copies are no longer relations. Keep an old name withtables.<table>.relations. - Breaking:
@supabase/postgrest-typegenis an optional peer; install it forgen,introspectanddoctorwithpnpm add -D @supabase/postgrest-typegen@0.4.0. - Breaking: a
GeneratorInputbuilt by hand needs amodel.
- A nullable column a CHECK requires is typed not null, and
-
The comments and attachments blocks (
better-supabase/blocks/comments,/blocks/attachments) store threads and files on any subject with per-subject permissions.options.subjects.<type>takespermissions: { read, create, moderate },cascade, andlabel,pathandreadableByfor notifications; a mentioned member is notified only when they may read the subject.- Comments keep a rich-text
document(mentionsOf,options.documentSchema), expandoptions.mentionGroups, and havecopy(),history()andcounts(). - Attachments take a
bucket,allowedMimeTypesandtenant: falseper subject, keepmetadata, and haveput(attachment, file)andread(id). A malware scan gate works for any bucket (object_clean(bucket, path),createObjectScanner,options.scanBuckets).
-
Errors map to typed messages and result libraries, plugins behave the same whoever wrote them, and each definition keeps its own state.
createErrorMessages(messages)needs a message for everyDbErrorkind.toBetterResultreturns better-result's ownResult<T, E>when that is the expected type, anddefineBetterResultErrorsmaps kinds toTaggedErrorclasses.P0002maps tonot_found.- Plugins get
enforce: "first", a mutationintent,scopes, and acontexthook perconnect(), so two definitions in one process no longer share a tenant. Hooks receive the caller'ssignal, anddb.$withoutPlugins({ keep })keeps named plugins. defineSupabase(schema, { temporal })takes theTemporalnamespace without patchingglobalThis, anddiagnostics: truelogs a record without tokens or row values for every query.- Breaking:
DbErrorgains the kindsquota_exceeded(429),max_affected(400) andunsupported(501). An exhaustiveswitchoverDbError["kind"]needs the new cases.
-
better-supabase/credentialsresolves third-party tokens from acredential_ref, andbetter-supabase/streamsstores resumable output for chats, workflows and agents.vaultCredentials()keeps secrets in Vault through thecredentialsmodule and verifies inbound signed requests.createServertakes acredentialsprovider asctx.credentials,subjectFor(ctx)gives the subject,better-supabase/vercel-connectaddsvercelConnectCredentials(), andtestCredentialProviderchecks other providers.- The
streamsmodule keeps ordered chunks with idempotent appends and a cancel flag, used bypostgresStreamStore,teeToStore,writeToStoreandresumeFromStore.better-supabase/streams/redisaddsredisStreamStore(redisis an optional peer), andtestStreamStorechecks other stores. - A tenant's
credential_refcarriestenant(tenantCredentialRef,credentialRefInTenant): connectors, AI providers, the workflow builder and MCP refuse a ref from another tenant withCREDENTIAL_REF_FOREIGN, Vault stores tenant secrets astenant/<tenant>/<secret>, andvercelConnectCredentialsrefuses a tenant ref for the app subject.
-
The data-lifecycle block (
better-supabase/blocks/data-lifecycle) exports, anonymizes and purges a tenant's or a user's data across every module table.- Modules declare their tables, so exports and purges cover every installed module, and
options.autoTablesadds a schema's tenant tables. Exports leave out keys, token hashes and secrets. - The purge retries referenced tables, stops with
ORGANIZATION_PURGE_BLOCKEDwhen stuck, and deletes the tenant row last.createOrganizationPurger({ buckets })takes path prefixes (PurgeBucket). options.anonymizerules anonymize rows after a retention period (anonymizeDue()), andcreateDataExportertakesformat: "csv".
- Modules declare their tables, so exports and purges cover every installed module, and
-
Block events follow one contract. Run
better-supabase sql syncandbetter-supabase codemod 0.6.- Every type is
<entity>.<past_tense_verb>. Renamed:ai_chat.message.completedtoai_chat_message.completed,inbox.conversation.*toinbox_conversation.*,inbox.message.receivedtoinbox_message.received,incoming_webhook.rotatedtoincoming_webhook.token_rotated,workflow.alerttoworkflow_alert.triggered,workflow.run.*toworkflow_run.*anddata_export.readytodata_export.completed. BLOCK_EVENT_RENAMESfrombetter-supabase/eventsmaps theorg.*types toorganization.*, and the 0.6 codemod rewrites string literals that name a renamed type.BlockEventMaptypes every event a SQL module records. Each module declares its events inNAMES.events, andctx.recordthrows for an undeclared type, a subject that is not a kebab-case plural, a missing payload key or a retried event without an idempotency key.- Support events carry a camelCase payload with
organizationIdundersupport-sessions/<id>. Push, waitlist and audit subjects arepush-devices/,waitlist-entries/andaudit-entries/. SCIM events namescimUserIdorscimGroupId. notification.created,webhook.disabledand the workflow events carryorganizationId.notification.created,webhook.disabled,attachment.scanned,inbox_message.received,data_export.completed,data_export.failedandorganization.purgedhave idempotency keys.notifications.sink({ map })turns outbox events into notifications, keyed by the event id.
- Every type is
-
Adapters for more server frameworks, typed structurally, with the guards and actions of the Next.js adapter. They replace the
@supabase/serverframework adapters, which upstream removes on 2026-12-01.- New subpaths:
better-supabase/tanstack-start,/sveltekit,/react-router,/h3,/h3/v1,/elysia,/node(toExpress,toFastify,toKoa),/nestjs(@nestjs/commonis an optional peer),/astro,/nuxtand/solid-start.toHono,toEdge,toOrpcandtoExpobridge the existing adapters. - Each factory puts
db,bs,auth,tenantandsessionon the request, withbs.require()andbs.action(); every guard takesrolesandroleClaim. The edge getsbs.routes({ "GET /customers/:id": handler })with typedctx.params(RouteParams), oRPC getsbs.authed(), andcreateMcptakesrequiredRoles. handle(),extendServer,flushEventsandresolveTokenbuild an adapter on the shared request path, checked bytestAdapter.withServerTiming(),withDbStats()andtagCachecover timing headers, database budgets and tag caches.- Breaking:
createEdge'scorsoption runswithCorsfrom@supabase/middleware/cors. A preflight needsAccess-Control-Request-Method(otherOPTIONSrequests reach the handler), and an allow-list addsVary: Origin.corsConfig(options)returns the config.
- New subpaths:
-
The
inboxSQL module andbetter-supabase/blocks/inboxadd a shared support inbox per organization, andbetter-supabase/chat-sdkruns Chat SDK bots on it (chat>=4.41 <5is an optional peer).- The inbox stores contacts, conversations with assignment, teams, snoozing and bot handoff, messages and notes, read receipts, deliveries and attachments, with
purgeContactfor data subject requests.useInbox,useConversationanduseInboxWidgetin/blocks/inbox/reactstay current over private Realtime topics. createSupabaseStateis aStateAdapteron thechat-sdk-statemodule,inboxAdapteranswers in the in-app widget, andwebhook,inboundHandler,deliver,maintainandcreateChatInstallationsrecord Slack, WhatsApp, Messenger and SMS conversations.testChatStatechecks anyStateAdapter.
- The inbox stores contacts, conversations with assignment, teams, snoozing and bot handoff, messages and notes, read receipts, deliveries and attachments, with
-
Invitations can be edited, answered from an in-app inbox and sent for platform roles under the
providermodel. Runbetter-supabase sql upgrade.update_invitation(organizations.updateInvitation) changes an open invitation and emitsinvitation.updated; it refuses an expired one, so callresend_invitationfirst.my_invitations()lists the signed-in user's open invitations, andacceptInvitationByIdanddeclineInvitationByIdanswer them. Invitations carryextrafrom theinvitation_preview_extrahook,createdAt,organizationand aninviter.options.platformRolesnames the platform role table, withthrough,canAssignandcanAssignForchecked at invite and accept.through.whereis required when its table is alsoroleThrough's, andbs_role_scoperefuses other roles on direct writes (PLATFORM_ROLE_SCOPE).- Breaking: accepting or updating an expired invitation fails with the hint
INVITATION_EXPIREDinstead ofINVITATION_INVALID, which now means unknown, accepted, declined or revoked. - Breaking:
Invitationhas a requiredinviterfield (nullwithout the profiles module), and theinvitation_preview_extrahook also runs for invite, resend, update andmy_invitations.
-
Jobs run as the user who enqueued them and report queue health, and
better-supabase/blocks/jobsadds leases and rate limits. Runbetter-supabase sql upgrade.bs.forContext(job.context)returns repositories as the context's user and tenant, so RLS applies in the handler. It keeps a read-only support session read-only, andclaimsFor(userId, context)rebuilds hook claims.jobs.stats(),listDead()andretryDead()serve admin pages, andenqueuetakesdedupe: "waiting".- Under
scheduler: "drain", schedules record a tenant (listSchedules,unscheduleAll),ensureScheduleskeeps a named set in step,drainRoutetakesmonitorhooks, anddevDraindrains locally. withLease(sql, key, fn)holds one holder per key.hit_rate_limit(scope, key)andcreateRateLimit().check()limit any key, andrateLimited(decision)answers 429 withRetry-After.- Breaking:
begin_idempotentreturns aholder, andcomplete_idempotentandrelease_idempotent(createIdempotency().completeandrelease) take it and return false after another caller took an expired key over.
-
Kits are now blocks, and every feature module lives under
better-supabase/blocks/<name>. There are no aliases; the 0.5 to 0.6 guide lists every rename.- Breaking: subpaths move.
better-supabase/orgsisbetter-supabase/blocks/organizations, andbetter-supabase/jobs,/notificationsand/webhooksarebetter-supabase/blocks/jobs,/blocks/notificationsand/blocks/webhooks.createOutboxandoutboxCloudEventmove tobetter-supabase/blocks/outbox, andpurgeAuditLogtobetter-supabase/blocks/audit.hasEntitlement,EntitlementKey,entitlementMembersandENTITLEMENTS_UPDATEDmove tobetter-supabase/blocks/entitlements(out ofserver,next,ssr,reactandjobs), anduseNotificationsmoves frombetter-supabase/reacttobetter-supabase/blocks/notifications/react. - Breaking:
sql.kitand thekitskey merge intosql.modules, an object keyed by module name whose values are the module settings (a list of names still works). - Breaking:
Kit*names for features areBlock*(BlockEvent,onBlockEvent,forwardBlockEvents), andKit*names for SQL modules areModule*(ModulesConfig,ModuleConfig,renderModules,modulePermissionKeys).orgis spelled out:createOrganizations,Organizations,organizationLogoBucket, and theorganization.*event types replaceorg.*. - Breaking: in SQL,
member_org_ids,has_org_roleandorg_member_rolearemember_organization_ids,has_organization_roleandorganization_member_role, the organization functions take anorganizationparameter,better_supabase.kit_modulesisbetter_supabase.modules, and module files carry-- @bs-moduleand-- @bs-module-datamarkers. Runbetter-supabase sql sync, the schema diff andbetter-supabase sql datato move a database over.
list,storage,realtimeandeventskeep their subpaths. The list, storage and realtime pages move to/docs/platform, and the events page to/docs/standards/events. - Breaking: subpaths move.
-
The
knowledgeandmemorySQL modules give agents retrieval and long-term memory; both requirevector-search.createKnowledgeinbetter-supabase/blocks/knowledgestores documents scoped to an organization, agent, project, chat or user, chunks them with embeddings and atsvector, and searches with reciprocal rank fusion. Withjobsinstalled new documents are enqueued for embedding;ingest.filereads anai-filesupload.createMemoryinbetter-supabase/blocks/memorykeeps core memory files under/memories, archival facts and one embedding per chat message, plus versionedmemory.documents.better-supabase/ai-sdk/embeddingsaddsembedWith,supabaseEmbed,rerankWith,searchToolandtoSourceParts, and/ai-sdk/memoryaddsmemoryTool,anthropicMemory,recallTool,withMemoryand theextractMemoriesjob handler.- An item rewritten while it is being embedded stays pending,
set_memory_embeddingswrites a batch, bad vectors fail withEMBEDDING_INVALID, and knowledgedraintries each documentattemptstimes (3) before marking it failed.
-
better-supabase/mcp/sdkserves MCP servers built on the official SDK (@modelcontextprotocol/server2.3 or later, an optional peer), andcreateMcpworks on hosted Edge Functions.createMcpAuth(betterSupabase, { resource })verifies Supabase tokens locally as anOAuthTokenVerifier, serves the RFC 9728 metadata and answers 401 and 403 challenges.withBetterSupabaseMcp(server, auth)gives every tool callbackdb,authandbs.- On Edge Functions the
resourcecomes from the function slug. Both servers answer CORS preflights (allowedOrigins) and takerequiredRolesandwaitUntil.
-
Expo and React Native get a server adapter, a native client, local SQLite executors and push notifications.
better-supabase/expo:createExpo(betterSupabase)gives Expo Router loaders, API routes and+middleware.tsthe verified caller;better-supabase init expowrites it.better-supabase/client/native:createNativeClient(betterSupabase, supabase)binds repositories without@supabase/ssr,secureStorageandlargeSecureStoragekeep sessions in the keychain, andautoRefreshOnForeground,syncQueryWithApp,persistQueryCache,uploadFromUriandhandleAuthDeepLinkcover the app lifecycle.better-supabase/react/nativeaddsuseOAuth,useAuthDeepLinks,useProtectedRouteandAuthGate.better-supabase/powersync:powersyncExecutor(db)runs the same repositories on PowerSync's SQLite,createUploadConnectorreplays queued changes andsyncWithAuthclears data on a user change;/powersync/reactaddsuseWatch,useSyncStatusanduseConflicts.better-supabase/expo-sqliteaddsexpoSqliteExecutor(db).- The
pushmodule andbetter-supabase/blocks/pushstore device tokens and send through the Expo Push API (registerDevice,expoPush,expoPushChannel).
-
The Next.js adapter authorizes actions and Server Components, signs out ended sessions and scopes cache tags to a tenant.
bs.action()andbs.route()takerequireTenantandauthorize(session, input), andbs.require(options)refuses a Server Component caller withunauthorized(),forbidden()ornotFound().bs.proxy(request, { endedSession })asks Auth whether the session still exists and clears the cookies when it doesn't, andexpiredPrefetch: "render"renders a prefetch with an expired token signed out.bs.cacheTag,bs.cacheTagsandbs.cachedtake{ tenant }, so a mutation in one tenant no longer revalidates other tenants' reads, andbs.context({ tenant })takes the tenant from route params.- Mutations outside a Server Action expire tags with
{ expire: 0 }, so a read after a write in a route handler is fresh (nextCache({ revalidate })keeps"max"). useSessionChangerefreshes the session before an organization switch re-renders, andtenantOf(session)reads the active tenant.- Breaking: the
nextpeer range is>=16.3 <17, becausecreateNextawaitsio(). Upgrade Next.js first.
-
The notifications block reads more of the inbox, hydrates a page in one call and reports who received a send. Run
better-supabase sql upgrade; a custom-mode module implements the new signatures.get(id),page({ offset }),markUnread,subscriptions()andpreferences()are new, andlistfilters by subject type, search and read, resolved or dismissed state.hydrate(items)loads whatrenderneeds for a page, andinclude: ["actor"]adds each actor's profile.sendtakeswatchers: falseandexclude, andsubscribe({ ifAbsent: true })auto-follows without overriding a member's choice.- Breaking:
markRead,markUnread,dismissandresolvereturn{ count, items }instead of a number, and their SQL functions returnjsonb. - Breaking:
send()returns{ id, recipients }instead of the id, andonSentandnotification.createdget the recipients. It callssend_notification(jsonb);notify(jsonb)still returns the id.
-
Organizations can suspend members, route deletion through data-lifecycle and give platform staff admin rights, and profiles store an avatar path. Run
better-supabase sql upgrade.suspend_memberandresume_member(organizations.suspendMember,resumeMember) keep a member's role but drop its permissions through the memberships table'sdisabled_at; they refuse the caller, the last owner and higher members.transfer_ownershiprefuses suspended or disabled new owners.options.deleteMode: "lifecycle"sends deletion through data-lifecycle's grace period, and"none"writes no delete function.permissions.updatePlatform,deletePlatform,updateRolePlatformandremoveMemberPlatformlet platform staff manage any organization.options.assignmentGuard: "external"drops the module's role guard, which now checks only client writes.- Profiles get
avatarPath,usernameFromtakes several keys with a separator, andreadPolicy: { platform }lets staff read every profile.reserved-slugstakesslugs,minLengthandmaxLength.
-
The outbox (
better-supabase/blocks/outbox) hands consumers the raw rows and moves failing events aside. Runbetter-supabase sql upgrade.outbox.consume(consumer, handler)passesOutboxEventrows (OutboxHandler), andrelayRouteaccepts such a handler.- A failing consumer backs off (
maxBackoff), and aftermaxAttemptsfailures an event moves tooutbox.deadLetters(consumer).purgetakes{ ignoreIdle }, andcreateOutboxtakes aBlockTransport.
-
Realtime topics support presence, write their own policies and build triggers from parent rows.
defineTopictakespresence, and subscriptions gettrack,untrack,members()andonPresence.realtime.policies: { from, output }writes every topic'srealtime.messagespolicies onsql sync, with a--checkdrift test.topic.triggerSql()takes lookups through parent rows, aneventname and a custompayload(TriggerLookup).realtime.usersgives live queries on a table a per-user topic, anduseBroadcastworks with a plain supabase-jsclient.
-
Breaking: 0.6 removes the deprecated aliases 0.5 kept for one minor. A support token whose
acthassession_idbut nokindis refused asinvalid-chain. The audit module (version 5) drops the read-onlybetter_supabase.audit_logview; readbetter_supabase.audit_events.maxUrlLengthis gone fromdefineSupabaseandpostgrestExecutor(useurlLengthLimit),scopesfrom the MCP server options (useadvertisedScopes), andcreateInboxand theInbox*types frombetter-supabase/blocks/jobs(usecreateWebhookInboxandWebhookInbox*).better-supabase codemod 0.6now renames theKitandOrgexports andmaxUrlLength, and lists imports from the moved subpaths for review. -
Repositories read with more filters and sorts, split long
inlists instead of failing, and count pages cheaply by default.findOnly({ where })returns the one matching row,nullfor none andmultiple_rows(409) for more.wheretakes jsonpathfilters (JsonPathOps),matchandimatchregular expressions, and json containment with arrays. Reads longer thanurlLengthLimit(6000) split along their longestinlist.orderBysorts by a to-one relation's column,aggregate()sorts groups by_countor a measure (AggregateOrderBy), andpaginate({ offset, limit })returns an offset window.defineReadSettakesauth.uid.- Breaking: list queries count with
count: "planned"by default; passcount: "exact"for the old behaviour. - Breaking: cursors record the table and sort, so cursors made before 0.6 and arrays from
encodeCursor()fail withInvalid cursor. Start again withafter: null.
-
Writes take conditions, return rows from bulk calls and cap how many rows they change.
update(key, patch, { where })returnsnot_foundfor a row that doesn't match,expecttakeswhereoperators, andupdateManyanddeleteManytakereturning: true.updateManyanddeleteManytakemaxAffected; a write matching more rows fails withmax_affectedand changes nothing. It needs PostgREST 13 (setpostgrestVersion: "12.2"on older servers), and the rules plugin'sstrict()preset requires it.- Every call takes
timeoutandretry,createManyandupsertManytakedefaultToNull, and mutations takecount: "planned". - Breaking:
deleteManyandupdateManyrefuse awherethat filters nothing. PassallowAll: truetoupdateManyto update every row. - Breaking: an update whose
datasets no columns returnsinvalid_requestinstead ofnot_found. - Breaking: a
*inlikeandilikepatterns is a literal character; use%.
-
db.$rpcis typed per overload, acceptsnullarguments and runs over the Postgres executor. Runbetter-supabase gen, thenbetter-supabase codemod 0.6, which lists every$rpccall to review.genkeeps every overload of a function as a union inFunctions, and$rpcpicks the overload by the argument names the call passes. Arguments are typedT | null.postgresExecutorimplementsrpc(), so requests over a direct connection (an API key, a job) call functions too.rpcTransportand the jobs block'spgmq_publicbackend accept a typedSupabaseClient<Database>without a cast.- Breaking:
gentypes function results as nullable: scalars,setofscalar elements, a single row and eachreturns tablecolumn are| null. Setfunctions.<name>.notNullinbetter-supabase.config.tstotrueor to the columns that are never null. - Breaking:
$rpcreturns rows of a table andreturns tablerecords in the configured casing with the configured codecs, like repository reads, typed as the model row. Delete hand-written key mapping around those results, or pass{ raw: true }for what PostgREST sent.
-
New SaaS blocks, each an SQL module with a subpath:
better-supabase/blocks/api-keys,/audit,/settings,/usage,/billing,/flags,/comments,/attachments,/data-lifecycle,/sso,/onboarding,/waitlist,/announcementsand/push. Add one withbetter-supabase sql add <name>;stripeis an optional peer that only billing and usage load.- SSO serves SCIM 2.0, flags evaluate rollouts in SQL and through an OpenFeature-shaped provider, and
SPEC_PINSgainsocsf,openfeatureandscim. Under theprovidermodel, SSO and waitlist roles go throughroleThroughand needcan_assign(SSO_ROLE_FORBIDDEN,WAITLIST_ROLE_FORBIDDEN), andjoin_waitlistalways answersstatus: "waiting"to clients. - Blocks take
ctx.postgresfrom@supabase/server,withBlock(key, create)puts a block on the context, and every block takestemporaland aproblemoption (ProblemFormat) for error bodies. - New event types cover organization domains and deletion,
billing.*, comments, attachments, data exports andwaitlist.approved. - Breaking: the server's
auth.kindgains"apiKey", so an exhaustiveswitchover it needs the new case.
- SSO serves SCIM 2.0, flags evaluate rollouts in SQL and through an OpenFeature-shaped provider, and
-
withBetterSupabase(server, options)frombetter-supabase/serveris one@supabase/middlewareentry that resolves the caller and contributes the request's database handles, and the server gains session and account helpers.better-supabasedepends on@supabase/server^1.9.1.- The entry reads a bearer token, then the session cookie, enforces
allow,aalandscopes, and contributesbs,db,sql,tenantand the keyswithSupabasewrites.server.context(request)runs the same entries once per request.createServer(betterSupabase, { db: { timeout, retry, urlLengthLimit } })tunes its requests. - Session cookies support the
@supabase/ssr0.12tokens-onlyencoding (encode: "tokens-only", doctor BS412 for mismatches), andcookieScopesandclearSessionAtScopesexpire cookies an earlier deploy set. sessionStatusandclearSessionCookiesrun the ended-session check in any proxy.endSessions(sql, userId)andsuspendAccount(admin, sql, userId, { suspended })end sessions and ban a user, anddeleteAccountis exported on its own and returns the database's error, such asORGANIZATION_OWNER_REQUIRED, with thesqloption.- An early refresh that hits a network failure keeps the user until the token expires, and the
otelplugin recordsdb.$rpccalls as spans. - Breaking: the leaf entry
withBetterSupabase(betterSupabase)that ran afterwithSupabaseis renamedwithBetterDb(betterSupabase). Replace it, or dropwithSupabaseand use the newwithBetterSupabase(server).
- The entry reads a bearer token, then the session cookie, enforces
-
The settings block has a
platformscope for product-wide settings, and feature flags can be managed from an admin page.defineSettings({ platform })addsclient.platform; each key names the permission that changes it and who reads it, and only listed keys can be written.createFlagAdmin({ transport })lists, saves and deletes flags and sets overrides for staff withflags.manage.tenant_ids_with_flag(key)is the policy form offlag_enabled,createFlagsProviderworks over the Data API, andflagContextreads amembershipsclaim.
-
SQL modules call each other through shared helpers and declare the modules they work with, and fewer modules pull in others they only use when present. Run
better-supabase sql sync.ModuleContextgainsrecord,notify,enqueue,entitlements,broadcast,canandstaff. Each returns a statement or expression that is valid without the other module, so a module installs alone and calls the other one once it is installed.SqlModule.integrateslists the optional modules a module works with.ctx.installedandctx.ofthrow for a module it neither requires nor lists,better-supabase sql listprints "works with", and the blocks overview has the full matrix.inboxno longer requiresjobsorstreams: withoutjobsit queues no bot or delivery jobs.workflowsno longer requiresjobs, andai-cacheno longer requirestenant.webhooks-inrequiresupdated-at, which its trigger uses.support.endedrecords the session's tenant in the audit log and the outbox, likesupport.started.sql.modules.jobs.schemais rejected: the jobs module always installs inbetter_supabase, so a schema only pointed the modules that call it at missing functions. Functions of theaccessmodule are always called inbetter_supabase, whateversql.modules.access.schemasets for its tables.
-
SQL modules can be called over the Data API without exposing their schema, and land their extensions and event triggers in migrations. Run
better-supabase sql syncand create a migration for the new function bodies.sql.modules.<module>.apiwritessecurity invokerentry points for the functions apps call into a schema, andrpcTransport(supabase, { schema: "api" })calls them there. Doctor BS312 points at the option.sql add,syncandupgradewrite the modules' extensions into a<stamp>_better_supabase_extensions.sqlmigration, and data files repeat extensions and event triggers so pg-delta plans need no hand edits (doctor BS321, BS323).- The
ensure-rlsmodule enables row level security on every new table outside the Supabase-managed schemas. - A write that breaks a
jsonb-schemasschema fails with avalidationerror whoseissuesname the column. sql.modules.sessions.options.policieswrites a restrictivebs_session_activepolicy on every table, and doctor BS320 reports tables without one.- The
grantsmodule keys functions by signature, takes column privileges such as"update(title, body)", and derives grants from permissive policies withoptions.fromPolicies. - Policies check tenant permissions once per statement, module functions pass
supabase db lint, and module actions follow a renamed sibling key. - Breaking:
grantswrites the complete privilege set of each entry inexpose, so a table loses privileges it doesn't list, includingtruncate,referencesandtrigger, on the next sync.
-
defineBucketcovers what Storage added in supabase-js 2.117, takes several path layouts and reports bad paths as aResult.versioningandlifecycle, applied withbucket.apply(client)and checked by doctor BS302. Connected buckets listversions, take aversionId, and haveremoveVersions,purgeCache,copyandmove.defineVectorBucketanddefineAnalyticsBucketdeclare the new bucket kinds.path: [current, older]accepts several templates, and{...rest}matches any depth.defineBuckets({ ... })registers definitions by id for rows that store a bucket id (byId,resolve,connectStored).- Policies from
.sql()use the name index,sweep()removes only objects matching everywithinvalue, andreplace()checkspreviousagainst the tenant. - Breaking: a bucket definition's
path(values)returns aResult<StoragePath>instead of throwing. - Breaking: a connected bucket's
publicUrl()returns aResult<string>.better-supabase codemod 0.6lists both kinds of call.
-
The tenant module keeps references inside one tenant and reads membership roles through a roles table.
sql.modules.tenant.options.sameTenantentries add a trigger that fails a write referencing another tenant's row withTENANT_MISMATCH, also throughmatchandthroughcolumns.options.roleThrough: { table, id, column, where?, tenant? }reads role names when memberships store role ids, taken from the provider'sroleSourcesunder theprovidermodel. Abs_role_scopetrigger refuses roles outsidewhereon direct writes (MEMBERSHIP_ROLE_SCOPE), and doctor BS324 reports a shared roles table withoutwhere.
-
better-supabase/testingchecks Next.js navigations for instant renders and database budgets, and its kits check adapters and executors.expectInstant(page, options)runs a navigation inside@next/playwright'sinstant()(an optional peer) and checks what shows while the lock holds.expectDbBudget(response, { maxCalls })checks thewithDbStats()header and waitssettleMsfor late responses.testAdapter,testExecutorandtestPlugincheck custom adapters, executors and plugins against the first-party contracts.
-
The usage block (
better-supabase/blocks/usage) meters fractional quantities against quotas that follow the plan or billing cycle, and entitlements read from any plan catalog.- Quantities and limits are
numeric,recordManyandconsumeManyrecord several meters all or none, and anulllimit is unlimited. options.metersis a meter catalog in the config or a table, read byusage.meters(),overview(organizationId)andcurrent().options.historykeeps each record, read byhistoryandbreakdown. Reading needsusage.readand recordingusage.record.- The
billingperiod followsusage_billing_period(tenant), andreportUsageToStripe({ overage: true })sends only usage above the quota. entitlements.sourcereads features from your plan tables or"custom", with values throughentitlement_value, andentitlements.claimsets the claim's shape (EntitlementClaimOptions).
- Quantities and limits are
-
Vector search supports hybrid ranking, filters and scores. Run
better-supabase sql sync.vectorSearchentries taketype: "halfvec",hybrid,boost,prefilter,predicateandorder.db.$searchtakesfilter,textandscore: true; on ahybridentrytextalone ranks by full text when the embedding call fails.options.schemasets pgvector's schema, whichsql syncotherwise reads from yourcreate extensionstatement.
-
Breaking:
createInboxinbetter-supabase/blocks/jobsis nowcreateWebhookInbox, and its types areWebhookInbox*; the old names are removed.better-supabase/blocks/inboxhas a differentcreateInboxfor the conversation inbox. Runbetter-supabase sql upgrade.- Messages record a tenant and dedupe per source and tenant, and
message.checkpoint(fields)saves progress a retry resumes from. store(event)stores an event an SDK already verified, and a source without secrets is store-only.- Sources take
maxAttempts,processtakesbudgetMsand renews leases, and bodies overmaxBodyBytes(1 MiB) get a 413.
- Messages record a tenant and dedupe per source and tenant, and
-
The
webhooks-inmodule andcreateIncomingWebhooksinbetter-supabase/blocks/webhooksgive each tenant trigger URLs with hashed tokens, andcreateSafeFetchcalls URLs that users supply.- Endpoints verify Standard Webhooks, HMAC-SHA256 or a shared secret, with size and rate limits, keep secrets in Vault, and hand deliveries to the webhook inbox.
update,rotateandrotateSecret(id, { grace })change them, andoptions.subjectsattaches them to a record. verifyWebhookand incoming endpoints accept Svix'ssvix-*headers.createSafeFetch(options)allows public HTTPS URLs only, checks every redirect, drops credentials on a redirect to another origin, and throwsUnsafeUrlErrorfor a refused URL andUrlCheckErrorfor a failed check such as DNS.
- Endpoints verify Standard Webhooks, HMAC-SHA256 or a shared secret, with size and rate limits, keep secrets in Vault, and hand deliveries to the webhook inbox.
-
The
workflowsandworkflow-builderSQL modules record durable workflow runs and store graph workflows per tenant.better-supabase/blocks/workflowsrecords the runs of any engine inworkflow_runswith cron schedules, semaphores and admission control, anduseWorkflowRunsanduseWorkflowRunin/blocks/workflows/reactread them.better-supabase/workflow-sdk/worldis a Workflow SDK World on Supabase (Node only,createWorld(), theworkflow-sdk-worldmodule), andbetter-supabase/workflow-sdkaddsstartFor,workflowStarter,startOnEvent,authorizeHook,hookMetadataandprotectWebHandler.better-supabase/blocks/workflow-builderstores definitions, checked versions, triggers, credentials bycredential_ref, a step library, node status and alerts, withuseWorkflowBuilderanduseWorkflowCanvasRun.better-supabase/workflow-sdk/builderaddscompileGraph,graphStarterandnodeRunReporter. The new permissions areworkflow.editandworkflow.publish.- Only the service role stores a version's compiled form (
createBuilderwrites it throughservice), andgraphStartercompiles from the graph on every start. Node ids are 1 to 100 letters, digits,_or-. - The World refuses unsigned poll deliveries outside development and test, fails closed on a Vault read error, aborts a delivery after
deliveryTimeout(300 s), and mirrors a run's tenant only when its actor holdsworkflow.runthere.
-
verify_api_keyrefuses a personal key while its user is banned in Supabase Auth (banned_untilin the future) or soft-deleted. Before, only the configured disabled column stopped a personal key, so a banned user's key kept working after their sessions ended. -
The
data-lifecyclemodule (version 5) exports and purges more module tables, leaves credentials and audit snapshots out of exports, and the organization purger revokes credential refs before the purge. Runbetter-supabase sql syncto get the new version.- Platform role assignments, outbox events, webhook secrets (purged, never exported), inbox tables, flag overrides and SCIM users per user, waitlist redemptions, AI provider keys, connector servers and grants, and workflow credentials join exports and purges.
- Exports leave out every
credential_refcolumn, and audit events loseold_record,new_recordand the impersonation columns. createOrganizationPurger({ credentials })revokes thecredential_refof each row the purge deletes through theCredentialProvider(connector grants for their user), only when the ref carries the organization. The rest come back inpurge.credentials.unrevokedwith a reason (foreign,no_providerornot_revocable), and a failed revoke stops the purge before it deletes anything.- The purger now checks that the deletion is due (
organization_credential_refs) before it cancels billing or clears Storage.
0.5.1 (2026-10-04)
-
Breaking (types):
SessionActoris a union onkind:oauth-client(withchain),support(withsessionId,readOnlyandreason) andimpersonation(withreason), andImpersonatorgainskind. An exhaustiveswitchonsession.actor.kindneeds the two new cases.Support sessions and impersonated sessions mark their
actclaim:supportClaimswritesact.kind: "support"andactingAswritesact.kind: "impersonation".actorOfreads them as their own actor kinds instead of OAuth clients,session.impersonatorfollowsactorOf, so an OAuth client or agent chain is no longer shown as an impersonator, andsession.delegationand thescopesguard apply tooauth-clientactors only. Anactwith anotherkind, or a support level withoutsession_id, makes the session invalid (reason: 'actor'). A support token minted by 0.5.0 (session_idwithoutkind) still counts as a support session until 0.6.supabaseClaimFixturesfrombetter-supabase/testingholds a support session (writable and read-only), an impersonated session, an OAuth client and an agent chain, each valid against PermDock'ssupabase-claims-v1.json. -
Breaking:
allow: ['anon']no longer admits users fromsignInAnonymously(). Only'anonymous'admits anonymous sign-ins, and'anon'means a caller without a session.['anonymous']alone now admits anonymous sign-ins and refuses other users; before, it admitted nobody. A route that serves guests next to signed-in users lists['user', 'anonymous'], and a public route that also serves guests['user', 'anonymous', 'anon']. With PermDock, pair the defaultallowwithrls: { anonymousSignIns: 'deny' }inpermdock.config.ts. -
The entitlements module in PermDock mode reads
entitlement_members()from the manifest'srls.membershipsentries for its scope, the tables PermDock'smember_<scope>_ids_forreads, and falls back to the hook's membership sources only for a manifest withoutrls.memberships. Doctor (BS408) warns whenrls.membershipsmaps no table to the scope, and notes the fallback. -
The
permdockaccess model reads PermDock's manifest itself.better-supabase sql addtakes the helpers' schema fromrls.schema, the scope from the rootrls.scopesentry (the one withoutwithin) and the id type from that scope'stype, whateverentitlements.permdocksays, so a manifest withrls.schema: "authz"and a root scopetenantgetsauthz.permitted_tenant_ids. It stops instead of guessing when the manifest is missing, has no single root scope, or disagrees withkits.access.permdock.scope,kits.access.permdock.schemaorkits.access.idType; 0.5.0 fell back topermdock.permitted_organization_idsanduuid. Code that renders the kit without the CLI (renderKit,moduleBody) now sets bothkits.access.permdock.schemaandkits.access.permdock.scope. Doctor reports the same problems, and helpers the manifest or the database lacks, as the new BS411 error. -
Under the
permdockaccess model,can_user()andmember_can()raise SQLSTATE0A000(hintACCESS_CALLER_ONLY) for anyone but the caller instead of returningnull, because PermDock's helpers readauth.uid(). The invitations module no longer re-checks the inviter's permission when an invitation is accepted, and the notifications module no longer filters recipients by their read permission, under that model; in 0.5.0 the re-check passed silently on thenullanswer, and the filter dropped every recipient but the sender. Check both in the app when they matter. Runbetter-supabase sql addto rewrite the installed files. -
The access kit docs, the
canAssignJSDoc and thecan_assign()SQL comment recommend PermDock's assignment rule for thepermdockmodel:canAssign: "permdock.permdock_can_assign({role}, {tenant}::text)", with the manifest'srls.schema. This is the assignment rule the 0.5.0 note "thepermdockandcustomaccess models need an assignment rule" refers to; see the access kit. Without it only the service role assigns roles, since PermDock projects don't install thetenantmodule, and doctor (BS411) warns. -
Under the
permdockaccess model,better-supabase sql addand doctor (BS411) check every permission key the kit modules check againstpermissions.catalog.json, platform keys forpermdock_hasincluded. A key must berowConditions: false, because PermDock's helpers check role and scope only; a key with row conditions, without the flag or missing from the catalog stopssql add.kitPermissionKeys(kits, names)frombetter-supabase/sqllists the keys with their module, action and scope, andkitFilePaths(names, layout)lists the files a set of modules writes without rendering them, sosql listworks while the access settings are incomplete. -
better-supabase genuses@supabase/postgrest-typegen0.4.0.database.types.tsgains aComputedFieldskey on every table and view: the names of its computed fields, ornever. postgrest-js reads it to leave computed fields out ofselect('*'), and row-typed function arguments no longer include them. Runbetter-supabase gento regenerate. Supabase CLI 2.119 doesn't writeComputedFieldsyet, so until it does,supabase gen typesoutput differs fromgenby that key. -
The optional
oxfmtpeer accepts any version from 0.66.0 below 1.0, sopnpm add -D oxfmtinstalls the latest. The runtime dependencies are ranges instead of exact versions:@supabase/postgrest-js ^2.116.0(the floor of the@supabase/supabase-jspeer),@supabase/ssr ^0.12.7,@supabase/server ^1.9.0,@supabase/middleware ^1.0.0and@standard-schema/spec ^1.1.0, so an app shares one copy of each with its own Supabase packages.@supabase/postgrest-typegenstays an exact version.The
canAssignJSDoc no longer says it defaults to true. Thecustomaccess model requires it. Without it, thepermdockmodel lets only owners assign the owner role when thetenantmodule is installed, and lets only the service role assign roles when it isn't. The access kit docs now say the same, and theircustomexample setscanAssign, which that model requires.
0.5.0 (2026-10-04)
-
Guards refuse anonymous users (
signInAnonymously(), theis_anonymousclaim) with a 403ANONYMOUS_USERunlessallowlists'anonymous'or'anon',toSession()addsanonymous, and therealtime-tableskit module sends anonymous users no change signals. Before 1.0 this minor release is the breaking slot: routes that served guest sessions needallow: ['user', 'anonymous'].The framework adapters agree with each other.
ctx.apply(response)adds refreshed session cookies and, after a write,bs-primary-until, so Hono, edge and the new oRPCbs.fetchHandler(handler)keep read-your-writes like Next.js does. MCP reads the session from theAuthorizationheader only, answers an unreachable JWKS with a 503 instead of a scope challenge, sends a missing second factor as a plain 403, takesadvertisedScopes(withscopesas a deprecated alias) and enforcesrequiredScopes. REST resources refuse cross-site form posts that ride on the session cookie (CROSS_SITE_REQUEST) and answer malformed keys and bodies withinvalid_input, whose detail survives in production. Hono'sbs.onErrorreturns anHTTPException's own response, Next.js route handlers turn unexpected throws into a 500 Problem Details response whileredirect()andnotFound()still work, andcontextForSessionrequires the token's auth kind to match the session.createServertakesfetchfor its PostgREST and supabase-js clients, theauthevent carriesreasonandrawSource, thereact-serverbuild exportshasEntitlementanduseLiveCount, and every adapter builds the user actor, impersonator included, from one function. -
The
auditSQL kit module can adopt an existing audit table (kits.audit.tablesandcolumns), andaudit()takesredact,category,event_prefix,target_typeandtenant_column. The newaudit_eventfunction records events that are not row changes, with an idempotency key. The optionsappendOnly,readPolicy,impersonators,restricted,eventRoles,eventCategoryandeventSourceadd an append-only guard, a tenant read policy, hidden impersonation columns and a separate table for sensitive details.purge_audit_loghonours anaudit_retention(tenant)SQL hook, andpurgeAuditLogfrombetter-supabase/jobstakes a per-tenant retention callback. Runbetter-supabase sql upgradeto move from version 1. -
better-supabase/honoaddsbs.app(), aHonoapp typed with the adapter'sEnvand withbs.onErrorinstalled, and the type-onlybs.Envfor apps that build their own. After@supabase/server'swithSupabase,bs.middleware()reuses its verification of the bearer token when the stored claims are that token's payload, then runs its own claims,actanduserMetadatachecks.clearOnUserChange(queryClient, auth)inbetter-supabase/queryremoves the["bs"]queries when the signed-in user changes, for apps without React;BetterSupabaseProvideruses it.A bucket with
tenantnow checks paths on the client too:upload,download, signing,remove,reserveandlistrefuse a path in another tenant's segment, or any path when the connection has no tenant, with aforbiddenerror before calling Storage. Pass{ context }or{ tenant }toconnect(), or{ allTenants: true }for cross-tenant admin work;deleteAccountdoes the latter.client.path(target)returns the checked path.Jobs record the enqueuing request's actor and tenant:
enqueue(queue, payload, { context })andschedule(..., { context })store them next to the payload, and the handler gets them asjob.context, ready fordb.$with(job.context). A job without a tenant gets thetenant()plugin'sonMissingunless the worker runs withallTenants: true.actor()fills animpersonatedBycolumn (generated fromimpersonated_by, the column the SQL kit'strack_actorstamps) from the impersonating admin, and clears it on writes without one.Event sink sends are tracked on
betterSupabase.events(pending,settled()). Next.js routes and actions hand them toafter(), and edge handlers towaitUntil: the Workersctx, orcreateEdge(..., { waitUntil })on Supabase.The PermDock guide has oRPC and Hono recipes that refuse a procedure or route without a permission.
-
Jobs run without pgmq or pg_cron when you want.
kits.jobs.options.backend: "table"stores jobs inbetter_supabase.job_messagesand claims them withfor update skip locked, andkits.jobs.options.scheduler: "drain"stores schedules with a time zone each.jobs.drainRoute({ secret, handlers })is a route for Vercel Cron that enqueues due schedules and drains queues within a time budget, anddraintakes abudgetMs.scheduletakes{ timeZone }and validates the cron expression first.createJobsaccepts anyQueueBackend(API version 1), withsqlQueueBackend,pgmqPublicBackendand thetestQueueBackendconformance kit. Thejobsmodule is now version 2:better-supabase sql upgradedrops the old four-argumentschedule_job. -
The SQL kit's rows and role settings, which a schema diff can't capture, move to
supabase/better-supabase-data, and the newbetter-supabase sql datawrites them into a migration stamped after the newest one.rate-limitsetspgrst.db_pre_requestthat way, and doctor BS313 warns when the live database never callscheck_request().sql upgradewrites next to the locatedconfig.toml, and each module rejects options it doesn't declare.Breaking:
entitlementsno longer defaultsentitlements.customertoorganizations.stripe_customer_id. It reads the managedorganizationsmodule's column when that module is installed; otherwisesql addstops until you set it.tenant_ids_with_entitlement(key)gives policies a set check.Jobs enforce max attempts at claim, retry with full jitter and replay dead letters (
replay_dead_job,jobs.replay). The outbox orders by(xid, position)and gives events uuid ids. Outgoing webhooks take a lease token, follow the Svix retry schedule withRetry-After, and disable a destination after failing fordisableAfter. Notifications back off between deliveries and fail them aftermax_attempts. Key indexes lead with the key, webhook policies readtenant_ids_with()once per statement,jsonb-schemasadds its checksnot validand validates them separately, andpurge_rate_limits(),purge_webhook_deliveries()andpurge_notifications()join the other purges. -
Kits share one set of extension points: typed events, policy callbacks, SQL hooks and fixed attribute names.
betterSupabase.on("kit", handler)receivessupport.*,org.*,invitation.*,notification.*andwebhook.*events with a copy of their data.onKitEvent(betterSupabase, "support.*", handler)frombetter-supabase/eventsfilters by type or prefix and types the data.forwardKitEvents()andkitCloudEvent()send kit events to anEventSinkas CloudEvents, andtraceKitEvents()frombetter-supabase/otelrecords them with theKIT_ATTRIBUTESnames (better_supabase.org.id,better_supabase.support.session_id, ...).- Policy callbacks (
Policy,PolicyDecision) fail closed: onlytrueallows, and a throw or rejection denies. kits.<module>.hookssets where a module looks for the app'sbefore_*andafter_*SQL functions, andkits.<module>.events: falsestops it writing its events to the outbox.
-
Breaking: the SQL kit fails closed.
current_tenant_id()returns a tenant only while the caller is a member, the claim is cleared when a member is removed, andkits.access.activeTenantdefaults to'resolver'(the tenantServerOptions.tenantresolved, then the claim). Disabled organizations deny access, thepermdockandcustomaccess models need an assignment rule, and only an owner can transfer ownership. A member can never raise their own role or assign one above it.Platform invitations move to
platform_invitationsunder a role ceiling that accept checks again, accept checks that the inviter can still assign the role, andvalid_foris capped bymaxValidFor. Support sessions refuse platform targets and writes by default and allow one active session per admin; a token with anactclaim has no platform permissions.Doctor BS312 reports a kit schema listed in
[api] schemas.set_actorkeepscreated_byon updates,track_realtimerefuses a table without the tenant column, the rate limit andrequest_ip()use the right-most forwarded hop, audit is append-only by default, idempotency keys are scoped to the caller, public buckets get no select policy, members see only public profile columns, and outgoing webhooks follow no redirects, cap the response body and use 32-byte secrets. -
Breaking: the SQL kit follows one naming standard. Run
better-supabase sql upgrade, thensql syncandsql data; the 0.4 to 0.5 guide lists every step. The forward steps renamememberships.org_idandinvitations.org_idtoorganization_id,better_supabase.audit_logtoaudit_events(withoccurred_atandorganization_id, and a read-onlyaudit_logview until 0.6), andaudit_trigger()toaudit_row_change(). Doctor reports the old column names in your SQL (BS309), also when a column is unqualified next to its table.The modules new in this release use the same names:
webhook_endpointswithevent_typesand the statusespending,delivering,succeeded,retrying,deadandcanceled; notifications withtype,data,actor_idanduser_id, andtypesinstead ofkindsincreateNotifications. Permission keys follow<area>.<verb>, and managed tables getupdated_attriggers and indexes on their foreign keys.Breaking:
toCloudEventsandkitCloudEventput the actor indata.actorIdinstead of theactoridcontext attribute, so user ids stay out of broker headers. The outbox relay prefixes event types withdev.better-supabase, andwebhooks.sink()removes the prefix again. -
The new
sessionsSQL module addsbetter_supabase.session_active()for restrictive policies: it is false once the token's session was revoked or expired, or the user is banned or deleted.Options that only exist to match an existing schema are accepted in
mode: "adopt"only:tokenStorage: "plain"for invitations,secretStorage: "column"and non-texteventIdTypeorrunIdTypefor webhooks-out, andkitSourceordefaultSourcefor the outbox. Doctor BS314 warns about each until you remove it.better-supabase/sqlexportsmigrationOptionUses(kits)to list them. TheassignmentCeilingandtriggerPrefixoptions, the invitationserrorCodesoption andkits.access.disabled.tenantKeyare removed. -
SQL kit modules now fit existing schemas.
kits.<module>in the config sets a module's mode (managed,adoptover your own tables, orcustomwhere you write the contract functions), its schema, table and column names, tenant id type and permission keys. Each file's header records the module version and mode, and schema files record them inbetter_supabase.kit_modules. Doctor BS307 checks the functions of custom-mode modules, and BS304 points hand edits atkitsinstead.The new
accessmodule gives policies and kit modules one permission check,can(scope, id, permission), withtenant_ids_with(),is_platform(),can_user(),can_assign()andpermission_claims().kits.access.modelpicks a role list from the config, role and permission tables with per-tenant overrides, PermDock or your own functions, andkits.access.disabledswitches off tenants and users with adisabled_atcolumn. Thetenantmodule (version 2) takes its role names fromkits.access.roles, addsmemberships.last_used_atandorg_member_role(), writes the memberships claim as an array or a map (options.claimFormat), and reads the active tenant fromkits.access.activeTenant: a resolver (the default), the claim or a profile column.For resolvers,
createServertakestenant: (request, auth) => id, andcontext()takes{ tenant }. The tenant becomescontext.tenant, thebetter_supabase.tenantsetting over Postgres and thex-bs-tenantheader (TENANT_HEADER) over the Data API.postgres.asUser,executorForandtransactiontakesettingsandreadOnly. Doctor BS308, with--as <user id>, warns when the access token hook writes no tenant claim while the claim is the active tenant.better-supabase/configexports the kit config types (KitsConfig,KitModuleConfig,KitMode,AccessKitConfigandActiveTenantSource) for apps that build theirkitsconfig in a separate module. -
SQL kit modules have versions and an upgrade path, and a codemod rewrites renamed APIs.
better-supabase sql upgradereads each module's@bs-kitversion (a file without one is version 1), writes the forward steps intosupabase/migrations/<timestamp>_better_supabase_kit_upgrade.sqland rewrites the module files.--checkexits 1 when a module is behind or a file is stale.- Deprecated kit functions keep a wrapper under the old name until they are removed.
upgradePlan(),kitDeprecations()andmoduleVersion()are exported frombetter-supabase/sql. track_updated_at()andaudit()warn about an existing trigger that does the same work, and drop it withreplace_trigger => true.- Doctor reports deprecated or removed kit symbols in schema files and policies (BS309), a kit trigger next to an equivalent one (BS310), and a module behind its version on disk or in
better_supabase.kit_modules(BS311). BS304 skips files BS311 reports. better-supabase codemod <version>rewrites imports, members, JSX props and call options for renamed APIs (0.4, and0.5forcreateMcp'sscopes), skipping strings and comments, and lists the lines it leaves for review.--dry-runprints the diff.
-
Add the
notificationsSQL kit module andbetter-supabase/notifications.notify(jsonb)is asecurity definersender that checksnotifications.send, leaves out the actor and non-members, and applies subject subscriptions and per-channel preferences.createNotificationssends with typed data and reads, counts, marks, dismisses and resolves notifications;deliver()sends email, push and other channels throughNotificationChannelimplementations with leases and retries.useNotificationsfrombetter-supabase/reactkeeps a list current over a private Realtime topic. Existing tables work withmode: 'adopt', and the topic and event names are configurable.OrgsTransportis nowKitTransport, exported from bothbetter-supabase/orgsandbetter-supabase/notifications. -
Organizations and invitations. The new
organizationsSQL kit module creates, updates and deletes organizations (hard or soft), changes member roles, removes members, transfers ownership and switches the active organization throughkits.access.activeTenant. A deferred trigger keeps an owner in every organization, and a trigger stops members from raising their own role or assigning one above it. Theinvitationsmodule moves to version 2:invite_memberreturns the invitation with its token, invitations can be resent, revoked, declined and previewed without a session, can carryprefilldata and can target the platform under the catalog access model, and accepting re-checks that the inviter may still invite.create_invitationkeeps its 0.4 signature. Both modules check permissions through the access contract, soinvitationsnow needsaccess, and both supportmode: 'adopt'with options for token storage, slug rules, error SQLSTATEs and extra columns. The newbetter-supabase/orgssubpath calls them withcreateOrgs, over Postgres (sqlTransport) or the Data API (rpcTransport), withcanInviteandonInvitecallbacks andorg.*andinvitation.*kit events, including the neworg.updatedandorg.deleted. Thetenantmodule now installs on a fresh database underkits.access.model: 'catalog'. -
Transactional outbox. The new
outboxSQL kit module stores events withemit_event(type, payload, subject, tenant, key, source)in the writing transaction, deduplicates by key per tenant, addstrack_events(table)row triggers and keeps events foroutbox_historyuntilpurge_outbox. Named consumers read in order with their own cursor and a lease, and a claim never skips an event whose transaction is still open. Theorganizationsandsupport-sessionsmodules write their events to it once it's installed.createOutboxinbetter-supabase/jobsemits, registers consumers, relays events as CloudEvents to anyEventSinkand servesrelayRoutefor a cron caller. The module supportsmode: 'adopt'for an existing events table.The
defaultSourceoption fills the source ofemit_eventcalls that pass none, andkitSourcesets the source kit modules write (better-supabase/{module}by default), so an adopted events table with a check on its source column keeps working. Adopt mode still creates the consumers table, since an existing app has no cursors yet. -
The PermDock integration fails closed in more places. Buckets and topics in
permdockmode now call PermDock's helpers inpermdock, PermDock's defaultrls.schema, instead ofpublic; setschema: 'public'on the policy if your PermDock config writes them there.genand doctor BS214 refuse PermDock bucket policies whenpermissions.catalog.jsonis missing, and the catalog must be version 1.sql add entitlementsrefuses a PermDock project without a manifest orrlsblock instead of falling back to the tenant module (setentitlements.permdock: falsefor that). BS214 also reports a helper schema other than the manifest's, a scope the manifest doesn't declare and a key checked at another scope than its catalog entry. BS408 checks that PermDock's hook fillsclaims.featuresfrombetter_supabase.feature_claimsand that a membership source covers the scope. The new BS409 reports aclaims.tenantthat differs from the manifest'srls.tenantClaim, PermDock markers other than v1 and aclaims.scopethat isn't the root scope. Scope id typesinteger,int8and other aliases are accepted, and MCP table tools take a permission per operation from the resource'smeta. -
Plugins compose without holes.
timestamps(),actor()andsoftDelete()refuse caller-supplied values for the columns they fill unless the call passes{ override: true }, and generated JSON Schema and OpenAPI documents mark those columnsreadOnly. On tenant tables, an upsert that updates on conflict needs the tenant column in its conflict target, the SQL executor guards the update withwhere <tenant> = excluded.<tenant>, a query whose includes reach a tenant table fails closed without a tenant, and numeric tenant columns compare by their text. An upsert that updates a soft-deleted row restores it.rules()runs before every other plugin.noUnboundedFindManyskips aggregates,maxLimitignorespaginate()'s look-ahead row,requireTenantContextreads the same claim paths astenant(), andnoSensitiveSelectchecks reads only, because writes without aselectno longer return sensitive columns. Offsetpaginate()orders by the primary key by default.validation()decodes codec columns (Temporal values,bigint) before validating and encodes them afterwards.Mutation events give hooks and listeners a copy of the rows, so they can't change the result (
testPluginchecks this), and carryintent(softDeletefor a delete that became an update), the affected primarykeyswhen they are known, and thetenantthattenant()resolved. CloudEvents and cache invalidation use them, so soft deletes sendrow.softdeletedevents and invalidate their rows.defineReadSetwarns when query plugins scope tables its generated function reads. The audit kit keys entries by each table's primary key and reads the tenant column fromplugins.tenant.column, andgenrefuses a soft-delete column that isn't a timestamp. -
Profiles and image buckets. The new
profilesSQL kit module creates a profile on sign-up from auth metadata (full, first and last name, avatar), allocates a unique username, mirrorsauth.users.email, grants updates only on the columns users own and refuses changes to service-owned columns (PROFILE_COLUMN_READONLY). It supportsmode: 'adopt'for an existing table keyed by any column, anafter_profile_synchook, extra columns, a read policy for people in the same organizations andbackfill_profiles().better-supabase/storageaddsavatarBucket()andorgLogoBucket()presets and a bucket policy,{ access: { read, write } }, that checks permissions through the SQL kit's access contract. -
Support mode: platform admins can view the app as a user. The new
support-sessionsSQL kit module records sessions in a table (or an adopted one), checksis_platform('support.start'), writessupport.startedandsupport.endedto the audit log and can call your access token hook for the target's claims.createServertakessupport: supportSessions({ store, authorize, claims, policy, cookie }), which apps without support mode never bundle; while thebs-supportcookie names a running session, contexts, sessions, actions and routes run as the target over Postgres, read-only by default, with anactclaim that carries the session id. Next.js getsbs.startSupport(),bs.stopSupport()andsupportTag(), React getsuseSupportSession(), andbetter-supabase/testinggetstestSupportSessionStore. The audit module records the session in a newsupport_session_idcolumn; an adopted table mapssupportSessiontonullwhen it has none. -
Values from Postgres and the peer libraries no longer break responses. JSON responses from the server adapters and MCP write
bigintvalues as decimal strings. Atimestamptzortimestampholdinginfinitycomes back as aninvalid_valueerror (status 500, withcolumn) instead of throwing, because Temporal has no infinite value. Temporal values from another realm or a second polyfill copy are recognized by theirSymbol.toStringTag, and Standard Schema issues with symbol path keys keep the error serializable.loadEnv()reads inline keys fromSUPABASE_JWKS, as@supabase/serverdoes, and verifies with them without fetchingjwksUrl. The OpenTelemetry plugin writesdb.namespaceas{database}|{schema}(postgres|publicby default,otel({ database })to change it), addsserver.addressandserver.portfromotel({ server })to spans and metrics, and setsdb.response.status_codeonly for SQLSTATE codes.BetterQueryMetabuilds on the app'sRegister['queryMeta'], andsend_email'semail_dataaccepts fields Auth adds later.Doctor's BS410 reports HTTP auth hooks and checks their
v1,whsec_secrets, and its custom access token hook event carriesissandamr. The peer ranges now state what the code needs:pg >=8.15 <9,@tanstack/query-core ^5.62.0,@orpc/server >=2.0.0-beta.40 <3,hono <5,next <17,@opentelemetry/api <2, andoxfmt 0.66.0, the version@supabase/postgrest-typegenpins; thegennotice and docs show how to allow a newer oxfmt. -
Add the
webhooks-outSQL kit module and outgoing webhooks inbetter-supabase/webhooks. Destinations subscribe to event types (exact,*orprefix.*), secrets live in Supabase Vault (or a column) and rotate with an overlap, and every delivery is logged with its status, response and duration.createWebhookspublishes events idempotently, dispatches to one destination, anddeliver()ordeliverRoute()sends due deliveries with leases, retries with backoff, dead letters, redelivery and auto-disable after repeated dead letters. Requests are signed with Standard Webhooks by default or withhmacSignerfor an existing format, andpublicUrl()rejects private and local addresses, also on each redirect.WebhookSigner,WebhookTransportandWebhookSecretStoreare versioned extension interfaces with conformance kits inbetter-supabase/testing. RLS policies in thenotificationsmodule now usebetter_supabase.can, which clients may execute, instead ofmember_can. -
The docs and skills follow the Naming page's file layout everywhere. The PermDock page defines
betterSupabaseinsrc/lib/supabase/index.tsand createsbsinserver.tsandclient.ts, and every Next.jsserver.tsstarts withimport "server-only". The docs drift check now fails a code block that breaks the layout. -
Doctor BS404 and
doctor --fix-grantsfollow pg-delta for PermDock's hook. With[experimental.pgdelta] enabled = true, they point topermdock supabase hook generate --out <schema file>without--grants-out, thensupabase db schema declarative sync, instead of a grants migration. A hook whose grants are in the declarative schema file that defines it now counts as granted under pg-delta, and the finding for a file that already grants the hook namessupabase db schema declarative syncbeforesupabase migration up. -
Doctor BS408 checks exactly the PermDock helpers the
entitlementsmodule calls for the chosen scope, and no longer claims PermDock writesmember_<scope>_ids_forfor every scope. It warns when the manifest lacksmember_<scope>_idsor doesn't letauthenticatedexecute it, when it lacksmember_<scope>_ids_for(add a membership source for the scope inpermdock.config.ts), and whensupabase_auth_adminmay not executemember_<scope>_ids_for(addsupabase.hook.claims: { features: 'better_supabase.feature_claims' }). -
The PermDock MCP recipe in the docs and the auth skill fails closed: a tool without a PermDock permission in
metais hidden (visiblereturnsfalse) and refused (authorizereturns{ allowed: false }). The page also shows PermDock'sdecidefor putting the denial reason in the refusal. -
The
entitlementskit module takes its PermDock scope from the manifest. Withoutentitlements.permdock.scope, it now uses the manifest's root scope (therls.scopesentry withoutwithin) instead oforganization, so a PermDock project whose root scope istenantworks without config. A manifest with no root scope or several stopssql add entitlementsand doctor BS408 asks forentitlements.permdock: { scope }. An explicitscopestill overrides,falsestill opts out, and a scope the manifest doesn't list is still reported by BS408.permdockKeyStatusand thePermdockCatalogandPermdockKeyStatustypes are exported frombetter-supabase/sql. -
In PermDock mode, the
entitlementskit module renders the tenant argument ofhas_entitlement,tenant_entitlementsandtenant_stripe_customer, and the rows ofstripe_customer_tenants, with the scope's id type from the manifest'srls.scopes(uuid,textorbigint) instead of alwaysuuid. A missing or other type stopssql add entitlementsand doctor BS408 reports it.better-supabase/sqlexportsKIT_ID_TYPES,isKitIdTypeand theKitIdTypetype, andKitPermdockhas a requiredidType. -
The auth skill's PermDock caching recipe works as written. It passes only static tags to
bs.cached(), then callscacheTag(snapshotTag(session.user.id))andcacheLife(cacheLifeFor(snapshot))inside the loader once the snapshot is built, because the user id and the snapshot don't exist beforebs.cached()returns. It pairs the recipe withbs.invalidateSession(userId, { tags: [snapshotTag(userId)] }). -
PermDock's catalog is read fail closed.
defineBucketanddefineTopicwithcatalogaccept only keys markedrowConditions: false: a key whose entry has no booleanrowConditions, or that the catalog doesn't list, now throws with a message to regenerate the catalog with a currentpermdock catalog. Doctor BS214 reports those keys as errors, andbetter-supabase genrefuses to write their bucket policies.
0.4.0 (2026-10-03)
-
The CLI ships inside
better-supabaseagain. Installingbetter-supabasegives you thebetter-supabasecommand, so drop@better-supabase/clifrom your dev dependencies (it was never published) and runnpx better-supabase initin a new project. The commands and their options are unchanged. The CLI's own dependencies are bundled into the package, so apps install nothing extra;pgstays an optional peer that the CLI needs to read your database.Import
run,registerCommand,defineCliCommandand the introspection helpers frombetter-supabase/cli.@supabase/configis an optional peer again, for readingsupabase/config.toml.VERSION,better-supabase --version, doctor reports and the header of newly written SQL kit files now show the package version instead of0.0.0. Existing kit files are not reported as changed, because the comparison ignores that version. -
Names are now the same in every adapter. The definition from
defineSupabaseisbetterSupabase, and every runtime instance an adapter creates isbs. They live inlib/supabase/index.ts,lib/supabase/server.ts(withimport "server-only"in Next.js) andlib/supabase/client.ts, which is whatbetter-supabase initnow writes. The old names have no aliases; the compiler points out each one. Naming lists the conventions.Before After createBrowser,BetterBrowser,BrowserOptions,BrowserAuthcreateClient,BetterClient,ClientOptions,ClientAuth<BetterSupabaseProvider browser={browser}>,BrowserLike<BetterSupabaseProvider client={bs}>,ClientLikeclient.sband thesboption oftestExecutorand the test pluginbetterSupabasenext.server()bs.context()(pass aRequestto read it instead of the incoming one)next.serverFor(session, { token })bs.contextForSession(session, { token })BetterEnvandbs.handle()(Hono)HonoEnvandbs.handler()bs.toORPCError()bs.toOrpcError()HandlerOptions(Edge)MiddlewareOptions, shared by Hono, oRPC and Edge and exported frombetter-supabase/serverhandler(MCP)endpointQueries,CreateQueriesOptions,queries.keyBetterQueries,QueriesOptions,queries.$keyPostgresBetterPostgresDefineSupabaseOptionsSupabaseOptionsrepository.$tablerepository.$tableNamecreateHono,createOrpc,createEdgeandcreateMcpnow keep the claims and profile types from.claims()and.userMetadata(), soc.var.auth,context.auth, the edge handler'sauthand MCP'sctx.authare typed by your schema.better-supabase/nextalso exports theLiveCountSeedtype thatbs.liveCount()returns. -
Less work per request in auth and the adapters.
- The Next.js adapter verifies the token once per render scope:
context(),session()andcached()share one resolution.BetterServergainscontextFromResolution(resolution, request)for the same pattern elsewhere. - A token seen before skips the claims and
userMetadataschemas as well as the signature check, per schema pair. createServerfetches the JWKS when it is created, so the first request doesn't wait for it. PassprefetchJwks: falseto turn it off; it is off underNODE_ENV=test.- Bearer requests parse cookies only when something reads them, and contexts read the replica pin cookie only when a read URL is configured.
- Job workers back off from
pollIntervaltomaxPollInterval(30 seconds by default) while the queue is empty, and keep the leases of every job in a claimed batch alive, not only the running one. - Webhook verification imports each secret's key once, compares signatures
with
crypto.subtle.verify, and checks the headers before reading the body. - The MCP server builds its tool list once when no
visiblehook is set. - The OpenTelemetry plugin builds span and metric attributes once per table and operation.
- Edge resource routes answer unknown paths before resolving auth, and a malformed id is a 400 instead of a 500. CORS header values are built once.
- The Next.js adapter verifies the token once per render scope:
-
A faster CLI that reads the database less often.
--helpand each command's--helpstart in about 30 to 50 ms instead of 130 to 150 ms: the commands, config loading, env validation, prompts and the typegen schemas load only when a command runs.genhashes the system catalogs with one query and reuses the snapshot cached innode_modules/.cache/better-supabasewhile the schema is unchanged.gen --watchkeeps one connection open and polls that hash, so an unchanged schema costs one small query per interval.- Introspection runs its queries concurrently over a pool of four connections. Connecting gives up after 10 seconds and each introspection query after 2 minutes; Ctrl-C ends the connection or Management API request and exits with code 130.
doctorreads the snapshot and runs its live checks and splinter over one connection, and reads its input files concurrently.oxfmtis now an optional peer. Without it,genwritesdatabase.types.tsunformatted and prints a notice instead of failing.- Generated files and doctor reports sort names by code point, so they no
longer depend on the machine's locale. Run
better-supabase genonce; the order of a few entries ingenerated.tsand the validator files can change. - Breaking:
parseSnapshotfrombetter-supabase/clinow returns a promise, so the typegen schemas load on first use. Addawait.loadSnapshottakessignalandcachein its source options.
-
Fixes four bugs the performance audit found, one of which changes behavior.
findManywithoutorderBynow orders by the primary key's database names. On a camel-cased table whose key isn'tid(customerTagswithcustomerIdandtagId) it sentorder=customerId.asc, which PostgREST rejects.topic.send()no longer closes a subscription on the same topic. realtime-js reuses the open channel for a topic, andsend()removed it after sending.liveQuerykeeps the shared channel when a listener re-joins in the same tick (React StrictMode remounts), instead of subscribing the new listener to a closing channel.- A session refresh now times out after
refreshTimeoutMs(5000 by default, an option ofresolveAuthand every adapter'sauth) and counts as a network failure. Before, a hung Auth request blocked every later request carrying the same refresh token. A rejected refresh is reused for ten seconds, like a successful one.
Breaking: where refreshing is off (Server Components, route handlers, prefetches, MCP), a token in its last 60 seconds is now valid until its
exp. It used to resolve as{ kind: 'anon', reason: 'expired' }, so pages rendered signed out in the last minute of every token.leewaynow only decides when the proxy refreshes. -
Generated files and types that cost less to check and to bundle.
- Breaking:
genwrites the schema metadata togenerated.meta.jswith agenerated.meta.d.tsnext to the main module, which imports it. TypeScript reads the metadata asSchemaMetainstead of checking a large object literal, which cuts check time and editor memory on large schemas. Runbetter-supabase genand commit both new files. - Breaking:
BetterPostgresgainsexecutorFor(claims), andcreateServeruses it forctx.sqlandactingAs(). Apps that don't passpostgresno longer bundle the SQL compiler; the Next.js, Hono, oRPC, edge and MCP entries are about 5 KB gzip smaller. A customBetterPostgresimplementsexecutorForaspostgresExecutor(asUser(claims)). - Reads without
selectorincludereturn the row type directly, which removes about a quarter of the type instantiations a query costs. - The build marks library modules as side-effect free and annotates module-level objects as pure, so bundlers drop the parts an app doesn't use.
- Breaking:
-
Faster request path in the core runtime.
connect()costs the same for any number of tables: every connection shares one prototype of table getters, and repositories are built on first access.- For a signed-in user,
ctx.db(anddbFor()) on the server runs on a bare PostgREST client, so requests that only query data no longer build the Realtime, Storage and Auth clients.ctx.supabaseandctx.db.$clientstill return the full supabase-js client, built when first read.better-supabasenow depends on@supabase/postgrest-jsat the version supabase-js uses. - Default selections, rendered select strings, column lookups, unique keys,
invalidation targets and the tables a query spec reads are computed once per
table or spec instead of on every call. Plugin hooks, tenant resolution and
claim paths are resolved once, and
mutationanderrorpayloads are only built when someone listens. - Row decoding and paging copy each row once instead of spreading and deleting keys in loops.
- Bucket connections take
{ cacheSignedUrls: true }to reuse a signed URL until shortly before it expires. The cache belongs to the connection. - Outside production, the event hub warns once when an event collects more than 50 handlers, which usually means a missing unsubscribe.
invalidationTargets()now returns a frozenreadonly string[]. -
The Agent Skills cover 0.3. A new
better-supabase-authskill teaches sessions, typed claims, OAuth clients and agents behind a token (session.actor,session.delegationand thescopesguard option),checkSessionbefore irreversible actions, what happens when claims change, and how to run next to PermDock. Thebetter-supabaseskill adds an upgrade workflow, cursor pagination,Temporalvalues, the CLI's--json,--db-url-stdinand exit codes, andmember_org_ids()in tenant policies. Thebetter-supabase-apiskill addsscopes, cursor resources, the MCPauthorize,visibleandallowedHostsoptions, the kit's purge functions and the Postgres pool options. Thebetter-supabase-testingskill adds delegated-token API tests,Temporalin tests and doctor in CI. Runbetter-supabase skills installto update installed skills.
0.3.0 (2026-10-02)
-
Name the OAuth client or agent behind a bearer token. A user session now carries
actoranddelegation, read fromclient_id,scopeand the RFC 8693actchain the way PermDock'sactorOfanddelegationOfread them. A malformedactchain resolves to{ kind: 'invalid', reason: 'actor' }and a 401, soInvalidReasongains'actor': an exhaustiveswitchover it needs the new case. Thescopesguard option onnext.route,next.actionand the edge, Hono and oRPC adapters answers 403 with an RFC 6750insufficient_scopechallenge when a delegated token lacks a scope; the user's own token is not limited.forbiddenerrors and Problem Details carry the neededscopes.better-supabase/servernow exportstoSession,AuthSession,ActClaim,SessionActorandSessionDelegation. A new monorepo guide shows one runtime package that ownsdefineSupabase, with domain packages typed from itsdb. -
Breaking: the
BetterResultShapetype is nowBetterResultValue. It is still the typetoBetterResultreturns, with thestatus,valueanderrorfields of a better-result value; rename the import to upgrade. -
On the Postgres executor,
createManyandupsertManysplit an insert that needs more than 65,535 bind parameters into several statements and run them in one transaction, instead of failing.upsertManysends rows sorted by the conflict columns, so concurrent upserts over overlapping rows lock them in the same order instead of deadlocking; its returned rows follow that order. -
checkSession(sql, auth)frombetter-supabase/authandbetter-supabase/serverconfirms that a user token's session still exists inauth.sessions, and returns anunauthorizederror with codeSESSION_REVOKEDwhen the user signed out or the session was ended. Call it before actions you can't undo, such as deleting the account. Nothing calls it by default, so other requests still verify tokens without a round trip. -
The CLI runs on citty.
initandaddask for the casing, the integrations and whether to overwrite files when they run in a terminal;--yes, CI and piped input skip the questions. Output is colored in a terminal (NO_COLORturns it off), database work shows a spinner on stderr, andgen --check,introspect --checkandsql sync --checkprint a unified diff of each stale file.registerCommandtakes a command from the newdefineCliCommand, andlist()splits list options. The 0.2 form,registerCommand(name, command, help), still works and is deprecated.help()replaces theHELPconstant. -
Breaking: the CLI follows one set of conventions for output, errors, prompts and secrets.
--db-urlis removed fromgen,introspect,doctorandseed, because a connection string holds the password and arguments end up in shell history and the process list. Set$DATABASE_URLorsource.dbUrl, or pipe the URL in with--db-url-stdin.--jsonis a global option. It prints one JSON document on stdout: the command's result, or RFC 9457 Problem Details with acodewhen it fails.doctor --format jsonbecomesdoctor --json.--yes(-y) is a global option. Prompts never run under--json,--yesorCI.- Exit codes are 0 for success, 1 for a failure and 2 for a usage, config or environment error. Every error code has a section on the errors page.
- A mistyped command gets a suggestion:
Did you mean "gen"?. better-supabase.config.*loads through c12 and is checked against a schema; an unknown key or a wrong value stops the run with each problem's path.DATABASE_URLandSUPABASE_API_URLmust be URLs.run()no longer readsprocess.env: passrun(argv, { env: process.env }).CliIo.envandCliIo.noware removed, andCliIo.stdinis new.- New exports:
CliError,CLI_ERRORS_URL,commandNames, and theCliEnv,CliProblemandCliErrorCodetypes. A command can throwCliErrorand returndatafor--json.
-
The CLI moved to its own package,
@better-supabase/cli, released at the same version asbetter-supabase. Install it withpnpm add -D @better-supabase/cli; thebetter-supabasecommand and its options are unchanged.Breaking for
better-supabase: the package no longer ships thebetter-supabasebin or thebetter-supabase/clisubpath. Importrun,registerCommandand the introspection helpers from@better-supabase/cliinstead. The newbetter-supabase/sqlsubpath exports the SQL kit (renderKit,kitLayout,compileReadSets), andbetter-supabase/confignow exports the snapshot types,DEFAULT_CLAIMSandtenantClaimPaths.The library no longer has
@supabase/configas an optional peer; only the CLI readssupabase/config.toml. -
Doctor BS213 warns when
anonorauthenticatedmay insert or update a column that RLS helpers read to decide access, such asmemberships.roleorcontacts.customer_id, and a policy lets them write the row. It also checks thedecidingColumnsin PermDock's manifest and names PD028. The finding lists the revoke and the grant of the remaining columns. Snapshots now record column-level insert and update grants (columnGrants); older snapshots only show table grants. -
Doctor treats
security definerfunctions and functions with asetoption as not inlinable (BS205, BS206), and its advice for them now points tocolumn in (select helper()). New checks:auth.role()(BS109), update policies without a select policy orwith check(BS110), needless and unused API grants (BS111), exposed security definer functions that never check the caller (BS112), storage inserts without the upsert policies (BS113), helpers that readuser_metadata(BS114), zero-argument helpers called withoutselect(BS215), foreign keys without an index (BS216, replacing splinter's lint for the same table), tenant foreign keys that can cross tenants (BS217), soft-delete tables without a partial index (BS218), containment filters without GIN (BS219), column types to avoid (BS220) and direct connections in serverless apps (BS221). BS211 also reportsidle_in_transaction_session_timeout.Snapshots now record each index's access method and predicate, and who among
anonandauthenticatedmay execute the functions doctor reads. Both fields are optional insnapshot-v2.json, so older snapshots still load. -
The
entitlementsSQL kit module reads memberships from PermDock whenpermdock.manifest.jsonis present:has_entitlementchecks<rls.schema>.member_<scope>_ids(),feature_claimsreadsmember_<scope>_ids_for(user_id)from PermDock's hook, andentitlement_membersreads the manifest's membership tables.sql add entitlementsthen no longer adds thetenantmodule or prints the hook note. The scope defaults toorganization; setentitlements.permdock: { scope }for another of the manifest's scopes, orentitlements.permdock: falseto keepbetter_supabase.memberships. The new doctor check BS408 warns when the manifest or the database lacks one of the two helpers. -
Cursor pagination no longer skips rows whose sort column is null: the next page follows where Postgres places nulls (last for
asc, first fordesc, or thenullsoption). On thebetter-supabase/postgresexecutor a cursor over columns that sort the same way and are not nullable compiles to a row comparison such as(name, id) > ($1, $2), which one index range scan can serve.defineListQuery,defineResource,createOpenApiand the MCP table tools acceptpagination: "cursor". The list then takesafterinstead ofpage, returnsnextCursorandhasMore, keepssizecapped bymaxPageSize, and documents the cursor in its OpenAPI parameters and JSON Schema.paginateand offset lists work as before. -
The
audit,webhook-inboxandjobsSQL kit modules addpurge_audit_log,purge_webhooksandpurge_job_archive. Each deletes rows older than an interval in batches and returns how many it deleted, for nightly pg_cron jobs. Onlyservice_rolecan execute them. Runbetter-supabase sql addagain to update the kit files. -
Security fixes in the SQL kit. Rerun
better-supabase sql addfor the modules you installed to apply them:create_invitationno longer lets an admin invite someone asowner; only an owner or the service role can. The service-role check readsauth.jwt() ->> 'role'instead of the deprecatedauth.role(), andinvitations.rolegets the same check constraint asmemberships.role.accept_invitationrequires the signed-in user's address inauth.usersto be confirmed, not only anemailclaim. An unconfirmed user gets the hintINVITATION_EMAIL_UNCONFIRMED.anoncan no longer callhas_org_role, and the pgTAP kit'stests.create_useris granted toauthenticatedandservice_roleonly.- The tenant module adds
member_org_ids(roles), a set-returning helper. Write policies asorg_id in (select better_supabase.member_org_ids()), which Postgres evaluates once per statement instead of once per row. - Deduplicated jobs get a partial index on
dedupe_keyin each queue table, soenqueue_jobno longer scans the queue while it holds the advisory lock. triggerSqlputs the realtime trigger function in thebetter_supabaseschema, which the Data API does not expose, instead ofpublic.
better-supabase gennames a composite foreign key that repeats a column on both sides, such as(customer_id, organization_id)referencing(id, organization_id), after the remaining column: the relation iscustomer, as it would be for a plaincustomer_idkey. Schemas with such keys get new relation names; settables.<name>.relationsto keep the old ones. -
createMcptakesallowedHosts, which rejects requests whoseHostheader names another host (DNS rebinding protection, next toallowedOrigins), andresourceDocumentation, published as RFC 9728resource_documentationin the protected resource metadata. -
next.cached()takestagsandlife.stale.tagsadds cache tags to the entry next tobs:session:<user id>, andlife.stalecaps the stale timesessionStalecomputes, sonext.cached({ tags: [snapshotTag(sub)], life: cacheLifeFor(snapshot) })caches a PermDock snapshot no longer than the token or the snapshot.next.invalidateSession(userId, { tags })also expires the extra tags. PermDock can now drop the "Planned in better-supabase" note in itsguides/next-cache-components.mdx. -
Doctor and
genread PermDock'spermdock.manifest.jsonandpermissions.catalog.json(paths set bypermdock.manifestandpermdock.catalogin the config). BS407 recognizes PermDock's hook by the manifest or its-- permdock:hook v1marker, treats functions insupabase.hook.claimsas the hook's own sources, flags a wrapper that writes those claims again, and reports an info finding whenpermdock.config.tshas no manifest. BS405 takes PermDock's budget from the manifest. The new BS214 reports bucket and topic policies that pass a permission withrowConditions: trueto PermDock's helpers,genrefuses to write such bucket policies, anddefineBucketanddefineTopicthrow for those keys when given the catalog ascatalog. The MCP recipe narrowstool.metawith PermDock'sisPermissionbeforecanandmayUse. -
Support the Supabase CLI's pg-delta engine and native local stack. When
supabase/config.tomlsets[experimental.pgdelta] enabled = true,better-supabase sql addand doctor (BS304, BS305, BS404 and--fix-grants) namesupabase db schema declarative syncinstead ofsupabase db diff, BS404 asks for the grants in the schema file that defines the hook, and the declarative schema files are read fromdeclarative_schema_pathin name order, since pg-delta ignoresschema_paths.better-supabase envfalls back tosupabase status --envwhen[experimental] stack = truemakessupabase status -o jsonfail. -
createPostgresapplies Supabase's role timeouts per transaction:statement_timeout8 s forasUserand 3 s foranon, becauseset roleskips the role's own setting.statementTimeouttakes a number for every role or one value per role (admin,authenticated,anon). New options:idleInTransactionTimeout,connectionTimeoutandidleTimeout(both default to 10 s). Each transaction now sets its timeouts, claims and role in one query afterbegin. -
createPostgres({ pool })runs on an existingpg.Poolor any object withconnect()andend(), typed as the newPgPoolandPgPoolClientexports ofbetter-supabase/postgres.list.parse()now reads a typedListQueryInputsuch as{ page: 2, size: 10 }instead of treating it as URL search params and falling back to page 1, and a non-stringqsuch as{ q: 5 }reportsMust be textinstead of being accepted.contextFromSupabasethrows aTypeErrorfor an auth mode it does not know instead of returning it as the request context. The standards page lists the conformance test behind each adopted standard. -
Doctor reads the declarative schemas in
[db.migrations] schema_pathsorder, then the files no entry matches, then the migrations newest first, and the built-inconfig.tomlparser reads arrays over several lines.sql addnames the kit files noschema_pathsentry matches, becausesupabase db diffwould skip them.doctor --fix-grantsprints the grant and revoke SQL BS404 asks for as one block to append to the migrationsupabase db diffwrote. For PermDock's hook, BS404 points topermdock supabase hook generate --grants-outinstead, and when a-- permdock:grants v1migration already grants the function, it says to apply the migrations. -
Breaking: time values in the public API are now
Temporalvalues instead ofDateobjects and epoch numbers.- The
codecs.timestamptzoption takes'instant'instead of'date'.timestamptzcolumns decode toTemporal.Instant,timestampcolumns toTemporal.PlainDateTime, and both keep microseconds. Rename the option and runbetter-supabase gen. - The
nowoptions ofdefineSupabase, plugin hooks,toCloudEvents,forwardMutations,verifyWebhookandbucket.sweepreturn aTemporal.Instant. Job.enqueuedAt,Job.visibleUntil,InboxMessage.receivedAt,EnqueueOptions.runAt, the verified webhooktimestampand thesignWebhooktimestampareTemporal.Instant.bucket.sweep({ olderThan })takes aTemporal.Durationor aTemporal.Instantinstead of milliseconds.- TypeScript 5.9 is no longer supported, because it has no Temporal lib. Use TypeScript 6 or 7.
On Node 24, Safari and other runtimes without a native
Temporal, installtemporal-polyfilland importtemporal-polyfill/globalonce at startup. Without it, the calls that needTemporalreturn aDbErrorthat names the import. Auth keeps itsnowoption in epoch milliseconds. - The
-
The PermDock docs and the plugins skill reference match current PermDock. With
supabase.hook.claims: { features: 'better_supabase.feature_claims' }inpermdock.config.ts, PermDock's hook writes thefeaturesclaim, sohasEntitlement(session, ...)works next to PermDock. The MCP recipe answersvisiblewith PermDock'smayUse, and the Storage and Realtime pages point to the catalog'srowConditionsandpermdock doctorPD037 for permissions the helpers don't fully check. -
Two public types no longer rely on DOM-only globals. The
headersoption ofproblem()takes what the globalHeadersconstructor accepts, and the JSON Web Keys inbetter-supabase/testinguse thenode:cryptotype, so both resolve in a project whoselibleaves out"DOM". -
The
better-supabaseskill's schema workflow now asks for RLS, policies, policy indexes and Data API grants on every new table, and points to Supabase's own skills. The CLI asks for an access token scoped to the project when it reads a hosted project. -
better-supabase genuses@supabase/postgrest-typegen0.3.1, which still produces the samedatabase.types.tsassupabase gen typesfrom Supabase CLI 2.119. Version 0.4.0 adds aComputedFieldskey that the Supabase CLI does not emit yet, so it waits until the CLI catches up. The optional@supabase/configpeer now accepts 0.11.
0.2.0 (2026-09-30)
-
createMcptakes optional per-tool authorization hooks.authorize(ctx, tool, args)runs after the arguments are validated and beforerun, and returns{ allowed: true }or{ allowed: false, reason?, scopes? }. A refusal is a tool error, and a refusal withscopesis a 403insufficient_scopechallenge that lists the scopes the call needs.visible(ctx, tool)filterstools/list, and a hidden tool is called like an unknown one.defineToolandmcp.toolaccept an opaquemeta, for example a PermDock permission, which both hooks receive and clients never see. New types:ToolRefandToolDecision. The PermDock guide has a recipe that checks PermDock permissions through a structural type. -
Align with PermDock's authorization contract, so a project can use better-supabase and PermDock on the same claims. The migration guide at https://bettersupabase.com/docs/migration/0.1-to-0.2 lists every step.
Breaking changes:
- The active tenant claim is
tenant_idinstead oforg_id, in the token and inapp_metadata. The newclaimsblock inbetter-supabase.config.ts(claims: { tenant, scope, features }) renames it for the tenant plugin, the SQL kit, storage and realtime at once.plugins.tenant.claimis removed. - SQL kit:
better_supabase.current_org_id()is nowcurrent_tenant_id().membership_claims()moves to the tenant module and returns PermDock's[{ scope, id, roles }]. Plan features move out of memberships intofeature_claims()in the entitlements module, which fills thefeaturesclaim ({ [tenantId]: string[] }). MembershipClaimhas PermDock's shape (scope,id,roles, and optionalwithin,via,expiresAt).hasEntitlementandEntitlementKeyread thefeaturesclaim.asUsersigns ES256 tokens with the key frombetter-supabase keys(signing_keys_pathinsupabase/config.toml), like a hosted project.{ alg: 'HS256' }keeps the shared secret and only works against a local stack.SPEC_PINS.mcpandMCP_PROTOCOL_VERSIONare2026-07-28.createMcpserves stateless requests (server/discover, request_meta,Mcp-MethodandMcp-Nameheaders) and still answersinitializefor2025-11-25,2025-06-18and2025-03-26clients. A 403 carries aninsufficient_scopechallenge.- BS405 measures the whole token against 2 KB and, when the project has a
permdock.config.ts,membershipsplusattrsagainst PermDock's 1 KB budget (doctor.claimsLimitoverrides the budget, or the whole-token limit without PermDock).
New:
sb.userMetadata(schema)parsesuser_metadatainto a typedsession.profilefor display. Metadata that fails the schema leavesprofileundefined and logs one warning with the failing paths. No authorization code reads it.ProfileOf<B>inbetter-supabase/reacttypesuseSessionfromcreateHooks.- Buckets take a PermDock policy (
{ permdock: { read, write }, scope }) and topics apermdock: { receive, send, scope }option. The generated policies check PermDock permissions through itspermitted_<scope>_ids()orpermdock_has()helpers instead of the tenant claim. sql add tenantstops when apermdock.config.tsexists, unless you pass--force. Doctor BS407 reports a hook that callsmembership_claimsor writes PermDock's claims next to PermDock.better-supabase/testingexportssignLocalJwt,localSigningKey,signTestJwtWithKeyand theSigningJwktype.- A new docs page, https://bettersupabase.com/docs/auth/permdock, shows both packages in one project.
- The active tenant claim is
-
Doctor BS405 now measures what PermDock's budget covers. With a
permdock.config.ts, it warns whenmembershipsplusattrsfrom the hook's output pass 1024 bytes (ordoctor.claimsLimit), measured withoctet_lengthas PermDock's hook measuressupabase.hook.budget. The whole-token check at 2048 bytes is a separate warning, so a normal PermDock token of about 1.5 KB no longer trips it. Without PermDock,doctor.claimsLimitstill limits the whole token.memberships_truncatedis reported as before. -
Entitlements are no longer treated as a PermDock conflict, because
featuresis not a PermDock claim.- Doctor BS407 reports a custom access token hook next to PermDock only when it calls
better_supabase.membership_claimsor writesroles,user_role,membershipsor the configured tenant claim itself. It no longer reportsfeature_claims, and it leaves PermDock's generated hook alone. sql add entitlementsworks next to apermdock.config.tswithout--force. It writestenantas a dependency and prints a note. Onlysql add tenantstill needs--force.- The PermDock and entitlements docs say what works today.
has_entitlement(tenant, key)andtenant_entitlements(tenant)work in SQL and RLS without a claim.hasEntitlement(session, ...)needs thefeaturesclaim, which PermDock's hook doesn't write yet, so read entitlements from the database on the server until PermDock adds a hook slot for it.
- Doctor BS407 reports a custom access token hook next to PermDock only when it calls
-
The PermDock guide lists every claim PermDock's generated hook writes (
user_role,roles,memberships, the tenant claim,attrs,authz_verandmemberships_truncated). The migration guide and thesb.userMetadata()TSDoc say thatsession.profileis for display only, and that roles, memberships, the tenant and entitlements never come from it. -
The storage and realtime docs say that the
permdockpolicy mode compares ids as text, so a path or topic segment must be the id's canonical lowercase form: an uppercase uuid is denied. An integration test covers it for buckets and topics. -
The docs now name the right PermDock command for the SQL helpers.
permdock_hasandpermitted_<scope>_idscome frompermdock rls generate, not frompermdock supabase hook generate. The PermDock guide gains a setup step that runs both commands, and says that the helpers live in PermDock'srls.schema, which must equal theschemaoption on buckets and topics. -
Document that the
permdockpolicy mode for buckets and topics only fits permissions whose grants have no row conditions beyond the scope. PermDock's helpers check role and scope, so a permission with row conditions (for exampleownerId = principal.id) would grant every object in the scope. Leave those to the policiespermdock rls generatewrites. The storage, realtime and PermDock docs pages show a wrong and a right example, and the TSDoc on thepolicyandpermdockoptions says the same. -
The PermDock guide says that a non-default
claims.tenantmust also be set as PermDock'srls.tenantClaimand passed tosubjectFromSupabaseorsubjectFromSupabaseSessionas{ tenant }, so both packages read and write the same tenant claim. -
The docs site answers questions with Ask AI, shows the last-updated date on every page, and has Open Graph images, a sitemap, type tables generated from the source, and links that add the docs MCP server to Cursor and VS Code. The repository now has a root
CHANGELOG.md, and its fixture schema is declarative, with pgTAP tests for RLS. The published package does not change.
Every release of better-supabase, newest first. pnpm version-packages adds a
section from the pending changesets. Releases up to 0.1.0 are listed in
packages/better-supabase/CHANGELOG.md.
Last updated on