Settings
Per-user and per-organization settings with a Standard Schema per key, defaults, typed get and set, and matching pg_jsonschema checks.
The settings block stores preferences as key-value rows: one table for each
user's own settings and one for organization settings. You declare the keys
once with a Standard Schema each (Zod, Valibot, ArkType), and the block gives
you typed get, set and reset that validate before they write.
better-supabase add settings # adds tenant and access as well| Table | Key | Who reads | Who writes |
|---|---|---|---|
user_settings | (user_id, key) | the user | the user |
organization_settings | (organization_id, key) | members with settings.read | members with settings.update |
platform_settings | key | each key's read rule | each key's platform permission |
The default roles give admin both permissions and member the first.
Rename them with blocks.settings.permissions. Both tables keep
updated_by and updated_at, and the functions run as the caller, so the
row level security policies decide every read and write.
Declaring settings
import { toStandardJsonSchema } from "@valibot/to-json-schema";
import { defineSettings } from "better-supabase/blocks/settings";
import * as v from "valibot";
export const settings = defineSettings({
user: {
theme: {
schema: toStandardJsonSchema(v.picklist(["light", "dark", "system"])),
default: "system",
},
digest: { schema: v.object({ weekly: v.boolean() }) },
},
organization: {
defaultRole: {
schema: toStandardJsonSchema(v.picklist(["member", "viewer"])),
default: "member",
},
},
});A key without a default reads as undefined until it is set. A stored
value that no longer matches its schema (after you narrow an enum, for
example) also reads as the default, so old rows never break a page.
Resolving per legal entity
With the legal entities block, resolve
reads an organization key for one legal entity: its own value, else the
organization's, else the key's default. Without legalEntityId the
organization's default legal entity answers.
const footer = await db.settings
.resolve(orgId, "invoiceFooter", { legalEntityId })
.orThrow();Reading and writing
createSettings takes the definition as settings and returns typed
get, set and reset methods for each scope:
Server code calls the settings instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useSettings } = defineDataHooks(
"settings",
(db: AppDb) => db.settings,
);const rows = await db.settings.list({ limit: 50 }).orThrow();"use client";
import { useSettings } from "@/lib/supabase/hooks";
const rows = useSettings({ limit: 50 });With defineBlocks, pass the definition
through using:
settings: settingsBlock.using((options) =>
createSettings({ ...options, settings }),
),hooks run around every method, such as an audit line on
setOrganization:
const client = createSettings({
settings,
transport,
hooks: {
setOrganization: {
after: (result, [organizationId, key]) => {
if (result.ok) log.info("setting changed", { organizationId, key });
},
},
},
});The settings tables take no app columns: each value is typed by its key's schema.
setUser returns a validation error with the schema's issues when the value
doesn't match, and an invalid_input error for a key you didn't declare;
neither reaches the database. Use sqlTransport(postgres.asUser(claims))
instead of rpcTransport to call the functions over Postgres. With
rpcTransport, set blocks.settings.api to an exposed schema such as
api and pass rpcTransport(supabase, { schema: "api" }); see
SQL modules.
Settings pages
useSettings is a registry item: npx shadcn add @better-supabase/use-settings writes hooks/use-settings.ts into the app.
The hook edits one scope of the definition through the provider's client, so
a settings page can be
generated from it. fields lists the keys in declaration order, each with
a kind (boolean, number, text, choice or json), its choices,
and the title and description from the schema. They come from the
schema's Standard JSON Schema: Zod implements
it, and toStandardJsonSchema from @valibot/to-json-schema adds it to a
Valibot schema. For a schema without it, the kind follows the default's
type. The same hook runs in React DOM and React Native.
import { toStandardJsonSchema } from "@valibot/to-json-schema";
import { defineSettings } from "better-supabase/blocks/settings";
import * as v from "valibot";
export const settings = defineSettings({
organization: {
defaultRole: {
schema: toStandardJsonSchema(
v.pipe(v.picklist(["member", "admin"]), v.title("Default role")),
),
default: "member",
},
},
});import { useSettings } from "@/hooks/use-settings";
import { settings } from "@/lib/settings";
const { fields, values, saving, setField } = useSettings(settings, {
scope: "organization",
organizationId,
schema: "api",
});
// fields: [{ key: "defaultRole", kind: "choice", choices: ["member", "admin"], ... }]set(key, value) takes the key's typed input, and setField(key, value)
takes whatever a generated control produces; both validate with the key's
schema first and keep a failure in error. reset(key) goes back to the
default. createSettingsController and settingFields from
better-supabase/blocks/settings are the same logic without React. Vue,
Svelte and Solid run the controller with useBlockController from
better-supabase/vue, /svelte and /solid (see
Block controllers),
passing the scope's entries and its client. The settings layout recipe shows it in
the Next.js and Expo examples.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createSettings,
createSettingsController,
rpcTransport,
} from "better-supabase/blocks/settings";
import { settings } from "@/lib/settings";
const supabase = useSupabase();
const { state, actions } = useBlockController(createSettingsController, {
entries: settings.schemas.user,
user: createSettings({ settings, transport: rpcTransport(supabase) }),
});
</script>
<template>
<label v-for="field in state.fields" :key="field.key">
{{ field.title ?? field.key }}
<input
:value="state.values?.[field.key]"
@change="actions.setField(field.key, $event.target.value)"
/>
</label>
</template><script lang="ts">
import { betterSupabase, useBlockController } from "better-supabase/svelte";
import {
createSettings,
createSettingsController,
rpcTransport,
} from "better-supabase/blocks/settings";
import { settings } from "$lib/settings";
const { supabase } = betterSupabase();
const preferences = useBlockController(createSettingsController, {
entries: settings.schemas.user,
user: createSettings({ settings, transport: rpcTransport(supabase) }),
});
</script>
{#each $preferences.fields as field}<p>{field.title ?? field.key}</p>{/each}import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createSettings,
createSettingsController,
rpcTransport,
} from "better-supabase/blocks/settings";
import { settings } from "~/lib/settings";
export function Preferences() {
const supabase = useSupabase();
const { state } = useBlockController(createSettingsController, {
entries: settings.schemas.user,
user: createSettings({ settings, transport: rpcTransport(supabase) }),
});
return <p>{state().fields.length} settings</p>;
}Platform settings
Settings for the whole product, such as fee rates, routing rules or an
announcement text an admin console edits, go in the platform scope. Each
key can name the platform permission (is_platform) that may change it and
who reads it: public (also signed out), authenticated (the default) or
staff (holders of the key's permission). Keys guarded by different
permissions share one table:
export const platformSettings = defineSettings({
platform: {
invoiceFeePercent: {
schema: v.pipe(v.number(), v.minValue(0), v.maxValue(10)),
default: 0,
permission: "platform.billing.manage",
read: "public",
},
aiDefaults: {
schema: v.object({ model: v.string() }),
permission: "platform.ai.manage",
read: "staff",
},
},
});Pass the definition as blocks.settings.options.schemas, or name it in
standardSchema({ settings: "./src/settings.ts#settings" }) and leave the
option out, so the module writes the permission and read rule of each key into the policies.
When schemas lists platform keys, only those keys can be written: a key
the config doesn't list is refused, so a typo or a stale key never lands in
platform_settings. Rows that exist without a listed key are read with
options.platform.permission (default settings.manage, renamed with
permissions.platform) and options.platform.read. Without listed keys,
any key can be written with that permission.
const admin = createSettings({
settings: platformSettings,
transport: sqlTransport(postgres.asUser(claims)),
});
await admin.setPlatform("invoiceFeePercent", 1.5).orThrow();
const fee = await admin.getPlatform("invoiceFeePercent").orThrow();A key a caller may not read comes back as its default, and a write without
the key's permission fails with forbidden.
Checks in the database
Pass the definition to the module, and keys whose schema implements
Standard JSON Schema get a
pg_jsonschema check, so writes that skip TypeScript are held to the same
shape. Zod 4 schemas implement it directly; wrap Valibot schemas in
toStandardJsonSchema:
import { defineConfig } from "better-supabase/config";
import { settings } from "./src/lib/settings.ts";
export default defineConfig({
blocks: { settings: { options: { schemas: settings } } },
});better-supabase add jsonb-schemas settingsThe checks need the jsonb-schemas module, which installs pg_jsonschema.
Each one is named bsb_json_value_<key> and applies only to rows with that
key. options.schemas also takes plain { user, organization } maps of key to
JSON Schema. An entry can also be a module reference such as
"./settings.ts#theme", which the CLI loads. Keys whose schema has no JSON Schema (digest above) are
validated in TypeScript only.
Reading a setting in SQL
Other modules' security definer functions read one organization setting with
better_supabase.organization_setting(tenant, key). It returns the stored
value as jsonb, or null when the key is not set, and checks no
permission, so the calling function decides who may see the value. Only
service_role and the module schema's owner may execute it; signed-in
callers can't.
select better_supabase.organization_setting(v_tenant, 'drive.sharing') ->> 'links';A block's SQL calls it through ctx.of("settings").fn("organization_setting"),
so it follows the app's schema and naming.
Options
| Option | Default | What it does |
|---|---|---|
schemas | none | A defineSettings() result or { user, organization, platform } JSON Schemas |
platform | { permission: "settings.manage", read: "authenticated" } | The permission and read rule of platform keys that don't set their own |
Without the client
db.settings is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createSettings, rpcTransport } from "better-supabase/blocks/settings";
import { settings } from "@/lib/settings";
const client = createSettings({
settings,
transport: rpcTransport(supabase, { schema: "api" }),
});
const theme = await client.getUser("theme").orThrow(); // "light" | "dark" | "system"
await client.setUser("theme", "dark").orThrow();
await client.resetUser("theme"); // back to the default
const all = await client.getOrganization(organizationId).orThrow();
await client.setOrganization(organizationId, "defaultRole", "viewer");Last updated on
Audit log
Record events, and list, reveal and export a tenant's audit entries as NDJSON, CSV or OCSF, and purge them per tenant's retention.
Legal entities
Several companies inside one organization, each with its VAT and chamber numbers, bank account, logo and fiscal calendar, one of them the default, and settings that fall back from the legal entity to the organization.