Flags SDK
Declare flags with the Vercel Flags SDK and evaluate them from the flags block, per user, per tenant and per custom context such as a brand, with precompute and Flags Explorer.
better-supabase/flags-sdk connects the Flags SDK
to the flags block. You declare flags with flag()
from flags/next, and the adapter answers them from the flags table with
the same rules, overrides and rollout buckets as flag_enabled() in your
policies.
pnpm add flags
pnpm better-supabase add flagsflags is an optional peer (>=4.5.0 <5). The entry types the SDK
structurally and never imports it, so it adds nothing to a bundle that
doesn't use it, and a type test fails when a new flags release changes the
Adapter shape. The entry imports no Node built-ins, so it runs in
proxy.ts.
| Export | Does |
|---|---|
betterSupabaseAdapter | a ready adapter that reads SUPABASE_URL and SUPABASE_SECRET_KEY on first use |
createBetterSupabaseAdapter | an adapter over your own project, transport or definitions, with origin and identify |
createIdentify | an identify that returns the user, the tenant, a visitor and custom contexts from a token |
getProviderData | Flags Explorer data for every stored flag, joined with the flags your code declares |
flagOptions | a flag's variants as options, which a precomputed flag needs |
flagContextOf | the evaluation context the adapter builds from the entities |
The Next.js example wires all of them.
Declaring flags
Pass betterSupabaseAdapter to flag() the way the Flags SDK's own
adapters are passed. It reads SUPABASE_URL (or NEXT_PUBLIC_SUPABASE_URL)
and SUPABASE_SECRET_KEY when the first flag is decided, not at import, and
loads every flag with flag_definitions(), which only the service role may
call. Never prefix that key with NEXT_PUBLIC_.
import "server-only";
import {
betterSupabaseAdapter,
type FlagsSdkEntities,
} from "better-supabase/flags-sdk";
import { flag } from "flags/next";
export const newEditor = flag<boolean, FlagsSdkEntities>({
key: "new_editor",
adapter: betterSupabaseAdapter,
defaultValue: false,
});Without the keys, a flag answers its defaultValue and one without a
default throws. To pick the project, the Data API schema or the cache
yourself, call createBetterSupabaseAdapter. It takes url and
secretKey (with schema, ttl, staleTtl and fetch), or the options of
createFlagsProvider: a transport or fixed definitions. Give it an
identify so every flag on it identifies the caller the same way:
import "server-only";
import {
createBetterSupabaseAdapter,
createIdentify,
type FlagsSdkEntities,
} from "better-supabase/flags-sdk";
import { dedupe, flag } from "flags/next";
import { bsb } from "@/lib/supabase/server";
export const identify = dedupe(
createIdentify({
server: bsb,
visitor: ({ cookies }) => cookies.get("visitor-id")?.value,
contexts: ({ headers }) => ({ brand: brandOf(headers.get("host")) }),
}),
);
export const bsFlags = createBetterSupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL!,
secretKey: process.env.SUPABASE_SECRET_KEY!,
schema: "api",
origin: "https://admin.acme.test/flags/{key}",
identify,
});
export const newEditor = flag<boolean, FlagsSdkEntities>({
key: "new_editor",
adapter: bsFlags,
defaultValue: false,
});The adapter keeps one definitions cache (30 seconds by default) and one
adapterId, so evaluate([...]) decides a batch from one load. A flag that is missing,
has another type or fails to load answers the declaration's
defaultValue, so a database outage turns features off instead of
breaking the page. Without a defaultValue, decide throws.
A variant whose value is null is served only when defaultValue is
null or left out. With a null default, any other value must match the
flag's type; with another default, it must have the default's type. A flag whose default variant is
missing from its variants is treated as missing, not as null. A row
whose type is not one the table allows never serves its variants; it
always answers the fallback.
origin tells Flags Explorer where each flag is managed: a URL in which
{key} is replaced by the flag key, or a function of the key.
Identifying the caller
createIdentify builds on flagContext.
It returns these entities:
| Entity | Holds |
|---|---|
user | { id }, the user id from the claims |
organization | { id, plans, roles }, the active tenant with its features and roles |
visitor | { id }, a signed-out visitor's id, only when there is no user |
brand, ... | { id } for each custom context, named as in blocks.flags.options.contexts |
Pass server (the object createNext or createServer returns) and
createIdentify reads the session from the request's cookie or bearer
token. It verifies the token locally and never refreshes it, so it never
calls the Auth server; refreshing stays in the proxy. Pass claims instead
to return claims you verified yourself. visitor gives a signed-out request
a stable rollout bucket: the user id is the targeting key, and the visitor
id stands in without one. Set the cookie it reads in the proxy. tenant
picks the active tenant when the claims
don't carry it, and contexts adds custom context values from a header,
the host or a cookie. contextClaims from flagContext also works, such as
{ brand: "brand_id" }. Wrap the result in dedupe so it runs once per
request.
The entity names are the ones Vercel Flags targets (user.id,
organization.id, brand.id), so one identify serves both adapters. Move
a flag to Vercel Flags by changing its
adapter:
import { vercelAdapter } from "@flags-sdk/vercel";
export const checkoutTheme = flag<string, FlagsSdkEntities>({
key: "checkout_theme",
adapter: vercelAdapter(),
defaultValue: "classic",
identify,
});The flags block is still what policies check, so keep a flag that guards data in the flags block.
While some flags live in each place, Flags Explorer needs both lists from one
discovery route. mergeProviderData from flags combines the provider data
of both adapters:
import { getProviderData } from "better-supabase/flags-sdk";
import { getProviderData as getVercelProviderData } from "@flags-sdk/vercel";
import { createFlagsDiscoveryEndpoint, mergeProviderData } from "flags/next";
import { bsFlags, newEditor } from "@/flags";
export const GET = createFlagsDiscoveryEndpoint(() =>
mergeProviderData([
getProviderData(bsFlags, { flags: { newEditor } }),
getVercelProviderData({
edgeConfigConnectionString: process.env.EDGE_CONFIG,
}),
]),
);Precompute
A precomputed flag
is evaluated once in proxy.ts, and the request is rewritten to a static
page for that combination of values. List the flag's options so
generatePermutations knows every combination; flagOptions(definition)
builds them from a flag's variants.
import { precompute } from "flags/next";
import { pricingFlags } from "./flags";
if (path === "/pricing") {
const code = await precompute(pricingFlags);
return NextResponse.rewrite(new URL(`/pricing/${code}`, request.url));
}import { generatePermutations } from "flags/next";
import { pricingBanner, pricingFlags } from "@/flags";
export async function generateStaticParams() {
const codes = await generatePermutations(pricingFlags);
return codes.map((code) => ({ code }));
}
export default async function Pricing({
params,
}: PageProps<"/pricing/[code]">) {
const { code } = await params;
const banner = await pricingBanner(code, pricingFlags);
return (
<>
{banner ? <UpgradeBanner /> : null}
<FlagValues values={{ [pricingBanner.key]: banner }} />
</>
);
}The page never reads cookies or headers, so each code is a static page.
Read a per-user flag in a page without a [code] segment instead, inside a
<Suspense> boundary with a skeleton. FlagValues from
flags/react tells Flags Explorer and Vercel Analytics which values the
page was built with.
precompute signs the code with FLAGS_SECRET, a random 32-byte base64url
string. Set it in every environment
(node -e "console.log(crypto.randomBytes(32).toString('base64url'))").
With Cache Components, generateStaticParams must return at least one
code, so an app that builds without the secret returns one fixed code there
and renders the flags' defaults for it, as the example does.
Precompute only flags with a few values per visitor: a brand, a plan, a rollout bucket. A per-user flag multiplies the permutations, and a static page built for one user's variant can reach another user. Read those flags dynamically.
Dashboard pages
On a signed-in page, read the flag at request time, as in the dashboard pages guide:
const showEditor = await newEditor();The flag only decides what the page shows. Keep the data behind it in a
policy with flag_enabled() or tenant_ids_with_flag(), so a request that
skips the page still meets the same flag:
create policy "drafts_insert" on public.drafts for insert to authenticated
with check (better_supabase.flag_enabled('new_editor', organization_id));The adapter and flag_evaluation() agree, with one difference: the adapter
never reads a custom context from the tenant table, so pass it through
identify when a rule targets it.
Flags Explorer
Flags Explorer in
the Vercel Toolbar reads the flags from a discovery route. getProviderData
lists every flag in the flags block that isn't archived, with its
description, options, origin and last change. Pass the flags your code
declares as flags, one at a time or in groups such as pricingFlags, and
it joins them: a declared flag shows its defaultValue and is marked
declared in code, and one the table lacks shows a hint.
import { getProviderData } from "better-supabase/flags-sdk";
import { createFlagsDiscoveryEndpoint } from "flags/next";
import { bsFlags, newEditor, pricingFlags } from "@/flags";
export const GET = createFlagsDiscoveryEndpoint(() =>
getProviderData(bsFlags, { flags: { newEditor, pricingFlags } }),
);The route answers only requests signed with FLAGS_SECRET. A failed load
still lists the declared flags, with a hint instead of an error, and a flag
with an unknown type shows a hint too, as does a variant whose value doesn't
match the flag's type. Exclude /.well-known/vercel/ from the proxy
matcher. An override set in the toolbar applies before the adapter's
decide.
toFlagsSdkDefinition(flag, origin) turns one stored flag into the
definition Flags Explorer shows, and origin may be a URL or an object
such as { provider: "better-supabase", projectId }, or a function of the
key. flagDrift(declared, stored) lists the keys your code declares that the
table lacks (notStored) and the ones the table has that no code declares
(notDeclared); archived flags count as neither. Run it in a test to catch
a flag someone deleted while code still reads it.
Outside Next.js
flagsDiscoveryHandler(getData, { verify }) is the discovery route as a
(request: Request) => Promise<Response>, for any framework with web
requests. It answers 401 unless verify accepts the Authorization header,
and otherwise sends the data with cache-control: no-store and, given
version, the x-flags-sdk-version header. Pass verifyAccess from
flags:
import {
flagsDiscoveryHandler,
getProviderData,
} from "better-supabase/flags-sdk";
import { verifyAccess } from "flags";
const discovery = flagsDiscoveryHandler(() => getProviderData(bsFlags), {
verify: (header) => verifyAccess(header ?? "", process.env.FLAGS_SECRET),
});
app.get("/.well-known/vercel/flags", (c) => discovery(c.req.raw));import { FLAGS_SECRET } from "$env/static/private";
import {
flagsDiscoveryHandler,
getProviderData,
} from "better-supabase/flags-sdk";
import { verifyAccess } from "flags";
const discovery = flagsDiscoveryHandler(() => getProviderData(bsFlags), {
verify: (header) => verifyAccess(header ?? "", FLAGS_SECRET),
});
export const GET = ({ request }) => discovery(request);overrideEncryptionMode defaults to encrypted, which is what the toolbar
writes when FLAGS_SECRET is set. Pass plaintext for an app that reads
overrides without decrypting them.
Overrides on the OpenFeature path
flag() reads the toolbar's vercel-flag-overrides cookie itself. Code
that evaluates through the OpenFeature provider reads it with
explorerOverrides(cookies, { decrypt }) and wraps the provider for that
request with withExplorerOverrides. An overridden flag of the asked type
resolves with the reason OVERRIDE; any other flag evaluates as usual:
import {
explorerOverrides,
withExplorerOverrides,
} from "better-supabase/flags-sdk";
import { decryptOverrides } from "flags";
const overrides = await explorerOverrides(await cookies(), {
decrypt: (value) => decryptOverrides(value),
});
const client = createFlagClient(withExplorerOverrides(provider, overrides));decrypt is yours to pass, so better-supabase never loads flags for it.
Without one, the cookie is read as plaintext JSON. These overrides apply to
server code only: flag_enabled() in a policy never sees a browser cookie.
Testing with overrides
flagOverrideCookie(values) from better-supabase/testing builds the cookie
Flags Explorer would set, so an end-to-end test serves the variants it needs
without the toolbar:
import { flagOverrideCookie } from "better-supabase/testing";
import { encryptOverrides } from "flags";
const cookie = await flagOverrideCookie(
{ checkoutTheme: "compact" },
{ encrypt: (values) => encryptOverrides(values) },
);
await context.addCookies([{ ...cookie, url: baseURL }]);Leave out encrypt when the app reads plaintext overrides. For a request
in a unit test, send cookie.header as the cookie header.
Environments
vercelEnvironmentContext() returns { environment } from VERCEL_ENV
(or NODE_ENV outside Vercel), for a rule that turns a flag on in preview
only. Merge it into identify, and target it with a rule such as
{ variant: "on", contexts: { environment: ["preview"] } }.
Running without FLAGS_SECRET
Flags 4.5 works on Vercel without a FLAGS_SECRET. Flags Explorer overrides
and the discovery endpoint use tokens that Vercel signs, and precompute signs
its codes with a key Vercel provides for each deployment. Locally, run
vercel env pull so the SDK can identify the project, and make sure the
project exposes the system environment variables on Vercel. Nothing in
better-supabase reads FLAGS_SECRET itself, so the flags block, identify
and flagsExplorerApiData need no change. Projects that already have a
secret keep working.
You still need a FLAGS_SECRET to precompute flags outside Vercel or in a
prebuilt deployment (vercel build and vercel deploy --prebuilt), to use
Flags Explorer outside Vercel or without vercel env pull, and to create
your own encrypted overrides, for example in end-to-end tests.
Reporting exposures
flag() reports each value to Vercel Web Analytics when the page renders
<FlagValues> from flags/react, or when you pass the values to
track() from @vercel/analytics; custom events then carry the flags the
visitor saw. On the OpenFeature path, createFlagsProvider({ onEvaluate })
sees each evaluation. To send evaluations elsewhere, wrap the adapter. This one sends PostHog's
$feature_flag_called event:
import type { FlagsSdkAdapter } from "better-supabase/flags-sdk";
function reported<V>(adapter: FlagsSdkAdapter<V>): FlagsSdkAdapter<V> {
return {
...adapter,
async decide(params) {
const value = await adapter.decide(params);
posthog.capture({
distinctId: params.entities?.user?.id ?? "anonymous",
event: "$feature_flag_called",
properties: {
$feature_flag: params.key,
$feature_flag_response: value,
},
});
return value;
},
};
}For OpenTelemetry, record a feature_flag.evaluation event with
feature_flag.key and feature_flag.result.value on the active span in the
same place.
Not built in
These are left to the app or to other tools for now:
- Self-serve previews that a tenant admin turns on. Build them as a flag with tenant overrides that your settings page writes.
- Scheduled changes other than a rollout. A rollout follows
rolloutSchedule(see scheduled rollouts); for anything else, runflags.upsertfrom a job. - Approval before a change. A
savehook can require one (see extending blocks). - Experiments and metrics. Use PostHog or Statsig through their own Flags SDK adapters.
- Brands as a table of their own. A brand is a custom context read from your tenant table (see custom contexts).
Last updated on
The inbox on eve
Hand inbox conversations in bot mode to eve, run their tools as a service user, send replies as bot messages or ai drafts, and accept channel events without Chat SDK.
Vercel Sandbox
Give each chat its own Vercel sandbox, recorded in the AI chat block's sandbox registry, stopped when idle, and locked down with network presets.