Profiles
A profile row per user, created on sign-up from auth metadata, with a unique username, an email mirror and columns users can't change.
The profiles SQL module gives every user a profile
row. A trigger on auth.users creates it on sign-up from the user's
metadata, allocates a unique username and keeps the email in step with
auth.users. Users update their own name and avatar through the Data API,
while the email, the active organization and disabled_at stay with the
server.
pnpm better-supabase add profilesWhat sign-up fills in
sync_profile(user_id) runs after each insert into auth.users. When the
user has no profile yet, it inserts one:
| Column | From |
|---|---|
full_name | metadata full_name, then name, then the first and last name joined |
first_name | metadata first_name, then given_name, then the first word of the full name |
last_name | metadata last_name, then family_name, then the rest of the full name |
avatar_url | metadata avatar_url, then picture |
email | auth.users.email in lowercase, and again after every change of address |
username | metadata user_name, preferred_username or username, else the email's local part |
avatar_path is never filled from metadata, and a metadata option that
names it is refused. It holds the Storage object path of an avatar the user
uploads (<user id>/avatar.webp in a public bucket), so a provider picture
in avatar_url never overwrites it. Users update it like their name, and
update_my_profile writes it. The Next.js example uploads to an avatars
bucket, saves the object path in avatar_path and shows avatar_url when
the user has no upload.
locale is a BCP 47 tag such as nl-NL, empty until the user sets it. Users
update it like their name, and the notifications
block renders email and push deliveries in it. Over your own profiles table,
map columns: { locale: "language" } to an existing column; an app that
already adds a locale column keeps that column, and
notifications reads it.
Your locale column may be an enum or a domain, such as
locale public.app_locale. The module writes it through
better_supabase.as_column_type and notifications reads it as text, so
update_my_profile with a label the enum lacks fails with Postgres error
22P02. When options.metadata maps a metadata key to locale, a sign-up
whose value the type rejects gets a null locale through
better_supabase.try_column_type, as it would without the key, so the
sign-up never fails on it. Keep that column nullable or leave it out of
metadata.
The generated types follow the column: db.profiles rows carry the enum's
labels as a union ("en" | "nl" | "de"), and fields on createProfiles
types the same union on mine().
Usernames are lowercased, stripped to a-z, 0-9 and _ (plus the .
or - of a usernameFrom separator), start with a letter, and get a number suffix while the name is reserved or another
profile has it (ada, then ada1). allocate_username(base) returns a
free one for a "pick a username" form. On a managed table, a check
constraint applies the same rules to names users pick themselves: the
length limits, the characters and reservedUsernames (admin, api,
support, www and similar by default). The check is declared not valid, so
Postgres enforces it on every new and changed row and leaves existing rows
alone; run alter table ... validate constraint bsb_profiles_username_check
yourself once no profile breaks it.
After the module creates a profile, it calls your after_profile_sync(user_id)
SQL hook when it exists, to create rows
that hang off the profile. It doesn't call the hook for users who already
had a profile.
A failure while creating the profile, in the insert or in the hook, never
blocks the sign-up. The user gets an account without a profile, Postgres
logs a warning with the error, and select better_supabase.backfill_profiles()
as the service role creates the missing profiles once the cause is fixed.
Run it once after installing on a project that already has users.
The active organization and team columns exist only next to the memberships
and teams blocks. An app with no organizations gets neither column, and the
service-column guard leaves them out.
Who can change what
| Rule | Default |
|---|---|
| Read | your own profile; with readPolicy: 'members', the public columns of everyone who shares an organization with you |
| Update | your own row, only the columns in updatable |
| Service columns | email, disabled_at, the active organization and team, created_at; a trigger refuses changes from the API roles with PROFILE_COLUMN_READONLY |
| Insert and delete | the service role and auth.users (rows are deleted with their user) |
With readPolicy: 'members', authenticated gets select on the public
columns only, so select them by name instead of *. email, the active
organization and team and onboarding stay private: read your own through
better_supabase.my_profile(), which returns your full row as jsonb.
update_my_profile(attrs) updates the updatable columns present in
attrs. createProfiles from better-supabase/blocks/profiles calls both:
Server code calls the profiles instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useProfiles } = defineDataHooks(
"profiles",
(db: AppDb) => db.profiles,
);import { createProfiles } from "better-supabase/blocks/profiles";
const row = await db.profiles.mine().orThrow();
await db.profiles.updateMine({ full_name: "Ada Lovelace" }).orThrow();"use client";
import { useProfiles } from "@/lib/supabase/hooks";
const rows = useProfiles({ limit: 50 });Pass a Standard Schema as fields to type your own columns (a column you add,
or any column of an adopted table): mine() parses the row
with it and updateMine validates the columns it sets. hooks refuses,
rewrites or observes mine and updateMine. In SQL,
before_profile_update(attrs jsonb, user_id uuid) runs before every update
and can raise to refuse it, and after_profile_update(user_id uuid) runs
after a change. See Extending blocks.
const profiles = createProfiles({
transport,
fields: z.object({ locale: z.enum(["en", "nl"]) }),
});
const profile = await profiles.mine().orThrow();
profile?.locale; // "en" | "nl"On a table the block creates, the guard also sets updated_at. Over a
profiles table of your own, the guard neither checks nor writes the column:
update_my_profile sets it, and your own trigger keeps it current for other
writes.
Security definer functions, such as switch_organization from the
organizations module and the email mirror, write the
service columns. To disable users through the profile, point the access
contract at its column:
blocks: {
permissions: { disabled: { user: "better_supabase.profiles.disabled_at" } },
profiles: {},
},Options
blocks.profiles.options:
| Option | Default | What it does |
|---|---|---|
metadata | the keys in the table above | metadata key to column name; replaces the defaults |
splitName | true | fills first and last name from a full name |
username | true | allocates a username on sign-up |
usernameFrom | ["user_name", "preferred_username", "username"] | metadata keys tried before the email, or { names, separator } and { columns, separator } entries (see below) |
usernameMinLength | 3 | shorter names become user |
usernameMaxLength | 32 | the longest name, suffix included |
reservedUsernames | admin, api, support, www and more | names nobody gets; allocation adds a suffix |
updatable | name, avatar, username, onboarding and your columns | the columns users can update |
avatarSource | "url" | "path" makes the author of a comment or upload carry avatarPath (the Storage path) instead of avatarUrl |
columnGrants | true when managed | revokes update and grants it on updatable only |
serviceColumns | see above | the columns only the service changes; [] drops the guard. updated_at is never guarded |
readPolicy | self | members also shows profiles of people in the same organizations (needs tenant); see below |
syncTrigger | true | false leaves sign-up to your own trigger, which calls sync_profile |
mirrorEmail | true | keeps email equal to auth.users.email |
An entry of usernameFrom can join several metadata keys when all of them
are set, so a "first_last" convention is a setting:
profiles: {
options: {
usernameFrom: [
{ names: ["first_name", "last_name"], separator: "_" },
"user_name",
],
},
},Ada Lovelace becomes ada_lovelace; a user without a last name falls back to
user_name, then the email. allocate_username still lowercases, strips and
suffixes the result, and keeps a . or - separator, which the username
check then also accepts.
{ columns, separator } joins the values the profile's own columns get
instead, after metadata and splitName. A sign-up that only sends
full_name: "Grace Hopper" becomes grace.hopper:
profiles: {
options: {
usernameFrom: [{ columns: ["first_name", "last_name"], separator: "." }],
},
},readPolicy also takes { members, platform }. platform is a permission
key that is_platform() checks, so platform staff read every profile, which
admin consoles need. It writes its own policy, bsb_profiles_platform_read,
on a managed table and on yours, and pulls in the permissions module. Column grants
still apply, so the private columns stay behind them.
profiles: { options: { readPolicy: { members: true, platform: "platform.user.read" } } },Existing profiles
When your schema already has a profiles table, the module skips its
create table, adds the columns it needs that your table lacks and writes
its functions, policies and triggers over it. Map the key and the columns you
have, and set the optional ones you don't want to null:
blocks: {
profiles: {
tables: { profiles: "public.profiles" },
columns: {
profiles: {
key: "user_id",
fullName: null,
avatar: null,
avatarPath: "avatar_path",
activeTenant: "active_organization_id",
onboarding: null,
},
},
callbacks: {
schema: "public",
functions: { after_profile_sync: "create_contact_profile" },
},
options: { syncTrigger: false, usernameMaxLength: 30 },
},
},If a trigger of yours already creates profiles (handle_new_user),
installing warns about it. Keep it and set syncTrigger: false, calling
better_supabase.sync_profile(new.id) from it, or drop it and move its
extra work into after_profile_sync. With ownership: "custom" the module
writes nothing and you provide sync_profile and backfill_profiles.
On your table, map avatarPath to null to go without the column; the
module adds it otherwise.
Avatar and logo uploads use the avatarBucket and organizationLogoBucket
presets.
Without the client
db.profiles is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createProfiles } from "better-supabase/blocks/profiles";
const profiles = createProfiles({ transport });
const row = await profiles.mine().orThrow();
await profiles.updateMine({ full_name: "Ada Lovelace" }).orThrow();Setting the avatar
setAvatar({ path }) points the profile at an object path the app already stored, and null clears it. setAvatar({ file }) uploads through options.avatarUploader: it receives the file, the previous path and a commit(path) function, and returns the result of its own upload. Without an uploader, setAvatar({ file }) fails with invalid_request.
const profiles = createProfiles({
transport,
avatarUploader: ({ file, previous, commit }) =>
replaceAvatar(file, previous).andThen((path) => commit(path)),
});
await profiles.setAvatar({ file }).orThrow();The column defaults to avatar_path; set avatarColumn to use another. Both forms go through mine and updateMine, so their hooks run.
Last updated on