# How to use Supabase Auth with a backend on Render

- Date: 2026-10-20T13:26:43.270Z
- URL: https://render.com/articles/how-to-use-supabase-auth-with-a-backend-on-render

Your users already sign in with Supabase Auth, and your API already runs on Render. Each request raises two questions: is the token real, and what data may this user read?

This guide answers both with two decisions:

1. *Verify tokens locally.* Your Render service checks each token's signature against cached public keys, so it doesn't call Supabase on every request.
2. *Choose a data path.* Either forward the user's token so your RLS (row-level security) policies stay in charge, or use a secret key on the server and enforce authorization in your own code.

To replace Supabase Auth instead, see the Render guide *Migrating from Supabase*. For background on sessions, tokens, and third-party identity providers, see Render's guide on [how to implement authentication and authorization](https://render.com/articles/how-to-implement-authentication-and-authorization).

*Before you start:*

- Your users sign in with Supabase Auth.
- Your API runs as a Render [web service](https://render.com/docs/web-services).
- You can decode one of your own access tokens with a local script or a JWT debugger you trust.

## How a request flows

1. The client signs in with Supabase and receives an access token.
2. The client calls your Render API with `Authorization: Bearer <token>`.
3. The API verifies the token locally against public keys cached in memory.
4. The API reads data from Supabase (Path A or B) or from Render Postgres over the internal URL.

```text
Client ──sign in──▶ Supabase Auth
Client ──Bearer token──▶ Render web service ──▶ Supabase (Path A or B)
                                             └─▶ Render Postgres (internal URL)
```

## Store Supabase keys in Render environment variables

Environment variables keep credentials such as API keys and connection strings out of your source code. Environment groups let you share one set of variables across several Render services. For the mechanics, see [Render's environment variables docs](https://render.com/docs/configure-environment-variables). For more on handling secrets, see [how Render handles secrets and environment variables](https://render.com/articles/how-render-handles-secrets-and-environment-variables). This section covers only the Supabase-specific layout.

| Variable | Value | Needed when |
|---|---|---|
| `SUPABASE_URL` | Your Supabase project URL | Always |
| `SUPABASE_JWKS_URL` | `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json` | Asymmetric signing keys |
| `SUPABASE_JWT_ALGS` | The asymmetric `alg` value(s) from your token header | Asymmetric signing keys |
| `SUPABASE_JWT_ISSUER` | `https://<project-ref>.supabase.co/auth/v1` | Always |
| `SUPABASE_JWT_AUDIENCE` | The `aud` value from one of your tokens | Always |
| `SUPABASE_JWT_SECRET` | Legacy shared secret | Legacy projects only |
| `SUPABASE_CLIENT_KEY` | The publishable key (`sb_publishable_...`) or the legacy `anon` key | Path A (token forwarding) |
| `SUPABASE_SECRET_KEY` | A secret key (`sb_secret_...`), or the legacy `service_role` key on older projects | Path B only |
| `DATABASE_URL` | Render Postgres internal URL | App data on Render Postgres |

Put the shared, non-secret values in an environment group, such as `supabase-shared`, and link it to the backend services that need it. Add `SUPABASE_SECRET_KEY` and `SUPABASE_JWT_SECRET` only to the individual backend services that use them, or to a separate group that you link only to backends.

> *The secret key never reaches a client.* Keep it on backend services only: web services, private services, background workers, and cron jobs. Never set it on a static site or in any frontend build-time variable, such as `REACT_APP_`, `NEXT_PUBLIC_`, or `VITE_` prefixed variables, which frontend frameworks bundle into JavaScript shipped to browsers. Never link an environment group containing the key to a frontend service. Apply the same rule to the legacy `service_role` key and the legacy shared secret.

Environment variable values are always strings. Validate them once at startup so a missing value stops the deploy instead of failing on the first request. This minimal `config.ts` requires only what every service needs and exposes path-specific keys through getters:

```typescript runnable
// config.ts: server-only module. Never import this from shared or client code.
function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing required env var: ${name}`);
  return value;
}

function optional(name: string): string | undefined {
  return process.env[name] || undefined;
}

export const config = {
  supabaseUrl: required("SUPABASE_URL"),
  // Copy the JWKS URL from your Supabase project's settings.
  jwksUrl: optional("SUPABASE_JWKS_URL"),
  legacyJwtSecret: optional("SUPABASE_JWT_SECRET"),
  jwtAlgs: (optional("SUPABASE_JWT_ALGS") ?? "").split(",").map((a) => a.trim()).filter(Boolean),
  jwtIssuer: required("SUPABASE_JWT_ISSUER"),
  jwtAudience: required("SUPABASE_JWT_AUDIENCE"),
  databaseUrl: optional("DATABASE_URL"), // only services that use Render Postgres
};

if (!config.jwksUrl && !config.legacyJwtSecret) {
  throw new Error("Set SUPABASE_JWKS_URL or SUPABASE_JWT_SECRET");
}
if (config.jwksUrl && config.jwtAlgs.length === 0) {
  throw new Error("SUPABASE_JWT_ALGS is required with SUPABASE_JWKS_URL");
}

// Path A: the client-side API key your frontend already uses.
export const clientKey = () => required("SUPABASE_CLIENT_KEY");
// Path B: the secret key (sb_secret_...). Server-only.
export const secretKey = () => required("SUPABASE_SECRET_KEY");
```

Call each getter at module load in the module that uses it, as the samples below do. A service using Path A or Path B still fails at startup when its key is missing, and a service using neither doesn't need either key.

## Verify tokens locally with JWKS

With asymmetric signing, the issuer signs each token with a private key and publishes the matching public keys as a JWKS (JSON Web Key Set) document, defined in [RFC 7517](https://www.rfc-editor.org/rfc/rfc7517).

To confirm which scheme your project uses, decode a token header:

- An `alg` such as `ES256` or `RS256`, together with a `kid` (key ID), means asymmetric. Use this section.
- An `alg` that starts with `HS` means a symmetric shared secret. Skip to the legacy section.

### Cache keys and handle rotation

supabase-js also offers `supabase.auth.getClaims()`, which verifies JWTs issued by Supabase Auth. This guide uses `jose` so each check is explicit.

Fetch the JWKS once and keep it in process memory. The [`jose`](https://github.com/panva/jose) library's `createRemoteJWKSet` handles this:

- It caches fetched keys.
- It refetches when the cache ages out (`cacheMaxAge`, which defaults to 10 minutes).
- It refetches when a token arrives with an unseen `kid`, rate-limited by `cooldownDuration`, which defaults to 30 seconds after a successful fetch.

Supabase rotates signing keys in stages. A new signing key starts as a standby key. Rotating makes it the current key and moves the old one to "previously used", and Supabase keeps trusting both, so tokens signed with either key keep verifying. Revoke the previously used key once every token it signed has expired: with a 1-hour token expiry, Supabase says to wait at least 1 hour 15 minutes. Supabase's edge caches the JWKS endpoint for 10 minutes, so a revoked key can keep verifying for up to 10 minutes plus your `cacheMaxAge`.

Build the key set at module load, not per request, or you lose the cache.

### Check claims after the signature

A valid signature isn't enough. Also check:

- *Expiry (`exp`):* `jose` checks this by default.
- *Issuer (`iss`) and audience (`aud`):* Compare them against `SUPABASE_JWT_ISSUER` and `SUPABASE_JWT_AUDIENCE`.
- *Subject (`sub`):* The standard JWT subject claim from [RFC 7519](https://www.rfc-editor.org/rfc/rfc7519). Treat it as the user ID.

This simplified Express middleware takes the verifier and an optional post-verification hook as arguments, so the legacy and Render Postgres sections can plug into it:

```typescript runnable
// auth.ts: simplified example. Production: add structured logging and metrics.
import type { Request, RequestHandler } from "express";
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";
import { config } from "./config";

export type AuthedRequest = Request & {
  user: { id: string; claims: JWTPayload; token: string };
};
export type Verifier = (token: string) => Promise<JWTPayload>;

// Built once per process; the cache lives here.
const jwks = config.jwksUrl
  ? createRemoteJWKSet(new URL(config.jwksUrl), {
      cacheMaxAge: 10 * 60_000,  // treat cached keys as stale after 10 minutes
      cooldownDuration: 30_000,  // limit refetches triggered by unknown kids
    })
  : null;

export async function verifyWithJwks(token: string): Promise<JWTPayload> {
  if (!jwks) throw new Error("JWKS not configured");
  const { payload } = await jwtVerify(token, jwks, {
    algorithms: config.jwtAlgs, // never accept whatever alg the token claims
    issuer: config.jwtIssuer,
    audience: config.jwtAudience,
  });
  if (!payload.sub) throw new Error("Token has no subject");
  return payload;
}

export function createRequireUser(
  verify: Verifier,
  onVerified?: (claims: JWTPayload) => Promise<void>,
): RequestHandler {
  return async (req, res, next) => {
    const header = req.headers.authorization ?? "";
    const token = header.startsWith("Bearer ") ? header.slice(7) : null;
    if (!token) {
      res.status(401).json({ error: "missing_token" });
      return;
    }

    let claims: JWTPayload;
    try {
      claims = await verify(token);
    } catch {
      // Expired, wrong issuer/audience, bad signature, or unknown kid after refetch.
      res.status(401).json({ error: "invalid_token" });
      return;
    }

    try {
      await onVerified?.(claims); // e.g. upsert the local user row
    } catch (err) {
      console.error("post-verification hook failed", err);
      res.status(500).json({ error: "internal_error" }); // not the user's fault
      return;
    }

    (req as AuthedRequest).user = { id: claims.sub!, claims, token };
    next();
  };
}

// Asymmetric-only project with no Render Postgres:
// export const requireUser = createRequireUser(verifyWithJwks);
```

If every request returns 401, compare your issuer and audience values character for character (including trailing slashes), and confirm that `SUPABASE_JWT_ALGS` matches the header's `alg`.

## If your project still uses the legacy shared secret

Verification works differently on projects that still sign tokens with a legacy shared secret:

- *Symmetric signing:* The header's `alg` is an `HS` value. You have no JWKS to fetch and no `kid` to track.
- *The secret lives on your API:* Store it as `SUPABASE_JWT_SECRET` on backend services only.
- *The secret can mint tokens:* Anyone holding it can create valid tokens. Guard it as carefully as the secret key.
- *No in-place rotation:* Supabase no longer lets you rotate the legacy JWT secret. Regenerating it immediately invalidates current API keys and severs connections. Migrate to asymmetric signing keys to rotate without downtime.

For projects on a shared secret (`HS256`), Supabase recommends verifying the access token with the Auth server rather than locally. Local verification with the secret works, but it puts a token-minting secret on your API.

When your project moves to asymmetric keys, tokens start arriving with an asymmetric `alg` and a `kid`. During that transition, one verifier can accept both schemes. This sketch adds a legacy branch with the same issuer, audience, and subject checks as the JWKS branch:

```typescript runnable
// verify.ts: transition sketch. Adapt the allowed algorithms to your token headers.
import { decodeProtectedHeader, jwtVerify, type JWTPayload } from "jose";
import { config } from "./config";
import { verifyWithJwks } from "./auth";

const legacyKey = config.legacyJwtSecret
  ? new TextEncoder().encode(config.legacyJwtSecret)
  : null;
const LEGACY_ALGS = ["HS256"]; // match the alg in your legacy token headers

async function verifyLegacy(token: string): Promise<JWTPayload> {
  if (!legacyKey) throw new Error("Legacy token but no secret configured");
  const { payload } = await jwtVerify(token, legacyKey, {
    algorithms: LEGACY_ALGS, // explicit allowlist in this branch too
    issuer: config.jwtIssuer,
    audience: config.jwtAudience,
  });
  if (!payload.sub) throw new Error("Token has no subject"); // same check as JWKS branch
  return payload;
}

export async function verifyAnyToken(token: string): Promise<JWTPayload> {
  const { alg } = decodeProtectedHeader(token); // throws on malformed tokens -> 401
  if (alg && LEGACY_ALGS.includes(alg)) return verifyLegacy(token);
  return verifyWithJwks(token); // asymmetric branch with its own allowlist
}
```

Both branches pin their algorithms. Never let the token's header decide which key type to trust. After the last legacy-signed token expires, remove the `HS` branch and delete `SUPABASE_JWT_SECRET` from your services.

Wire the verifier into the `requireUser` middleware that your routes import:

```typescript runnable
// middleware.ts: the requireUser your routes import.
import { createRequireUser } from "./auth";
import { verifyAnyToken } from "./verify";

export const requireUser = createRequireUser(verifyAnyToken); // use verifyWithJwks once no legacy tokens remain
```

## Read data: forward the user's token or use a secret key

### Path A: forward the user's token

Create a Supabase client per request with the client key, and pass the user's access token in the `Authorization` header. The request carries the user's identity instead of a privileged key, so your RLS policies for signed-in users, for example policies that compare rows to `auth.uid()`, decide what comes back. Your backend can add logic but can't widen access beyond those policies.

```typescript runnable
// supabaseForUser.ts: per-request client. Simplified example.
import { createClient } from "@supabase/supabase-js";
import { config, clientKey } from "./config";

const key = clientKey(); // read at load so a missing key fails at startup

export function supabaseForUser(accessToken: string) {
  return createClient(config.supabaseUrl, key, {
    global: { headers: { Authorization: `Bearer ${accessToken}` } },
    auth: { persistSession: false, autoRefreshToken: false },
  });
}

// Usage inside a handler after requireUser:
// const { user } = req as AuthedRequest;
// const { data, error } = await supabaseForUser(user.token).from("notes").select("*");
```

### Path B: use a secret key server-side

Create one server-only client with a secret key (`sb_secret_...`), or the legacy `service_role` key on older projects. Supabase is deprecating `service_role` by the end of 2026. Both bypass every RLS policy. Treat it as an admin connection that RLS doesn't restrict. Your code becomes the authorization layer, so scope every query to the verified user ID.

> *Reminder:* Keep this module server-only. Never return the key in a response, never log it, and never import this file into shared or client code.

```typescript runnable
// supabaseAdmin.server.ts: server-only singleton. Illustrates the pattern.
import { createClient } from "@supabase/supabase-js";
import { config, secretKey } from "./config";

export const supabaseAdmin = createClient(config.supabaseUrl, secretKey(), {
  auth: { persistSession: false, autoRefreshToken: false },
});
```

```typescript runnable
// routes/notes.ts: authorization lives here, not in RLS.
import { Router } from "express";
import { requireUser } from "../middleware"; // requireUser from middleware.ts above
import { supabaseAdmin } from "../supabaseAdmin.server";
import type { AuthedRequest } from "../auth";

export const notesRouter = Router();

notesRouter.get("/notes", requireUser, async (req, res) => {
  const { user } = req as AuthedRequest;
  const { data, error } = await supabaseAdmin
    .from("notes")
    .select("id, title, created_at")
    .eq("user_id", user.id); // forget this line and you leak every user's notes
  if (error) {
    res.status(500).json({ error: "query_failed" });
    return;
  }
  res.json(data);
});
```

| Path | Key used | RLS applies? | Where authorization lives | Typical uses | Main risk |
|---|---|---|---|---|---|
| A: forward token | Client key + user's access token | Yes | RLS policies | User-scoped reads and writes | Gaps in RLS policies |
| B: secret key | Secret key | No. Bypasses every RLS policy | Your backend code | Admin tasks, cross-user jobs, aggregates | A missing filter exposes other users' data |

Default to forwarding the user's token. Use a secret key deliberately, in narrow, well-reviewed code paths.

## Store app data on Render Postgres, keyed to Supabase user IDs

If your app data lives on Render Postgres, store the verified token's `sub` value in your own tables. Your application keeps that link consistent:

1. Keep a local `app_users` table keyed by the Supabase user ID.
2. On authenticated requests, upsert a row into it, copying only the claims you need.
3. Point your other tables at `app_users.id` with real foreign keys inside Render Postgres.

```sql runnable
-- Simplified schema. Switch id to uuid if every sub value you see is a UUID.
CREATE TABLE app_users (
  id          text PRIMARY KEY,          -- Supabase user ID (token sub)
  email       text,
  last_seen   timestamptz NOT NULL DEFAULT now(),
  deleted_at  timestamptz                -- set by reconciliation, cleared on sign-in
);

CREATE TABLE projects (
  id          bigserial PRIMARY KEY,
  owner_id    text NOT NULL REFERENCES app_users(id) ON DELETE CASCADE,
  name        text NOT NULL
);
```

The code below wires the transition verifier to a hook that upserts the user after each successful verification.

```typescript runnable
// db.ts: one pool per process, only when the service uses Render Postgres.
import { Pool } from "pg";
import { config } from "./config";

export const pool = config.databaseUrl
  ? new Pool({ connectionString: config.databaseUrl })
  : null;
```

```typescript runnable
// ensureUser.ts: uses node-postgres (pg). Simplified example.
import type { Pool } from "pg";
import type { JWTPayload } from "jose";

export async function ensureUser(pool: Pool, claims: JWTPayload): Promise<void> {
  const email = typeof claims.email === "string" ? claims.email : null;
  // The WHERE clause skips the write when nothing changed recently,
  // so you don't pay for a row update on every request.
  await pool.query(
    `INSERT INTO app_users (id, email) VALUES ($1, $2)
     ON CONFLICT (id) DO UPDATE
       SET email = EXCLUDED.email, last_seen = now(), deleted_at = NULL
     WHERE app_users.last_seen < now() - interval '5 minutes'
        OR app_users.deleted_at IS NOT NULL
        OR app_users.email IS DISTINCT FROM EXCLUDED.email`,
    [claims.sub, email],
  );
}
```

```typescript runnable
// middleware.ts: replaces the earlier version to add the upsert hook.
import { createRequireUser } from "./auth";
import { verifyAnyToken } from "./verify";
import { pool } from "./db";
import { ensureUser } from "./ensureUser";

export const requireUser = createRequireUser(
  verifyAnyToken, // use verifyWithJwks once no legacy tokens remain
  pool ? (claims) => ensureUser(pool, claims) : undefined,
);
```

The upsert never sees a deleted user. To catch deletions, run a periodic reconciliation job, such as a Render [cron job](https://render.com/docs/cronjobs). The job imports `config.ts` through `db.ts` and `supabaseAdmin.server.ts`, so it needs the same startup variables as your API, or it fails at startup:

- Link the `supabase-shared` group for `SUPABASE_URL`, `SUPABASE_JWT_ISSUER`, `SUPABASE_JWT_AUDIENCE`, `SUPABASE_JWKS_URL`, and `SUPABASE_JWT_ALGS`. On a legacy project, set `SUPABASE_JWT_SECRET` directly on the job instead of the JWKS variables.
- Set `DATABASE_URL` and `SUPABASE_SECRET_KEY` on the job.

If your API uses only Path A, the job is the only service that holds the secret key. Follow three safety rules:

- *Page through every user, and abort on any error.* Never reconcile against a partial list.
- *Soft-delete first.* Flag missing users with `deleted_at` and hard-delete only after a grace period, so you can recover from a bad run.
- *Skip rows touched during the run.* A user who signs up mid-run isn't in the listing yet.

```typescript runnable
// jobs/reconcileUsers.ts: run as a cron job. Sketch; adapt limits to your user base.
import { supabaseAdmin } from "../supabaseAdmin.server";
import { pool } from "../db";

const PER_PAGE = 1000;
const GRACE_PERIOD = "30 days";

async function listAllUserIds(): Promise<string[]> {
  const ids: string[] = [];
  for (let page = 1; ; page++) {
    const { data, error } = await supabaseAdmin.auth.admin.listUsers({ page, perPage: PER_PAGE });
    if (error) throw error; // abort the whole run
    ids.push(...data.users.map((u) => u.id));
    if (data.users.length < PER_PAGE) return ids;
  }
}

async function main() {
  if (!pool) throw new Error("DATABASE_URL is required");
  const startedAt = new Date();
  const liveIds = await listAllUserIds();
  if (liveIds.length === 0) throw new Error("Refusing to reconcile against an empty list");
  // Production: also abort if the run would flag an unusually large share of rows.

  const flagged = await pool.query(
    `UPDATE app_users SET deleted_at = now()
     WHERE deleted_at IS NULL AND last_seen < $2 AND NOT (id = ANY($1::text[]))`,
    [liveIds, startedAt],
  );
  // ON DELETE CASCADE removes dependent rows such as projects.
  // Never purge a flagged row whose user appears in liveIds again.
  const purged = await pool.query(
    `DELETE FROM app_users
     WHERE deleted_at < now() - $1::interval AND NOT (id = ANY($2::text[]))`,
    [GRACE_PERIOD, liveIds],
  );
  console.log(`flagged=${flagged.rowCount} purged=${purged.rowCount}`);
}

main()
  .catch((err) => { console.error("reconciliation failed", err); process.exitCode = 1; })
  .finally(() => pool?.end());
```

Two Render details matter here:

- *Use the internal URL.* Set `DATABASE_URL` to the database's internal URL, which serves connections only from Render services in the same region, so create the database in your web service's region. The internal URL minimizes query latency because traffic stays on your private network.
- *Pool connections when you need more.* If you outgrow your plan's connection limit, enable PgBouncer connection pooling (paid database plans only) and point `DATABASE_URL` at the pool URL, which uses port 6432.

As with Path B, your code authorizes every query against Render Postgres, so always filter by `owner_id = $userId`.

## Where to go next

You now have three building blocks:

- *Local verification:* Verify tokens against cached JWKS keys, or against the legacy shared secret during a transition.
- *A data path per use case:* Forward the user's token by default, and use a secret key narrowly.
- *App data keyed to Supabase users:* Key Render Postgres rows to Supabase user IDs, with a reconciliation job for deletions.

Next, revisit Render's guide on [how to implement authentication and authorization](https://render.com/articles/how-to-implement-authentication-and-authorization), review [environment variables and secrets](https://render.com/docs/configure-environment-variables), and read *Migrating from Supabase* if you ever decide to replace Supabase Auth.

## Frequently asked questions

###### Can one API use both token forwarding and a secret key?

Yes. Use token forwarding for routes that act on behalf of the signed-in user, and keep the secret-key client in a few narrow modules for admin tasks or cross-user jobs. Set `SUPABASE_SECRET_KEY` only on the services that run those modules, so a service that only forwards tokens never holds the key.

###### What happens if a user signs out or is deleted while their token is still valid?

Local verification checks the token's signature and claims without contacting the Supabase Auth server, so a verified token stays valid until its `exp`, and your API can't detect a sign-out. The reconciliation job covers deleted users only: it flags their rows in Render Postgres on its next run. It can't hold that flag while the deleted user's token is unexpired, because `ensureUser` clears `deleted_at` on every verified request. If a sensitive action must reject such tokens, add a server-side check of the user's status for that route, such as `getUser`, which sends a request to the Auth server for each token.

###### What if my Render Postgres database is in a different region from my API?

In that case, your API can't use the internal URL, because that URL serves only Render services in the same region. Connections from anywhere else go through the external URL. You can't change a database's region after creation, so choose the region before you store `app_users` rows.

###### Why does my startup check reject SUPABASE_JWT_ALGS or other config values?

Render always delivers environment variable values as strings, so your code must parse lists, numbers, and booleans itself. That's why `config.ts` splits `SUPABASE_JWT_ALGS` on commas and trims each entry. The startup check fails when `SUPABASE_JWT_ALGS` is empty or missing while `SUPABASE_JWKS_URL` is set. Stray quotes in the value don't fail the startup check, but they cause algorithm mismatches that return 401, so remove any quotes from the value you set in the Dashboard.

###### How do I handle too many connections when every request upserts a user?

Enable Render's integrated PgBouncer connection pooling. PgBouncer runs on the database's own host, so the extra hop adds little latency. Connection pooling requires a paid database plan. Enabling it restarts the database, so expect it to be unavailable for a few minutes. Afterward, point `DATABASE_URL` at the pool URL, which uses port 6432.

