Custom domains
Hostnames an organization serves your app on, its own domains verified by a DNS TXT record and subdomains of your platform domain, with a lookup the proxy runs on every request.
domains lets each organization serve your app on its own hostnames: a custom domain such as app.acme.com, verified by a DNS TXT record, or a subdomain such as acme.yourapp.com, which is verified when added. Each organization can mark one verified hostname as primary, and your proxy looks up the organization behind a request's Host header with resolve.
A hostname here says where your app is served. It does not decide who may join an organization; verified email domains for that live in SSO.
Listing hostnames needs domains.read, and adding, removing or choosing the primary one needs domains.manage. Admins get both, and members get domains.read.
better-supabase add domainsThe module needs memberships and access. With reserved-slugs installed, subdomains go through its slug check.
Server code calls the domains instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useDomains } = defineDataHooks(
"domains",
(db: AppDb) => db.domains,
);import { createDomains } from "better-supabase/blocks/domains";
const hostname = await db.domains.add(organizationId, "app.acme.com").orThrow();
// hostname.record: {
// type: "TXT",
// name: "_better-supabase.app.acme.com",
// value: "better-supabase-hostname-verification=3f1c...",
// }"use client";
import { useDomains } from "@/lib/supabase/hooks";
const rows = useDomains({ limit: 50 });Show the record to the organization's admin, who publishes it at their DNS provider and points the hostname at your app (a CNAME or the address your host gives you). The record stays on the hostname until it is verified, so the settings page can show it again.
Paging a list
list is the capped convenience list. page is the full contract for hostnames (ADR 0749, 0939): it takes organizationId, which names the organization per call, and sort, filters whose values are lists (a row matches any of a filter's values), after and limit, and returns { items, hasMore, nextCursor }. Pass the nextCursor back as after. The sorts are hostname and createdAt; the default order is the primary first, then hostname. The filters are kind and verified ("true" or "false"). The facets are kind and verified. list(organizationId) and page need domains.read; list returns at most 200 hostnames. A cursor belongs to the sort it came from, so start again from the first page when sort or direction changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error.
const verified = await domains
.page({
organizationId,
filters: { verified: ["true"] },
sort: { by: "hostname" },
limit: 20,
})
.orThrow();
// How many hostnames are custom or subdomains, and how many match.
const facets = await domains.facets({ organizationId }).orThrow();
const total = await domains.count({ organizationId }).orThrow();Verification
verify_hostname is granted to the service role only. createDomainsAdmin looks up the TXT record over DNS-over-HTTPS (Cloudflare's resolver by default) and marks the hostname verified once the value is there. Pass actorId when a user asked for the check, so the database confirms they hold domains.manage.
import { createDomainsAdmin } from "better-supabase/blocks/domains";
const admin = createDomainsAdmin({ transport: serviceTransport });
const result = await admin.verify({ hostnameId, actorId: user.id });
// DOMAIN_RECORD_MISSING until DNS has the recordRun it from a button on the settings page, or from a job that retries until the record appears. Pass resolver to look up TXT records another way. Verification proves the organization controls the hostname; your host still has to serve it, so pass a hosting platform provider to add the domain to your project in the same flow.
Only one organization can hold a verified hostname. Several can claim one while it is pending, and the first to verify it wins, so a pending claim can't block the real owner.
Hosting platforms
Pass a provider to createDomainsAdmin and the admin client also adds each hostname to the project that serves your app, waits for the platform to verify it, and removes it again. vercelDomainProvider is the provider for a Vercel project. It calls the Vercel SDK client you pass:
pnpm add @vercel/sdk@vercel/sdk is an optional peer (>=1.28.67 <2). Use a Vercel access token that can manage the project's domains, and keep it on the server.
import { createClient } from "@supabase/supabase-js";
import { Vercel } from "@vercel/sdk";
import {
createDomainsAdmin,
rpcTransport,
vercelDomainProvider,
} from "better-supabase/blocks/domains";
export const domainsAdmin = createDomainsAdmin({
transport: rpcTransport(
createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SECRET_KEY!,
),
),
provider: vercelDomainProvider(
new Vercel({ bearerToken: process.env.VERCEL_TOKEN! }),
{
projectId: process.env.VERCEL_PROJECT_ID!,
// Leave teamId out for a project on a personal account.
teamId: process.env.VERCEL_TEAM_ID!,
},
),
});Add the hostname to Vercel when the block records hostname.added, and remove it on hostname.deleted. The deleted row is gone by then, so remove takes the hostname from the event instead of its id:
import { domainsEvents } from "better-supabase/blocks/domains";
import { onBlockEvent } from "better-supabase/events";
import { domainsAdmin } from "./domains-admin";
import { bsb } from "./supabase/server";
onBlockEvent(bsb, domainsEvents, "hostname.added", async (event) => {
const added = await domainsAdmin.add({ hostnameId: event.data.hostnameId });
if (!added.ok) {
console.error("Vercel did not add the hostname", added.error);
}
});
onBlockEvent(bsb, domainsEvents, "hostname.deleted", async (event) => {
const removed = await domainsAdmin.remove({ hostname: event.data.hostname });
if (!removed.ok) {
console.error("Vercel did not remove the hostname", removed.error);
}
});The handlers only observe: a failed call never undoes the block's write. Run the calls from a job instead when they must be retried.
add returns verified and records: the DNS records the platform still asks for, such as the TXT record Vercel needs when the domain is in use on another Vercel account. Show them next to the block's own TXT record. Adding a hostname that is already on the project returns its status. status({ hostnameId }) reads it again for the settings page, and returns undefined when the hostname isn't on the project.
With a provider, verify checks the TXT record first and then asks the platform to verify the hostname; only when both pass does it mark the hostname verified. A subdomain has no TXT record, so only the platform check runs. Until the platform has verified it, verify fails with DOMAIN_PROVIDER_UNVERIFIED, and the message names the records still missing:
const result = await domainsAdmin.verify({ hostnameId, actorId: user.id });
// DOMAIN_RECORD_MISSING until DNS has the block's TXT record
// DOMAIN_PROVIDER_UNVERIFIED until Vercel has verified the domainErrors from Vercel come back as DbErrors: forbidden for a token without access, rate_limited with retryAfter, and network with DOMAIN_PROVIDER_FAILED when Vercel can't be reached. Without a provider, verify works as before, and add, remove and status fail with DOMAIN_PROVIDER_MISSING.
Write your own provider
For another platform, implement DomainProvider: apiVersion: 1, a name, and add, verify, remove and status, each taking the hostname and returning an AsyncResult. remove returns false and status returns undefined for a hostname the platform doesn't have, and verify reports verified: false instead of failing while the platform's checks don't pass. testDomainProvider from better-supabase/testing runs that contract against your provider and a test project:
import { testDomainProvider } from "better-supabase/testing";
const report = await testDomainProvider(cloudflareDomains, {
hostname: "conformance.example.com",
});Platform subdomains
Set platformDomain to your app's own domain, and one label below it becomes a subdomain that is verified when added:
export default defineConfig({
blocks: { domains: { options: { platformDomain: "yourapp.com" } } },
});add(organizationId, "acme.yourapp.com") returns a verified subdomain hostname. yourapp.com itself and deeper names such as a.b.yourapp.com are refused. txtPrefix (default _better-supabase) sets the record name's first label, such as _yourapp-verify.
The proxy
resolve(host) returns the organization behind a verified hostname, or undefined. It is open to anon callers, since the proxy runs before sign-in, and it returns nothing a DNS lookup doesn't already show. It ignores the port and the case of the Host header.
import { createClient } from "@supabase/supabase-js";
import { createDomains, rpcTransport } from "better-supabase/blocks/domains";
import { type NextRequest, NextResponse } from "next/server";
const domains = createDomains({
transport: rpcTransport(
createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
),
),
});
export async function proxy(request: NextRequest) {
const found = await domains.resolve(request.headers.get("host") ?? "");
if (!found.ok || found.data === undefined) {
return NextResponse.next();
}
const { organizationId, primary, primaryHostname } = found.data;
if (!primary && primaryHostname !== undefined) {
const url = request.nextUrl.clone();
url.host = primaryHostname;
url.port = "";
return NextResponse.redirect(url, 308);
}
const url = request.nextUrl.clone();
url.pathname = `/o/${organizationId}${url.pathname}`;
return NextResponse.rewrite(url);
}Cache the answer for a minute or so when every request goes through the proxy: a hostname changes owner only when it is removed and verified again.
Errors
| Hint | Cause |
|---|---|
DOMAIN_FORBIDDEN | the caller lacks domains.manage or domains.read |
DOMAIN_INVALID | not a hostname, or more than one label below the platform domain |
HOSTNAME_RESERVED | the platform domain itself, or a subdomain reserved-slugs refuses |
DOMAIN_TAKEN | another organization has verified this hostname |
DOMAIN_NOT_FOUND | no hostname the caller manages has this id |
DOMAIN_NOT_VERIFIED | only a verified hostname can be primary |
DOMAIN_RECORD_MISSING | verify found no TXT record with the value yet |
DOMAIN_PROVIDER_UNVERIFIED | the hosting platform hasn't verified the hostname yet |
DOMAIN_PROVIDER_CONFLICT | the hostname is on another project of the platform account |
DOMAIN_PROVIDER_FAILED | the hosting platform couldn't be reached or answered with an error |
DOMAIN_PROVIDER_MISSING | add, remove or status on an admin client created without provider |
Events
The block records hostname.added, hostname.verified, hostname.primary_changed and hostname.deleted with organizationId, hostnameId and hostname, and writes them to the audit log under configuration. See events.
The block takes hooks around its methods, such as a rule on how many hostnames a plan may add; see extending blocks.
Without the client
db.domains is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createDomains } from "better-supabase/blocks/domains";
const domains = createDomains({ transport });
const hostname = await domains.add(organizationId, "app.acme.com").orThrow();
// hostname.record: {
// type: "TXT",
// name: "_better-supabase.app.acme.com",
// value: "better-supabase-hostname-verification=3f1c...",
// }Check the DNS
With vercelDomainProvider, status and a verified verify also ask Vercel
whether the hostname's DNS points at the project. The result carries
misconfigured and dns (cname and ipv4, the records Vercel recommends,
lowest rank first), so the page can show the records to set. The check needs
domains.getDomainConfig in the SDK you pass in, which @vercel/sdk has; an
SDK without it returns the status as before.
Last updated on
Identities
Link an email address or a chat user to an app user or a contact, through a one-time code the signed-in user issues or a confirmed address.
Compliance
Compliance frameworks and controls with evidence files and notes, recurring evidence tasks with assignees and an overdue state, versioned policies that members acknowledge, and a status rollup per framework.