Tags
Tag definitions per kind, applied to subjects through one table or a link table per subject.
tags keeps definitions (kind, name, slug, color) and applies them to records. Applying or removing a tag needs tags.apply (or tags.manage) in the tenant, the subject's own read permission, and a tag kind the subject allows. When the record type declares a tag action in config.recordTypes (such as tag: "task.update"), applying or removing a tag also needs that action on the record, so a key, a per-row grant or the record's owner decides who may tag it.
With the drive installed, drive_node subjects follow the node's grants: reading a node's tags needs read access, and tagging or untagging needs write access, which is how the drive's labels work.
| Permission | Checked by | Default roles |
|---|---|---|
tags.read | list | owner, admin, member |
tags.apply | attach, detach | owner, admin, member |
tags.manage | create, update, reorder, delete, and every check above | owner, admin |
blocks.tags.permissions can split manage by action: create checks
create, update and reorder check update, and delete checks delete.
An action you leave unset checks the manage key, so a config without them
behaves as before:
export default defineConfig({
blocks: {
tags: {
permissions: {
read: "tag.read",
create: "tag.create",
update: "tag.update",
delete: "tag.delete",
},
},
},
});better-supabase add tagsimport { createTags } from "better-supabase/blocks/tags";In managed mode every application lives in taggings (subject_type, subject_id). Over your own tables, each subject can name its own link table (below).
Every call acts in the block's tenant, an organization id or a function that returns the current one; createBlocks and createBlockClient pass the request's tenant, and a call without one fails with invalid_request and the hint TENANT_REQUIRED. A record is a RecordRef, { type, id }.
Server code calls the tags instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useTags } = defineDataHooks(
"tags",
(db: AppDb) => db.tags,
);const customer = { type: "customer", id: customerId };
const vip = await db.tags
.create({ kind: "customer", name: "VIP", color: "amber" })
.orThrow();
await db.tags.attach(customer, vip.id).orThrow();
const onCustomer = await db.tags.list({ on: customer }).orThrow();"use client";
import { useTags } from "@/lib/supabase/hooks";
const rows = useTags({ limit: 50 });create({ kind, name, color?, description?, fields? }) creates a tag of a kind, and update(id, { name?, fields? }) renames it or sets its extra columns. With blocks.tags.options.patch: true, create also takes slug (lowercase letters and digits joined by single hyphens, TAG_SLUG_INVALID otherwise; derived from the name when left out), and update takes slug, kind, color and description: it changes the keys you pass and keeps the others, and null clears color or description. In SQL they are the slug argument of create_tag and the patch jsonb argument of update_tag; without the option neither exists. attach(record, tagId) and detach(record, tagId) put a tag on a record and take it off. list({ kind? }) returns the tenant's tags of a kind (every kind without one) in rank order, for a caller with tags.read or tags.manage. list({ on: record }) returns the tags on one record, for a caller who can also read the record. They call list_tags and subject_tags.
In the browser
useTagInput is a registry item: npx shadcn add @better-supabase/use-tags writes hooks/use-tags.ts into the app. The hook loads a record's tags and every tag of a kind for suggestions through the provider's client. add(tagId) and remove(tagId) show the change at once and take it back when the module refuses it. create(name) adds the tag of that kind with the same name (ignoring case), or creates it first, which needs tags.manage. The same hook runs in React DOM and React Native.
import { useTagInput } from "@/hooks/use-tags";
const { tags, available, add, remove, create } = useTagInput({
subject: { type: "customer", id: customer.id },
kind: "customer",
});The hook calls the schema and function names in the blocks config passed to the browser client (createClient(betterSupabase, { blocks: blockConfig })), so it takes no schema, and acts in the client's tenant: the client's organization option, then the session's organization claim. It waits while there is no tenant or subject is null.
createTagInputController from better-supabase/blocks/tags is the same logic without React. Vue, Svelte and Solid run it with useBlockController from better-supabase/vue, /svelte and /solid (see Block controllers), passing the controller's options: a client built with its organization, and subject. The tag input recipe shows it in the Next.js and Expo examples.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import { rpcTransport } from "better-supabase/blocks";
import {
createTagInputController,
createTags,
} from "better-supabase/blocks/tags";
const props = defineProps<{ organizationId: string; customerId: string }>();
const supabase = useSupabase();
const { state, actions } = useBlockController(createTagInputController, {
client: createTags({
transport: rpcTransport(supabase),
schema: "api",
tenant: props.organizationId,
}),
subject: { type: "customer", id: props.customerId },
kind: "customer",
});
</script>
<template>
<button
v-for="tag in state.tags"
:key="tag.id"
@click="actions.remove(tag.id)"
>
{{ tag.name }}
</button>
</template><script lang="ts">
import { betterSupabase, useBlockController } from "better-supabase/svelte";
import { rpcTransport } from "better-supabase/blocks";
import { createTagInputController, createTags } from "better-supabase/blocks/tags";
let { organizationId, customerId }: { organizationId: string; customerId: string } = $props();
const { supabase } = betterSupabase();
const tags = useBlockController(createTagInputController, {
client: createTags({
transport: rpcTransport(supabase),
schema: "api",
tenant: organizationId,
}),
subject: { type: "customer", id: customerId },
kind: "customer",
});
</script>
<p>{$tags.tags?.map((tag) => tag.name).join(", ")}</p>import { useBlockController, useSupabase } from "better-supabase/solid";
import { rpcTransport } from "better-supabase/blocks";
import {
createTagInputController,
createTags,
} from "better-supabase/blocks/tags";
export function CustomerTags(props: {
organizationId: string;
customerId: string;
}) {
const supabase = useSupabase();
const { state } = useBlockController(createTagInputController, {
client: createTags({
transport: rpcTransport(supabase),
schema: "api",
tenant: props.organizationId,
}),
subject: { type: "customer", id: props.customerId },
kind: "customer",
});
return (
<p>
{state()
.tags?.map((tag) => tag.name)
.join(", ")}
</p>
);
}Tags run in every scope. In user scope each user has their own tags, and in none scope every signed-in user shares one set.
Over your own tables
tags: {
tables: { tags: "public.organization_tags" },
on: {
task: {
table: "public.tasks",
kinds: ["task"],
links: { table: "public.task_tags", subject: "task_id", tag: "tag_id" },
},
},
},links columns are subject, tag and optional memberships and createdAt. When config.recordTypes registers the record type, its entry can leave out table and idType, which come from the registry.
Your kind and subjectType columns may be enums or domains, such as kind public.organization_tag_kind: the module casts the text it writes and compares to the column's type, so an unknown kind fails with the enum's invalid input value error.
Order
Tags of a kind are ordered by rank, a fractional key (see Rank). create appends a tag after the last one of its kind, and reorder(id, { previous, next }) moves it between the tags with those keys. Version 2 of the module replaced the integer position column with rank: the upgrade backfills keys in the old order and drops position. On a table of your own rank is optional: map it to null when you don't want the column, and the module otherwise adds it.
move({ id, toIndex, kind? }) puts a tag at position toIndex (0 is first) among the tags of kind, or all tags without it, and returns its new rank key. It reads the list and calls reorder with the neighbours.
Your own columns
Add columns to the tag table with alter table ... add column in your own schema files
(column name to SQL type), then pass a Standard Schema for them as fields.
create and update (the last argument) validates and writes them, and create return them parsed under
fields. A column whose type is not null without a default is written in
the insert itself, so create can set a required column. The block also takes hooks around its methods; see
extending blocks.
import { createTags } from "better-supabase/blocks/tags";
import { z } from "zod";
const client = createTags({
transport,
fields: z.object({ priority: z.enum(["low", "high"]) }),
});Without the client
db.tags is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const tags = createTags({ transport, tenant: organizationId });
const customer = { type: "customer", id: customerId };
const vip = await tags
.create({ kind: "customer", name: "VIP", color: "amber" })
.orThrow();
await tags.attach(customer, vip.id).orThrow();
const onCustomer = await tags.list({ on: customer }).orThrow();Replace a record's tags
replace({ record, tagIds }) reads the tags on the record, attaches the ones that are missing and detaches the others, and returns { attached, detached }. It stops at the first failure.
await db.tags.replace({ record, tagIds: [vip.id, lead.id] }).orThrow();Paging tags
page pages tags by keyset. Sorts are rank (the default), name, kind and createdAt. The filter and facet is kind, and q searches the name, the slug and the description. facets and count read under the same filters, and get(tagId) returns one tag or a not_found error. list stays as a deprecated alias for the capped array. The SQL functions are page_tags and get_tag.
const page = await tags
.page({ filters: { kind: ["label"] }, q: "vip" })
.orThrow();Last updated on