Credentials
Third-party tokens behind a credential reference, resolved by a CredentialProvider over Supabase Vault or Vercel Connect.
Blocks that call other services (a connector, an MCP server, a Slack bot)
never store a token in a table. A row stores a credential_ref jsonb that
names the credential, and a CredentialProvider from
better-supabase/credentials turns the ref into a token when the server
needs one. Revoking a connection is a provider call, not a schema change,
and a leaked row reveals no secret.
// A ref stored in a row
{ "provider": "vault", "secret": "github", "scope": "user" }| Provider | Subpath | Where the secret lives |
|---|---|---|
vaultCredentials(options) | better-supabase/credentials | Supabase Vault, through the credentials SQL module |
vercelConnectCredentials() | better-supabase/vercel-connect | Vercel Connect connectors |
Supabase Vault
pnpm better-supabase add credentialsThe module adds three security definer functions that only
service_role can call: credential_get(provider, name),
credential_set(provider, name, secret, description) and
credential_delete(provider, name). Secrets are stored in Vault under the
name bs:cred:<provider>:<name>. The module needs the Vault extension,
which Supabase projects have by default.
import { sqlTransport, vaultCredentials } from "better-supabase/credentials";
export const bsb = createServer(betterSupabase, {
credentials: vaultCredentials({
transport: sqlTransport(postgres.asService()),
}),
});Handlers read it as ctx.credentials:
const subject = subjectFor(ctx);
if (ctx.credentials === undefined || subject === undefined)
return unauthorized();
const token = await ctx.credentials
.getToken(row.credential_ref, { subject })
.orThrow();
await fetch(url, { headers: token.headers });subjectFor(ctx) is the signed-in user (or the user behind an API key),
the app itself for a service request, or undefined for an anonymous one.
ctx.credentials is set only when createServer gets a provider. A ref with scope: "user" holds one
secret per user; reading it without a user subject fails with the hint
CREDENTIAL_SUBJECT_REQUIRED, and a missing secret is not_found with
CREDENTIAL_NOT_FOUND. token.headers is authorization: Bearer <token>
unless the ref sets header and scheme (scheme: null sends the raw
token). Tokens are cached for cacheMs (60 seconds); set and revoke
clear the cache.
Store a secret with credentials.set(ref, value, { subject }), and remove
it with credentials.revoke(ref, { subject }).
Tenant refs
A ref on a tenant's row carries that tenant: { "provider": "vault", "secret": "github", "tenant": "<organization id>" }. Build one with
tenantCredentialRef(tenant, ref). Vault stores it as
tenant/<tenant>/<secret>, apart from every other tenant's secrets and the
app's own, so a tenant admin who picks a ref can't name another tenant's
credential. The connectors, AI providers and workflow builder blocks
reject a ref whose tenant isn't the row's tenant, in SQL and before any
provider call, with forbidden and the hint CREDENTIAL_REF_FOREIGN.
They never resolve or revoke such a ref. Only the service role may store
a ref without a tenant on a tenant's row; credentialRefInTenant(ref, tenant) is the same check for your own tables.
A provider without tenant namespaces refuses a tenant ref for the app
subject. vercelConnectCredentials does this: Vercel Connect would return
the app's own installation token for every tenant, so it resolves a tenant
ref only for a user subject, or for the tenant's own installation (see
Tenant installations).
Inbound requests
A ref with inbound verifies requests the other service sends:
standard-webhooks (Standard Webhooks signatures), hmac-sha256 (a hex
HMAC in x-hub-signature-256, or signatureHeader) or shared-secret.
credentials.verifyInbound(request, ref) resolves with true when the
request is signed with the stored secret. It reads a clone, so the handler
can still read the body.
Your own secrets table
An app that already keeps credentials in a table of its own can keep that
table: map it in tables.secrets, and the three functions read and write its rows
instead of Vault names, and keep their signatures, so vaultCredentials()
works unchanged.
export default defineConfig({
blocks: {
credentials: {
tables: { secrets: "public.integration_secrets" },
columns: {
secrets: { tenant: "organization_id", scope: "user_id", secret: null },
},
},
},
});The module then skips its create table, adds the columns it needs that
your table lacks, and writes the three functions, its policies, indexes and
the Vault cleanup trigger over it. provider
and name are required, and so is vaultId (or secret with
secretStorage: "column").
| Column | Default | Holds |
|---|---|---|
provider | provider | The provider, such as openai |
name | name | The credential's name |
tenant | tenant | The tenant of a tenant ref, or null; map to null to drop it |
scope | scope | The user id of a per-user secret, or null |
vaultId | vault_id | The Vault secret's id, with secretStorage: "vault" |
secret | secret | The secret itself, with secretStorage: "column" |
updatedAt | updated_at | Set on every write |
A call's name maps to a row like this:
- A
tenant/<tenant>/<name>name, which a tenant ref stores, reads the row with that tenant when the table mapstenant. - A name that ends in
@<user id>, which ascope: "user"ref stores, reads the row with that user inscopewhen the table mapsscope. A name then ends at its last@. vaultCredentials()always calls with the providervault, so avaultcall names another provider's row as<provider>:<name>. The ref{ "provider": "vault", "secret": "openai:api-key" }reads the row whose provider isopenaiand whose name isapi-key.
options.secretStorage is "vault" by default: each row's vaultId points
to a Vault secret, credential_set creates or updates it, and a trigger
deletes the Vault secret when its row is deleted or its vaultId changes.
secretStorage: "column" keeps the secret in the secret column, for a
table that stores it there today; doctor warns about it (BS314) until the
secrets move into Vault. Doctor also reports a mapped column the live table
lacks (BS330).
Vercel Connect
Vercel Connect holds the OAuth tokens of
connectors you install on a Vercel project. The adapter loads
@vercel/connect the first time it is used:
pnpm add @vercel/connectimport { vercelConnectCredentials } from "better-supabase/vercel-connect";
export const bsb = createServer(betterSupabase, {
credentials: vercelConnectCredentials(),
});A ref names the connector: { "provider": "vercel-connect", "connector": "github", "scopes": ["repo"] }. On Vercel the adapter authenticates with
the deployment's OIDC token; locally, vercel env pull writes
VERCEL_OIDC_TOKEN, and elsewhere you pass vercelToken. region picks
the Connect region for a project outside the default one. teamId or orgId
(set at most one) names the Vercel team or organization that owns the
connector, for a vercelToken that reaches more than one. It needs
@vercel/connect 2.9 and applies to tokens, installations and channel
configs.
The ref's audience, resources, authorizationDetails (RFC 9396) and
validityBufferMs pass through to the token request. getToken(ref, { subject, fresh: true }) skips Connect's in-process token cache, so a grant
revoked at the provider fails at once instead of when the cached token
expires.
Connecting a user's account
When the user hasn't authorized the connector yet, getToken fails with
forbidden and the hint CREDENTIAL_AUTHORIZATION_REQUIRED. Call
startAuthorization(ref, { subject, redirectUri }) and send the user to the
url it returns. Connect stores the grant itself and then redirects to
redirectUri, so the callback only needs to read the token once with
fresh: true to confirm it. Pass deviceCode: true to also get a code the
user enters on another device (result.deviceCode, valid until
result.expiresAt), and prompt: "consent" to ask again for scopes the user
already granted. revoke(ref, { subject }) removes the grant at Connect.
const started = await credentials.startAuthorization?.(ref, {
subject: { type: "user", id: session.user.id },
redirectUri: new URL("/api/integrations/callback", origin).href,
});The Next.js example's Integrations settings tab
(apps/examples/nextjs/src/features/integrations) runs this flow for Gmail
and Outlook, the accounts mail sync reads.
withConnectorToken(credentials, ref, { subject, redirectUri }, fn) wraps
this for a tool or a route: it runs fn with the token, or, when the user
hasn't authorized the connector, starts the authorization and resolves with
{ status: "authorization_required", url } so you can hand the link to the
user. Other errors come back as they are.
const outcome = await withConnectorToken(
credentials,
ref,
{
subject: connectSubject(user, { supabaseUrl: env.SUPABASE_URL }),
redirectUri: new URL("/api/integrations/callback", origin).href,
},
(token) => listRepositories(token.token),
);Supabase Auth users as subjects
A user subject is the Supabase Auth user id. connectSubject(user, { supabaseUrl }) adds the issuer <supabaseUrl>/auth/v1, so local, preview
and production deployments that share a Supabase project resolve the same
Connect grant for a user. You don't need Connect's Auth.js or Better Auth
helpers; the Supabase session already names the user.
Token details and the cache
credentials.tokenDetails(ref, { subject }) returns Connect's whole token
response: tokenId, installationId, tenantId, externalSubject (the
account at the provider), metadata and claims. When the provider rejects
a token with a 401 before it expires, invalidateToken(ref, { subject })
drops Connect's cached copy so the next getToken asks again.
connectorMetadata(ref) returns the connector's name, type and service for a
settings page.
These calls exist only on the Connect provider, so keep the
vercelConnectCredentials() value (typed VercelConnectCredentials) rather
than the CredentialProvider you pass to createServer.
Tenant installations
A connector installed per tenant (a Slack workspace, a GitHub organization)
gives each tenant its own installation. startInstallation(ref, { tenantId, returnUrl }) starts one; send the tenant's admin to the url it returns.
installationRef(ref, installationId) then makes a tenant ref that the app
subject may read. The adapter checks the token's tenantId against the ref's
tenant and fails with CREDENTIAL_REF_FOREIGN when they differ, so a ref
that names another tenant's installation resolves nothing. Revoking stays a
user-subject call.
Chat SDK adapters
channelConfig(ref, "slack") returns the adapter config from
@vercel/connect/chat (connectSlackAdapter and its siblings for Discord,
GitHub, Linear, Linq, Notion, Resend, Sendblue, Teams and Telegram): a token
resolver and a webhook verifier, so the adapter reads a fresh token for every
webhook. Pass it to the platform's adapter factory. For Resend,
channelConfig(ref, "resend") returns an apiKey resolver and a
webhookVerifier that checks the OIDC token Connect attaches after it has
verified the Resend signature, so the signing secret stays in Connect.
Errors
Connect's error codes map to DbErrors with a hint. The original code goes
in code, and the HTTP status and vendor go in details.
| Connect code | Kind | Hint |
|---|---|---|
user_authorization_required | forbidden | CREDENTIAL_AUTHORIZATION_REQUIRED |
client_installation_required, connector_installation_required | forbidden | CREDENTIAL_INSTALLATION_REQUIRED |
no_token | not_found | CREDENTIAL_NOT_FOUND |
connector_not_found | not_found | CREDENTIAL_CONNECTOR_NOT_FOUND |
client_not_linked_to_project | forbidden | CREDENTIAL_CONNECTOR_NOT_LINKED |
client_not_enabled_for_environment | forbidden | CREDENTIAL_CONNECTOR_NOT_ENABLED |
| HTTP 429 | rate_limited | CREDENTIAL_RATE_LIMITED |
Exchange subjects
Besides app and user, the adapter accepts the two exchange subjects
(capabilities(ref).exchangeSubjects). { type: "jwt-bearer", sub, iss?, aud?, additionalClaims? } asks Connect for a token for sub through an
RFC 7523 assertion, and { type: "token", token } exchanges a token the app
already holds (RFC 8693). Vault refuses both with the hint
CREDENTIAL_SUBJECT_UNSUPPORTED.
Forwarded webhooks
A ref with inbound: true lets verifyInbound(request, ref) check a webhook
Connect forwards. The adapter loads @vercel/connect/chat and verifies the
forwarded request's OIDC token against the project and environment, or
against the inbound option of vercelConnectCredentials. A ref without
inbound: true fails with the hint CREDENTIAL_INBOUND_DISABLED.
Your own provider
A CredentialProvider has apiVersion: 1, a name, capabilities
(userSubjects, authorization, revoke, inbound), getToken(ref, options) and revoke(ref, options), plus startAuthorization,
completeAuthorization and verifyInbound when its capabilities say so.
Every method returns a Result, never throws for a provider error, and
puts the token only in the returned value. Run testCredentialProvider from
better-supabase/testing against it; it throws a ConformanceError that
lists every failed check:
import { testCredentialProvider } from "better-supabase/testing";
import { it } from "vitest";
it("conforms", () =>
testCredentialProvider(provider, {
ref: { provider: "mine", name: "github" },
seed: (ref, subject, value) => store.put(ref, subject, value),
}));Last updated on
Document formats
Render the API model to a standard better-supabase does not ship, such as a Postman collection or a GraphQL schema, with defineDocumentFormat and testDocumentFormat.
Add a credential provider
Write a CredentialProvider for Nango, Composio or a cloud secret manager, route refs to more than one provider, and check it with the conformance kit.