# Use Pontive with Supabase

> Sign users in with Pontive and keep your data in Supabase. Supabase trusts Pontive's access tokens as a custom OIDC issuer, and Row Level Security policies scope every row to the organization in the token. Includes apps built in Lovable.

Source: https://www.pontive.com/docs/guides/supabase

Pontive signs your users in, holds their organizations, roles and permissions, and runs billing.
Supabase holds your data and runs your backend. Supabase's
[third-party auth](https://supabase.com/docs/guides/auth/third-party/overview) makes the two meet:
your Supabase project accepts Pontive's access tokens as they are, so there are no tokens to
exchange and no users to copy into Supabase Auth.

## How it fits together [#how-it-fits-together]

1. **Pontive signs the user in** and issues an access token for your app. The token is signed with
   RS256, carries a `kid`, and names the organization the session acts in (`org_id`) and what the
   user holds there (`roles`, `permissions`).
2. **The Supabase client sends that token** on every request. With supabase-js you pass a function
   that returns it (`accessToken`), and the client asks it for a token before each call.
3. **Supabase checks the signature** against the keys in your instance's JWKS, which it finds
   through `https://<auth-domain>/.well-known/openid-configuration`. A token whose `role` claim is
   `authenticated` runs as Postgres's `authenticated` role.
4. **Row Level Security decides access.** Policies read the verified claims with `auth.jwt()`, so a
   row is visible only inside the organization the token names.
5. **Pontive Billing gates features through its API.** Entitlements are not in the token: you ask
   the entitlement check API, from an Edge Function or your server.

Two settings make it work: Supabase must trust your Pontive issuer, and the token must carry
`role: "authenticated"`.

## 1. Add the `role` claim to the app's tokens [#1-add-the-role-claim-to-the-apps-tokens]

Supabase reads the `role` claim of every token to choose the Postgres role. Without one, a request
runs as `anon`. Pontive's tokens have no `role` claim of their own (they carry `roles`, an array),
so add one with the app's **access-token claims template**.

In the Pontive dashboard, open **Apps**, then your app, then **Security**. Under **Access token
claims**, set the template to:

```json
{
  "role": "authenticated"
}
```

Use **Preview** with one of your users' ids to see the claims a token would carry. Through the
[management API](/docs/api-reference/management/apps), the template is the app's
`token_config.access_token.claims_template`, and
`POST /v1/apps/{app_id}/claims-template/preview` renders it without saving.

The template is rendered at sign-in, on every refresh and on every organization switch, so every
access token the app gets carries the claim. ID tokens are not affected. If you already have a
template, add the `role` key to it.

A token for this app then looks like this:

```json
{
  "iss": "https://acme-x7k2p9qa-dev.auth.us.pontive.dev",
  "sub": "usr_...",
  "aud": ["app_..."],
  "client_id": "app_...",
  "org_id": "org_...",
  "roles": ["admin"],
  "permissions": ["project:read", "project:write"],
  "role": "authenticated",
  "exp": 1796342400
}
```

`aud` is a list holding the app's id. `org_id` is there only while the session acts in an
organization; a `b2c` token never has one. See
[which organization a session acts in](/docs/guides/organizations-and-roles#which-organization-a-session-acts-in).

## 2. Trust Pontive's issuer in Supabase [#2-trust-pontives-issuer-in-supabase]

Your issuer is the app's auth domain with `https://` in front of it, for example
`https://acme-x7k2p9qa-dev.auth.us.pontive.dev`, or the custom auth domain the app is bound to. It
must match the token's `iss` exactly.

In the Supabase dashboard:

1. Go to **Authentication**, then **Sign In / Providers**, then **Third-Party Auth**.
2. Click **Add provider** and choose **Custom OIDC**.
3. Enter the issuer in **Issuer URL**, exactly as it appears in the token's `iss`, and click **Add provider**.

Or call the Supabase Management API's
[create third-party auth integration](https://supabase.com/docs/reference/api/v1-create-project-tpa-integration)
with the issuer in `oidc_issuer_url`.

Each Pontive instance is its own issuer with its own keys. Add one integration per instance you
connect, for example your development instance on a development Supabase project and your
production instance on the production one.

## 3. Send the token from your app [#3-send-the-token-from-your-app]

Pass `accessToken` to `createClient`. supabase-js calls it before each request, and for Realtime on
connect and on every heartbeat.

### React and other browser apps [#react-and-other-browser-apps]

With `@pontive/pontkit-react` set up as in the [React quickstart](/docs/quickstart/react), read the
current access token from `Auth` in `@pontive/oidc-client`, the client the provider configured:

```ts title="src/lib/supabase.ts"
import { createClient } from "@supabase/supabase-js";
import { Auth } from "@pontive/oidc-client";

export const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
  {
    // The Pontive access token, or null when nobody is signed in (requests then run as anon).
    accessToken: async () => Auth.getCurrentSession()?.access_token ?? null,
  },
);
```

`getCurrentSession()` returns the stored session and starts a background refresh once 80% of the
token's lifetime has passed. Turn **refresh tokens** on for the app and ask for `offline_access`,
so the session is renewed before the token expires.

When the user switches organization, the next request carries the new `org_id`. Reload what you
fetched for the old one: `useSession()` reports `organization-changed`.

```tsx
import { useEffect } from "react";
import { useSession } from "@pontive/pontkit-react";

function useReloadOnOrganizationChange(reload: () => void) {
  const change = useSession();
  useEffect(() => {
    if (change?.reason === "organization-changed") reload();
  }, [change, reload]);
}
```

### Next.js on the server [#nextjs-on-the-server]

On the server, `pontive().auth()` from the [Next.js quickstart](/docs/quickstart/nextjs) returns the
session with its access token. Create a client per request:

```ts title="lib/supabase-server.ts"
import { createClient } from "@supabase/supabase-js";
import { pontive } from "@/lib/pontive";

export async function supabaseForRequest() {
  const session = await pontive().auth();

  return createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, {
    accessToken: async () => session?.accessToken ?? null,
  });
}
```

<Callout type="warn" title="supabase.auth is off in this client">
A client created with `accessToken` throws on every `supabase.auth.*` call. Sign-in, sign-out and
the user's profile go through Pontive. If you also need Supabase Auth somewhere, create a second
client for it.
</Callout>

## 4. Write RLS policies on the organization [#4-write-rls-policies-on-the-organization]

In a `b2b` app the tenant is the organization. Key every tenant table by `org_id` and compare it with
the token's **`org_id` claim, never with `sub`**. A policy on `sub` gives each user their own rows,
so two members of the same organization would never see each other's data, and a user's rows would
follow them into every organization they belong to.

```sql
create table public.projects (
  id uuid primary key default gen_random_uuid(),
  -- Pontive ids are text, such as org_... and usr_...
  org_id text not null default (auth.jwt()->>'org_id'),
  name text not null,
  created_by text not null default (auth.jwt()->>'sub'),
  created_at timestamptz not null default now()
);

create index projects_org_id_idx on public.projects (org_id);

alter table public.projects enable row level security;

-- Members see their organization's projects.
create policy "Members read their organization's projects"
  on public.projects for select
  to authenticated
  using (org_id = (select auth.jwt()->>'org_id'));

-- Creating, changing and deleting need a permission from the token.
create policy "project:write creates projects in the organization"
  on public.projects for insert
  to authenticated
  with check (
    org_id = (select auth.jwt()->>'org_id')
    and (select auth.jwt()->'permissions') ? 'project:write'
  );

create policy "project:write changes the organization's projects"
  on public.projects for update
  to authenticated
  using (
    org_id = (select auth.jwt()->>'org_id')
    and (select auth.jwt()->'permissions') ? 'project:write'
  )
  with check (org_id = (select auth.jwt()->>'org_id'));

create policy "Admins delete the organization's projects"
  on public.projects for delete
  to authenticated
  using (
    org_id = (select auth.jwt()->>'org_id')
    and (select auth.jwt()->'roles') ? 'admin'
  );
```

- `permissions` and `roles` are JSON arrays, so `?` tests whether one holds a key. Prefer
  permissions to role names: a role's permissions can change in Pontive without touching SQL.
- A token with no `org_id` matches no row, and one with no `permissions` claim passes no permission
  check. Every policy fails closed.
- Wrapping `auth.jwt()` in `(select …)` lets Postgres evaluate it once per statement rather than
  once per row.
- The token is a snapshot. A role granted or revoked, or a member removed, reaches Supabase with the
  user's next access token, at the latest when the current one expires.

**Per-user data.** `sub` is the right key only for data that belongs to one person and follows them
everywhere, which is the usual case in a `b2c` app. Use a `text` column:

```sql
create policy "Users read their own notes"
  on public.notes for select
  to authenticated
  using (user_id = (select auth.jwt()->>'sub'));
```

Do not use `auth.uid()`. It casts `sub` to `uuid`, and a Pontive `sub` such as `usr_...` is not a
UUID, so the cast fails.

### Accept only your app's tokens [#accept-only-your-apps-tokens]

Supabase trusts every token your issuer signs that carries `role: "authenticated"`, and it does not
document an audience check for third-party tokens. Your Supabase project also keeps Supabase Auth,
which cannot be turned off and issues tokens of its own. Add a **restrictive** policy to each table
so only tokens Pontive issued to your app get through:

```sql
create policy "Only tokens Pontive issued to this app"
  on public.projects
  as restrictive
  for all
  to authenticated
  using (
    (select auth.jwt()->>'iss') = 'https://acme-x7k2p9qa-dev.auth.us.pontive.dev'
    and (select auth.jwt()->>'client_id') = 'app_...'
  );
```

A restrictive policy grants nothing; it narrows the permissive ones. Keep the `as restrictive`
clause, or the policy would instead let every such token read and write every row. If several
Pontive apps share the database, such as a web app and a mobile app, list each app id with `in (…)`.

### Storage and Realtime [#storage-and-realtime]

The same claims work in Storage and Realtime policies. Store an organization's files under a folder
named for its `org_id`:

```sql
create policy "Members read their organization's files"
  on storage.objects for select
  to authenticated
  using (
    bucket_id = 'documents'
    and (storage.foldername(name))[1] = (select auth.jwt()->>'org_id')
  );
```

Storage records the uploader's `sub` in `owner_id`, a text column. Compare it with
`auth.jwt()->>'sub'`, never with `auth.uid()`.

For private Realtime channels, name each organization's topic after it and check the topic in a
policy on `realtime.messages`:

```sql
create policy "Members join their organization's channel"
  on realtime.messages for select
  to authenticated
  using (realtime.topic() = 'org:' || (select auth.jwt()->>'org_id'));
```

Postgres Changes deliver only the rows a subscriber's policies let them read. Realtime re-reads the
policies when it receives a new token, and supabase-js asks `accessToken` for the current one on
every heartbeat. After an organization switch, subscribe again to the new organization's topic.

## 5. Gate features with Pontive Billing [#5-gate-features-with-pontive-billing]

Entitlements are not in the access token: a token would be stale until its next refresh, and a
numeric or metered feature needs a value, not a yes or no. Ask the
[entitlement check API](/docs/api-reference/authz/billing-entitlements) when it matters, from a
Supabase Edge Function or your own server.

```ts title="supabase/functions/generate-report/index.ts"
import { createRemoteJWKSet, jwtVerify } from "npm:jose@5";

const ISSUER = Deno.env.get("PONTIVE_ISSUER")!; // https://<auth-domain>
const APP_ID = Deno.env.get("PONTIVE_APP_ID")!; // app_...
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/oauth2/jwks.json`));

Deno.serve(async (req) => {
  // Verify the Pontive token the browser sent, and read the organization from it.
  const token = req.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
  const verified = await jwtVerify(token, jwks, { issuer: ISSUER, audience: APP_ID, typ: "at+jwt" }).catch(() => null);
  if (!verified) return new Response("Unauthorized", { status: 401 });
  const orgId = verified.payload.org_id as string | undefined;
  if (!orgId) return new Response("Choose an organization first", { status: 403 });

  // Ask Pontive Billing whether the organization's plan includes the feature.
  const res = await fetch("https://authz.us.pontive.com/v1/entitlements/check", { // your instance's region
    method: "POST",
    headers: {
      authorization: `Bearer ${Deno.env.get("PONTIVE_SECRET_KEY")}`, // a secret key holding sys:billing:check
      "content-type": "application/json",
    },
    body: JSON.stringify({ subject: { type: "organization", id: orgId }, feature: "advanced_reports" }),
  });
  const { allowed, reason } = await res.json();
  if (!allowed) return Response.json({ upgrade: true, reason }, { status: 402 });

  // ... build the report
  return Response.json({ ok: true });
});
```

A denial is a `200` with `allowed: false` and a `reason`: `not_entitled`, `allowance_exhausted`,
`balance_exhausted` or `access_restricted`. Keep the secret key in the function's secrets, never in
the browser. To hide or show controls in the UI, the signed-in user's own check is
`POST /v1/me/entitlements/check`.

## Building in Lovable [#building-in-lovable]

Lovable offers two backends: its built-in backend, Lovable Cloud, and a Supabase project you own and
connect. They differ in what you can configure:

| | Lovable Cloud | Your own Supabase project |
| --- | --- | --- |
| Third-Party Auth (trust Pontive's tokens) | Not offered. Auth settings are Lovable's own sign-in methods, and there is no Supabase dashboard | Yes, in the Supabase dashboard |
| `org_id`, `roles` and `permissions` in RLS | No | Yes |
| Sign in with Pontive | Yes, as an OIDC sign-in method, then Supabase Auth issues its own session | Yes, with the Pontive SDK |

### Recommended: connect your own Supabase project [#recommended-connect-your-own-supabase-project]

For organization-scoped data, connect your own Supabase project to the Lovable project
(**Connect to Supabase** in Lovable), then do steps 1 and 2 above in the Pontive and Supabase
dashboards. Lovable does not move a project between its built-in backend and Supabase for you, so
choose your own Supabase project before you build.

Then give Lovable a prompt like this, with your own values:

```txt
Use Pontive for sign-in, organizations, roles and billing. Do not use Supabase Auth: no Supabase
sign-in or sign-up pages, and never call supabase.auth.

1. Install @pontive/pontkit-react and wrap the app in its <Provider> with
   domain="<your auth domain>", appId="<your app_ id>", signinUrl="/signin",
   signupUrl="/signup" and scope="openid email profile offline_access".
   Add /signin/* and /signup/* routes that render <Signin /> and <Signup />,
   and an <OrganizationSwitcher /> in the header.
2. Where the Supabase client is created, pass this option to createClient:
   accessToken: async () => Auth.getCurrentSession()?.access_token ?? null
   with Auth imported from "@pontive/oidc-client".
3. Every table that holds customer data has
   org_id text not null default (auth.jwt()->>'org_id'), indexed.
   Its RLS policies compare org_id with (select auth.jwt()->>'org_id'), never with auth.uid()
   or the user's id. Writes also need the permission, for example
   (select auth.jwt()->'permissions') ? 'project:write'.
4. Add a restrictive policy to every table:
   (select auth.jwt()->>'iss') = '<your issuer>'
   and (select auth.jwt()->>'client_id') = '<your app_ id>'.
5. When the session's organization changes (useSession() reports organization-changed),
   reload the data on screen.
```

Then, in the Pontive app's settings, add your published Lovable URL, such as
`https://your-app.lovable.app`, to the app's allowed origins, and set up the auth endpoints as in
the [React quickstart](/docs/quickstart/react) and [the auth proxy](/docs/sdk/auth-proxy).

#### Sign in from Lovable's preview [#sign-in-from-lovables-preview]

The editor's preview runs in an iframe on a host that changes with each draft, such as
`<id>.lovableproject.com`, so an allowed origin or redirect URI cannot list it. On a **development
instance**, turn on Lovable in the app's **Builder previews** card in the dashboard, or set the app's
`builder_previews` field with the [management API](/docs/api-reference/management/apps):

```json
{ "builder_previews": ["lovable"] }
```

The preview then signs in with nothing else to register:

- **Embedded sign-in** (`<Signin />`, `<Signup />`) is accepted from the preview's origin. A step
  that leaves the page, such as Google, opens in a popup, so allow pop-ups for Lovable.
- **OAuth redirects** use the hosted preview callback,
  `https://<your auth domain>/oauth2/preview-callback?origin=<the preview's origin>`, in that same
  popup. It sends the authorization response back to the preview with `postMessage`. Server sessions
  from `@pontive/pontkit-server` use it on their own.
- Safari, and Firefox with Total Cookie Protection, block cookies inside the iframe. Open the preview
  in its own tab and sign in there.

This lets every page on Lovable's preview hosts start your app's sign-in, so turn it on only while
you build. A production instance never admits previews: it rejects the setting with
`422 builder_previews_not_allowed`. In production, sign in on your published URL or your own domain.
More detail, including v0, Vercel, Replit, Bolt and CodeSandbox, is in the `pontive-builder-previews`
skill in [Agent Skills](/docs/agent-skills#the-skills).

### Lovable Cloud: sign-in only [#lovable-cloud-sign-in-only]

Lovable Cloud's **OIDC sign-in** can use Pontive as the identity provider: in Lovable, open **More**,
then **Users**, then **Settings**, then **OIDC**, and enter your issuer and the client id and secret
of a confidential oauth app in Pontive whose redirect URI is the one Lovable shows. Users then sign
in through Pontive, but Lovable Cloud's own auth issues the session token. That token carries none of
Pontive's claims, so RLS cannot see the user's organization, roles or permissions, and the app must
ask Pontive's APIs from an Edge Function instead. Lovable allows one OIDC provider per project and
asks only for `openid`, `profile` and `email`. Use this when sign-in is all you need from Pontive.

## Limits and caveats [#limits-and-caveats]

- **Supabase Auth stays on.** It cannot be disabled. Turn off new sign-ups in Supabase Auth's
  settings and keep the restrictive issuer policy, so its tokens never reach your data.
- **No Supabase Auth features in the app.** `supabase.auth.*` throws in a client created with
  `accessToken`; `auth.users` has no rows for Pontive's users, so nothing can reference it; and
  `auth.uid()` fails on Pontive ids. Users, sessions, MFA, email and organizations are Pontive's.
- **Local development.** The Supabase CLI has no custom OIDC provider and no config file option for
  one. Test against a hosted Supabase project, such as a development project or a branch.
- **Signing-key rotation.** Supabase stores your issuer's keys and checks them for changes
  periodically, and asks you to allow up to 30 minutes for a new key to be picked up. Pontive rotates
  each instance's signing key every 24 hours and signs with the new key straight away, so for a short
  while after a rotation Supabase can refuse a freshly signed token. Handle a `401` from Supabase by
  retrying after a delay rather than signing the user out.
- **Claim size.** When a user's roles and permissions are too large for a token, Pontive leaves the
  `permissions` claim out, then `roles`, and names them in `claims_overflow`. Policies on those
  claims then fail closed. Narrow what tokens carry under **Roles and permissions in tokens** on the
  app's **Security** page.
- **Agents.** An AI agent acting for a user gets a token issued to the agent, without your app's
  claims template. Supabase runs it as `anon`, and the restrictive policy refuses it.
- **Realtime.** A channel closes when its token expires and no new one has arrived. The Pontive SDK
  renews the token before then while refresh tokens are on.
- **Pricing.** Supabase bills users who use a third-party provider as Monthly Active Third-Party
  Users: 50,000 included on Free and 100,000 on Pro and Team, then $0.00325 each. See
  [Supabase's pricing](https://supabase.com/docs/guides/platform/manage-your-usage/monthly-active-users-third-party).

## See also [#see-also]

- [Organizations and roles](/docs/guides/organizations-and-roles): the claims and how a session
  picks its organization.
- [Protect an API](/docs/guides/protect-an-api): verifying Pontive tokens in your own services.
- Supabase: [Custom OIDC provider](https://supabase.com/docs/guides/auth/third-party/custom-oidc) and
  [Row Level Security](https://supabase.com/docs/guides/database/postgres/row-level-security).
