API keys
Hashed API keys for tenants and users, with scopes, expiry, rotation, a rate limit per key and an apiKey caller in every server adapter.
The api-keys block issues keys your customers call your API with. A key
looks like bs_0f3a9c2e7b1d4a68_<secret><checksum>: a prefix, a public id, a
43-character base62 secret and the 6-character CRC-32 checksum of everything
before it. Only the SHA-256 of the secret is stored, so a database dump holds no
usable key, and the token is shown once when the key is created. The checksum
lets verify and secret scanners reject a mistyped or made-up key without a
database lookup; keys created before it (no checksum) still verify.
Set the prefix to your product's, such as acme, with createApiKeys({ prefix })
and blocks.api-keys.options.prefix, so scanners and support can tell your
keys apart. It is bs by default.
better-supabase add api-keys # adds tenant and access as wellA key acts in one of three ways:
| Key | Created with | Acts as |
|---|---|---|
| Tenant key | organizationId | The tenant: api_key_tenant() is its id |
| Personal key | personal: true | The user who created it |
| Personal key limited to a tenant | personal: true and organizationId | The user, only while they are still a member |
Creating a tenant key needs api_keys.manage in the tenant; a personal key
in a tenant needs api_keys.own. A personal key without a tenant acts in
every tenant its user belongs to, so it needs api_keys.own in each of them;
a user without any membership can still create one. The default roles give
admin both and member the second. API keys are never part of a
data export; the purge still deletes a
tenant's keys. Rename the keys with blocks.api-keys.permissions.
Managing keys
Server code calls the api-keys instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useApiKeys } = defineDataHooks(
"apiKeys",
(db: AppDb) => db.apiKeys,
);const rows = await db.apiKeys.list({ limit: 50 }).orThrow();"use client";
import { useApiKeys } from "@/lib/supabase/hooks";
const rows = useApiKeys({ limit: 50 });rotate returns a new token and keeps the old one working for the grace
period (one day by default), so a deployment can switch over. revoke stops
the key at once. A key manager (api_keys.manage) may revoke any key of the
tenant, but a personal key (one with a user) is rotated only by its own user or
the service role, because the new secret acts as that user; anyone else gets
API_KEY_FORBIDDEN.
Every key that create, list and rotate return has a state, computed
with the database clock, so a list shows a rotated key as still working
while its grace period runs:
state | The key |
|---|---|
active | authenticates |
grace | was rotated and authenticates until revokedAt |
revoked | was revoked, or its grace period ended |
expired | passed its expiresAt |
A rotated key also has successorId, the id of the key that replaced it.
Key kinds
A key's kind says what it is for. List the kinds in
blocks.api-keys.options.kinds, and a check constraint on the kind column
refuses any other. Without the option, kind takes any value. A key created
without a kind has none, and rotate copies it.
blocks: {
"api-keys": { options: { kinds: ["client", "admin", "export", "feed"] } },
},const { token } = await keys
.create({
name: "Warehouse sync",
organizationId,
kind: "export",
scopes: ["deals:read"],
})
.orThrow();list and verify return the kind, so a settings page can group keys by
kind and a route can turn away a key of the wrong kind.
In the browser
useApiKeys lists an organization's keys newest first through the provider's client, with the
same rules as list. create({ name, personal }) keeps the new key and
its token in created until dismiss(), the only time the token is shown,
and revoke(id) revokes a key; both load the list again and return a
Result. Without an organization the hook lists and creates the caller's
personal keys. The same hook runs in React DOM and React Native. It is a
registry item: install it with npx shadcn add @better-supabase/use-api-keys,
which writes hooks/use-api-keys.ts into the app.
import { useApiKeys } from "@/hooks/use-api-keys";
const { keys, created, create, revoke, dismiss } = useApiKeys({
organizationId,
schema: "api",
});onChanged runs after a key was created or revoked, such as a server
action that completes an onboarding step. createApiKeysController from
better-supabase/blocks/api-keys is the same logic without React. Vue,
Svelte and Solid run it with useBlockController from better-supabase/vue,
/svelte and /solid (see
Block controllers). The API keys table recipe
shows it in the Next.js and Expo examples.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createApiKeys,
createApiKeysController,
rpcTransport,
} from "better-supabase/blocks/api-keys";
const props = defineProps<{ organizationId: string }>();
const supabase = useSupabase();
const { state, actions } = useBlockController(createApiKeysController, {
client: createApiKeys({ transport: rpcTransport(supabase), schema: "api" }),
organizationId: props.organizationId,
});
</script>
<template>
<p v-for="key in state.keys" :key="key.id">
{{ key.name }}
<button @click="actions.revoke(key.id)">Revoke</button>
</p>
</template><script lang="ts">
import {
betterSupabase,
useBlockController,
} from "better-supabase/svelte";
import {
createApiKeys,
createApiKeysController,
rpcTransport,
} from "better-supabase/blocks/api-keys";
let { organizationId }: { organizationId: string } = $props();
const { supabase } = betterSupabase();
const keys = useBlockController(createApiKeysController, {
client: createApiKeys({ transport: rpcTransport(supabase), schema: "api" }),
organizationId,
});
</script>
<p>{$keys.keys?.length ?? 0} keys</p>import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createApiKeys,
createApiKeysController,
rpcTransport,
} from "better-supabase/blocks/api-keys";
export function ApiKeys(props: { organizationId: string }) {
const supabase = useSupabase();
const { state } = useBlockController(createApiKeysController, {
client: createApiKeys({ transport: rpcTransport(supabase), schema: "api" }),
organizationId: props.organizationId,
});
return <p>{state().keys?.length ?? 0} keys</p>;
}Accepting keys
apiKeyResolver reads the x-api-key header, or a Bearer token shaped like
a key, and turns it into an apiKey caller. A Bearer token that starts with
the key prefix and _ counts as a key even when the rest is malformed, so
bs_bad_key answers INVALID_API_KEY like a revoked or unknown key instead
of failing JWT verification. Requests without a key fall through to the
usual JWT and cookie resolution. Verification runs as the service role, so
give the resolver a service transport:
import { createPostgres } from "better-supabase/postgres";
import {
apiKeyResolver,
createApiKeys,
sqlTransport,
} from "better-supabase/blocks/api-keys";
const postgres = createPostgres({ connectionString: env.SUPABASE_DB_URL });
const keys = createApiKeys({ transport: sqlTransport(postgres.admin) });
export const bsb = createHono(betterSupabase, {
postgres,
auth: { resolvers: [apiKeyResolver({ keys })] },
});
app.use(
"/api/deals/*",
bsb.middleware({ allow: ["user", "apiKey"], scopes: ["deals:read"] }),
);The guard checks scopes against the key's scopes; * grants every scope.
An invalid, expired or revoked key answers 401, and a key over its rate limit
answers 429 with Retry-After. A personal key also answers 401 while its user
is disabled, banned in Supabase Auth (auth.users.banned_until in the future)
or soft-deleted, the same as the user's sign-in. Each verification counts against the key's
limit and updates last_used_at at most once a minute
(blocks.api-keys.options.touchInterval, in seconds).
The apiKey caller carries createdAt (a Temporal.Instant) and
createdBy (the creating user's id) when the key row has them, so a guard or
an authorization check can tell who issued the key. toSession returns
createdAt in epoch seconds, like the session's other times.
There is no JWT for an API key, so PostgREST can't run its queries on its
own. ctx.db and ctx.sql run over direct Postgres instead (pass postgres
to the server, or see Without direct Postgres),
with these claims and the key's tenant as better_supabase.tenant:
{
"sub": "<user id, or empty for a tenant key>",
"role": "authenticated",
"api_key": {
"id": "…",
"name": "CI",
"organization_id": "…",
"scopes": ["deals:read"]
}
}ctx.supabase and ctx.db.$client throw for an API key caller.
authMode (for withSupabase entries) is user for a personal key and
secret for a tenant key.
Without direct Postgres
A serverless API that reaches the database only through PostgREST passes
apiKeyToken instead of postgres. apiKeyTokenSigner signs the same claims
as a short-lived ES256 JWT (60 seconds by default), once per request, and
ctx.db and ctx.supabase send it as the Bearer token, so RLS and the scope
ceiling apply as they do over Postgres. The key's tenant goes in the
x-bsb-tenant header, and ctx.sql is undefined.
import {
apiKeyResolver,
createApiKeys,
rpcTransport,
} from "better-supabase/blocks/api-keys";
import { apiKeyTokenSigner } from "better-supabase/server";
const keys = createApiKeys({ transport: rpcTransport(adminClient) });
export const bsb = createHono(betterSupabase, {
apiKeyToken: apiKeyTokenSigner({ key: JSON.parse(env.API_KEY_SIGNING_JWK) }),
auth: { resolvers: [apiKeyResolver({ keys })] },
});PostgREST accepts the token only when the project trusts its key. Import the
private P-256 key as a standby key under JWT signing keys and leave it there:
the project publishes it in its JWK Set without signing sessions with it.
Locally, add it to the file signing_keys_path names. Keep the private key
in a server-only secret. With postgres set, queries keep running over
Postgres and apiKeyToken is not called. The createOrpc and createMcp
adapters read the same context, so they serve API keys this way too.
When your own code routes a Bearer token to either API key or JWT
verification, ask keys.isApiKey(token) instead of matching the prefix by
hand. It answers true for any token with the configured prefix and _,
well formed or not, and keys.verify answers invalid for one that doesn't
parse:
const token = authorization.replace(/^Bearer\s+/i, "");
if (keys.isApiKey(token)) {
const checked = await keys.verify(token).orThrow();
// checked.status is "ok", "invalid" or "rate_limited"
} else {
// verify the JWT
}On the @supabase/server pipeline
A REST API built on @supabase/server's pipeline takes keys with
withApiKey in place of withSupabase. It verifies the key, answers a
missing, invalid or rate-limited key with Problem Details (problem sets
your error format), and contributes ctx.auth and the withSupabase keys
(jwtClaims, userClaims, authMode) from the key's claims, so
withPostgresClient runs each query as the key:
import { pipeline } from "@supabase/middleware";
import { withPostgresClient } from "@supabase/server/middleware/postgres";
import {
createApiKeys,
sqlTransport,
withApiKey,
} from "better-supabase/blocks/api-keys";
import { withBetterPostgres } from "better-supabase/server";
export default {
fetch: pipeline(
[
withApiKey({ keys }),
withPostgresClient(),
withBetterPostgres(betterSupabase)(),
],
async (_request, ctx) =>
Response.json(await ctx.sql.deals.list().orThrow()),
),
};In RLS
A personal key runs as its user, so existing policies apply. Add
has_scope() where a policy should also respect the key's scopes; it is
true for requests without a key. Wrap both functions in (select ...), as
below, so Postgres calls them once per statement instead of once per row. A
tenant key has no user, so give it its own policy:
create policy deals_read_with_key on public.deals for select to authenticated
using (
organization_id = (select better_supabase.api_key_tenant())
and (select better_supabase.has_scope('deals:read'))
);Paging keys
keyPage pages by keyset (ADR 1077), with keyFacets and keyCount. list stays as a deprecated alias until 0.70. Without an organizationId the page lists the caller's personal keys. With one it lists the tenant's keys for its managers and the caller's own keys for everyone else. Filters are userId and revoked (["true"] or ["false"]), q searches the name and the prefix, and the sorts are createdAt, name, expiresAt and lastUsedAt. Your own fields are read on every row. There is no get, because the secret hash never leaves the database and a key is read through verify.
const active = await apiKeys
.keyPage({ organizationId, filters: { revoked: ["false"] }, q: "ci" })
.orThrow();A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
SQL
| Function | Grants | Returns |
|---|---|---|
create_api_key(name, public_id, hash, ...) | authenticated, service_role | The key, without its hash |
list_api_keys(tenant) | authenticated, service_role | Keys the caller may see |
revoke_api_key(key) | authenticated, service_role | true |
rotate_api_key(key, public_id, hash, grace) | authenticated, service_role | The new key |
verify_api_key(public_id, hash) | service_role | { status: 'ok', key }, invalid or rate_limited |
has_scope(scope) | everyone | Whether the request's key carries scope (or has no key) |
api_key_tenant() | everyone | The tenant of the request's key, or null |
Restrict the scopes keys may carry with blocks.api-keys.options.scopes
(a list); create_api_key then refuses any other with API_KEY_SCOPE_UNKNOWN.
With an authorization provider,
scopes: "catalog" takes the list from the provider's permissions, so a
key's scopes are the same permission keys your guards and policies check, and
add fails when the provider lists none.
create_api_key refuses an
interactive-only
permission key, such as organization.transfer_ownership, as a scope with
API_KEY_FORBIDDEN. The access functions never grant one to a key, so a key
created before this check gets nothing from it.
An API key, OAuth client or agent (a JWT with api_key, client_id or
act) that may create keys only gives a new or rotated key the scopes it
holds itself: the key's own scopes (or any under *), or the permission keys
its OAuth scopes map to. Anything broader fails with API_KEY_FORBIDDEN. A
signed-in user's own session is not limited this way.
Scopes narrow permissions
A key holds only the permissions its scopes map to. cap_allows, which
member_can, can and every policy and module that asks them apply, checks
the permission against the key's scopes (or the keys those scopes map to in
blocks.permissions.scopes). A scope of * holds every permission except the
interactive-only ones, and a key with no scopes holds none. A personal key
therefore no longer acts with every permission of its user, and a policy
needs has_scope() only for scopes that are not permission keys.
Before 0.61 a key held every non-interactive permission its user had. To migrate, list the keys whose access would shrink and give each the scopes it needs, or rotate it with new scopes:
select id, name, scopes from better_supabase.api_keys where scopes = '{}';
update better_supabase.api_keys
set scopes = array['deals.read', 'deals.update']
where id = '...';With options.scopes: "catalog" the scopes are the permission keys
themselves, so a key's scopes read as the exact list of what it may do.
With an authorization provider
Queries for a key run with the api_key claim. A provider's SQL functions
can read a claim too, to make the key's scopes a ceiling or to treat a tenant
key as a service principal of its tenant. Pass claim to the resolver (or to
apiKeyClaims) so the request also carries the fields the provider reads:
apiKeyResolver({
keys,
claim: {
name: "authz_key",
tenant: "organization_id",
serviceRoles: ["integration"],
},
allPermissions: permissionKeys,
tenantClaim: "tenant_id",
});| Field | Default | Meaning |
|---|---|---|
name | required | the claim; api_key adds the fields to the module's own claim |
scopes | scopes | the field with the key's permission keys |
tenant | tenant | the field with a tenant key's tenant |
roles | roles | the field with a tenant key's roles |
serviceRoles | none | the roles a tenant key holds, unless the serviceRoles option answers per key |
claims adds claims of your own for each key, such as one read from its
kind or from an extra column. It cannot set sub, role,
aud or api_key, or the claims the other options write; TypeScript refuses
those names, and the resolver drops them. With fields, the hook and
serviceRoles receive the key with its parsed columns.
apiKeyResolver({
keys,
serviceRoles: (key) => (key.kind === "admin" ? ["admin"] : ["integration"]),
claims: (key) => ({ key_kind: key.kind ?? "client" }),
});A personal key limited to a tenant also gets tenantClaim, the claim that
narrows the provider's functions to one tenant. The claim has no wildcard:
* expands to allPermissions, and without it a key with * allows nothing
there or in has_scope(). Under the provider access model create_api_key
refuses * (API_KEY_SCOPE_WILDCARD) unless options.scopes lists it, and
options.scopes: "catalog" keeps every scope a permission key the provider
lists.
A provider's server package can verify the block's keys for its own
middleware: keys.verify(token) resolves to { status: "ok", key } with
the key's user or tenant and its scopes, invalid or rate_limited.
Your own fields
Columns you add to api_keys with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createApiKeys a Standard Schema
for them as fields: create (rotate copies them) take them next to the block's own keys and
validate them (a bad value is a validation error), and list, verify return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createApiKeys({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.apiKeys is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createApiKeys, rpcTransport } from "better-supabase/blocks/api-keys";
const keys = createApiKeys({ transport: rpcTransport(supabase) });
const { key, token } = await keys
.create({
name: "CI",
organizationId,
scopes: ["deals:read"],
expiresAt: Temporal.Now.instant().add({ hours: 24 * 90 }),
rateLimit: 600, // requests per minute
})
.orThrow();
// Show `token` once; `key` has everything else.
await keys.list(organizationId); // the tenant's keys for managers, the caller's own otherwise
await keys.rotate(key.id, { grace: Temporal.Duration.from({ hours: 1 }) });
await keys.revoke(key.id);Last updated on