Skip to content

Supabase and PostgresStorage, Edge Functions and Realtimeguide

Calling a private API from Supabase Edge Functions

This guide connects a hosted Supabase Edge Function to an API (application programming interface) that is not on the public internet, such as an internal service behind an API gateway. It covers the certificate, the function code, the gateway checks, the edge in front of the function, and two alternatives (a tunnel with a service token, and a fixed-IP forward proxy). It assumes you can deploy an Edge Function and that you, or the API’s owners, control the gateway in front of the API.

Everything marked measured ran on 2026-11-23 on throwaway projects in ap-southeast-1, invoked from Singapore, on supabase-edge-runtime-1.79.1 (compatible with Deno v2.1.4): a micro project for the 06:41 and 07:02 passes, the same experiment rebuilt as a second project for run 3 and the two repeat passes, and a separate project for the egress-address probe. The gateways were Cloudflare Workers standing in for the API’s gateway: one behind Cloudflare mTLS (mutual Transport Layer Security) with the Cloudflare-managed CA (certificate authority), one trusting only a CA we created (Cloudflare bring-your-own-CA, which needs an Enterprise zone), one behind a Cloudflare Access service token, and a local origin behind a Cloudflare Tunnel. Runs 1 and 2 were each run three times, run 3 once (RUNLOG, facts). No commercial API gateway was tested.

These hold for hosted Supabase whatever your setup. If a design depends on one of them being otherwise, it will not work.

FactDetailSource
No private path outEdge Functions cannot join a VPN (virtual private network) or peer into another network. PrivateLink carries traffic from your AWS VPC (virtual private cloud) into the database only (AWS PrivateLink).documented
No fixed egress addressFunctions on three projects left from 13.214.168.194 and 13.214.202.160 (one project), 56.10.122.236 (a second) and 54.179.73.206 (a third, two passes) in ap-southeast-1, and from 34.227.61.74 when pinned to us-east-1. Supabase documents that there are no static egress IPs.1measured, egress probe, F3; documented
No mTLS into SupabaseIn one handshake the project edge sent no client-certificate CA names (openssl s_client: No client certificate CA names sent). Cloudflare Workers cannot present a client certificate to a Cloudflare-proxied hostname either (it returns 520).2measured T1; documented
PlacementA function runs in the region closest to the caller unless the call is pinned with x-region or forceFunctionRegion;3 a pinned call is not re-routed in an outage.measured R3, ABR (placement); documented (no re-route)

On supabase-edge-runtime-1.79.1, X.509 v3 client certificates on RSA (Rivest-Shamir-Adleman) and on named-curve P-256 keys worked (F3, GW1, OWN1); a version 1 certificate and an EC (elliptic curve) key with explicit curve parameters were refused (V1, E1). That is a property of one runtime version, so recheck it after an upgrade.

AppYour edge (Cloudflare Worker)adds secret header, pins regionHTTPS 443Edge Functionchecks header + user JWTholds client cert as secretsHTTPS 443Gateway in front of the internal APIsverifies client cert + validates JWTHTTPS 443, client cert + user JWTInternal API AInternal API B

The app calls your edge, the edge calls the function, and the function calls one gateway over HTTPS (Hypertext Transfer Protocol Secure) with a client certificate and the user’s Supabase access token. The gateway checks both before routing to the internal APIs, so each internal API needs no public endpoint of its own.

ApproachWhat proves the callerWhat the API side runsMeasured here
mTLS + forwarded JWT to one gatewayclient certificate from your CA, and the user’s tokena gateway with a truststore and a JWT policyyes (GW1, OWN1)
Cloudflare Tunnel + Access service tokena service token (two headers), and the user’s tokencloudflared next to the API; no inbound portyes (TUN1)
Fixed-IP forward proxy + IP allowlistthe proxy’s addressan allowlist, plus a proxy you runproxy option only (P1)
The API side pushes data into Postgres on a schedulethe API side’s database credentialsa scheduled job on the API sideno

The first two prove the caller with something it holds. The proxy proves only where traffic came from, so pair it with a token if you use it.

Issue the certificate from the CA the gateway trusts, as X.509 v3 with extendedKeyUsage = clientAuth, on an RSA key or a named-curve EC key:

Terminal window
openssl ecparam -name prime256v1 -genkey -noout -out client.key
openssl req -new -key client.key -subj "/CN=edge-function-client" -out client.csr
printf 'extendedKeyUsage=clientAuth\nbasicConstraints=CA:FALSE\n' > ext.cnf
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-days 90 -extfile ext.cnf -out client.crt

Generate an EC key with openssl ecparam -name prime256v1 -genkey. On macOS LibreSSL, openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 wrote the key with explicit curve parameters (Field Type: prime-field, no ASN1 OID), and the hosted runtime refused it with failed to parse private key as RSA, ECDSA, or EdDSA (E1; local Deno 2.9.8 said KeyMismatch). On the same LibreSSL, openssl x509 -req without -extfile produced a version 1 certificate, and the runtime refused that with UnsupportedCertVersion (V1). Check both before handing the files over: openssl x509 -in client.crt -noout -text | grep -E 'Version|ASN1 OID'.

Step 2: store the certificate as function secrets

Section titled “Step 2: store the certificate as function secrets”

Set the certificate and key as two Edge Function secrets through the Management API:

Terminal window
jq -n --rawfile c client.crt --rawfile k client.key \
'[{name: "CLIENT_CERT", value: $c}, {name: "CLIENT_KEY", value: $k}]' |
curl -s -X POST "https://api.supabase.com/v1/projects/$PROJECT_REF/secrets" \
-H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" -H "Content-Type: application/json" -d @-

Multi-line PEM (Privacy-Enhanced Mail) set this way worked as a client certificate in the function (F2, GW1). The lab function also turned any literal \n in a secret into a newline, so whether the value arrived byte-identical was not checked; the sample below keeps that step. supabase secrets set is the CLI (command-line interface) form of the same call and was not run with PEM values. A certificate and key fit well inside the per-secret ceiling covered in Edge Function limits.

Step 3: call the gateway from the function

Section titled “Step 3: call the gateway from the function”

Deno.createHttpClient has been available to user functions since edge-runtime v1.69.0, and a bad client certificate stopped crashing the runtime in v1.78.1.45 Create the client once per worker, at module scope, and pass it to fetch:

import { createClient } from "npm:@supabase/supabase-js@2";
const env = (k: string) => Deno.env.get(k) ?? "";
const pem = (k: string) => env(k).replaceAll("\\n", "\n");
const sb = createClient(env("SUPABASE_URL"), env("SUPABASE_ANON_KEY"));
const gw = Deno.createHttpClient({ cert: pem("CLIENT_CERT"), key: pem("CLIENT_KEY") });
Deno.serve(async (req) => {
if (req.headers.get("x-gw-secret") !== env("FRONT_SECRET")) return new Response("forbidden", { status: 403 });
const token = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "");
const { data, error } = await sb.auth.getClaims(token);
if (error || !data?.claims?.sub) return new Response("unauthorized", { status: 401 });
const r = await fetch(`${env("GW_URL")}/orders`, {
client: gw,
headers: { authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(15_000),
} as RequestInit);
return new Response(r.body, { status: r.status, headers: { "content-type": "application/json" } });
});

Deploy it with --no-verify-jwt so the function’s own getClaims check is the one that decides; the platform’s verify_jwt check also passes a request that carries only the anon key (iap-lockdown L07).

A module-scope client reuses the connection. Over six interleaved sets to a gateway on Cloudflare’s Singapore edge (n = 20 or 50 per side per set), the reused client’s outbound call had a median of 12-24 ms and a new client per call 61-243 ms; one new-client call of 210 did not return ok (run 2 L, run 3 LAT). The reused-client minimum was 10 ms. The limiter is the new TCP (Transmission Control Protocol) and TLS (Transport Layer Security) connection, with the certificate exchange, on every call (inferred from the mechanism, not counted). Only the gap carries over to your gateway: the absolute times depend on where it runs.

Changing the certificate secrets needs no redeploy. The lab changed one pair of certificate secrets once; the first call on each client style afterwards already presented the new certificate, 5 s after the change was sent for a per-call client and 10 s for a module-scope client (one sample per style, subject read from a certificate echo server; ROT).

Step 4: check the certificate and the token at the gateway

Section titled “Step 4: check the certificate and the token at the gateway”

The gateway has to refuse a request with no certificate or with a certificate from another CA before any API logic runs, then validate the forwarded token against the project’s JWKS (JSON Web Key Set): signature, issuer https://<ref>.supabase.co/auth/v1 (with your project ref), audience authenticated, expiry. The JWKS is at https://<ref>.supabase.co/auth/v1/.well-known/jwks.json. The project created on 2026-11-23 had its ES256 signing key in use and the HS256 key retired at creation (setup log), and user tokens carried alg ES256 with a kid present in the JWKS (F4). The legacy JWT (JSON Web Token) secret and the shared-secret signing key are symmetric,6 so a project still on one of them gives the gateway no public key to verify against; move it to an asymmetric signing key first.

Measured against the stand-in gateways:

Request from the functionGateway trusting the Cloudflare-managed CA (GW1)Gateway trusting only our own CA (OWN1)
no certificate, valid token403403
certificate from another CA, valid token403403 (Cloudflare-managed CA certificate, and a third CA)
trusted certificate, no token401not run
trusted certificate, valid token200 on two internal APIs200 with an RSA certificate and with a named-curve EC certificate

Two things depend on the gateway product and were not tested here. Whether it refuses a request with no certificate at the TLS layer or passes it through for a policy to reject: test that on the real gateway, and remove any default hostname that skips the mTLS listener. And which claims its JWT policy requires by default: a Supabase user token carries sub, role, aud and iss, and a policy that also requires a client id claim would refuse it.

Step 5: put your edge in front of the function

Section titled “Step 5: put your edge in front of the function”

<ref>.supabase.co stays reachable whatever sits in front of it, so the edge needs something the function can check. In the lab a Worker added a shared-secret header and pinned the region:

const h = new Headers();
for (const k of ["authorization", "apikey", "content-type", "accept"]) {
const v = req.headers.get(k);
if (v) h.set(k, v);
}
h.set("x-gw-secret", env.FRONT_SECRET);
h.set("x-region", "ap-southeast-1");
const target = new URL(`${env.SUPABASE_URL}/functions/v1/relay${url.search}`);
target.searchParams.set("forceFunctionRegion", "ap-southeast-1");
return fetch(target, { method: req.method, headers: h, body: req.body });

The Worker forwards an allow-list of headers rather than the whole request, and sets both region controls: the egress probe’s notes record a GET that ignored x-region and honoured forceFunctionRegion (Edge Function limits).

The function then refused direct calls without the header (403, G1) and with a wrong one (403, G2). Pin when callers are outside the project’s region. The relay, forced into us-east-1 and then into eu-central-1 with forceFunctionRegion, called itself again: unpinned and direct, the second invocation ran in us-east-1 and in eu-central-1; through the Worker, which pins ap-southeast-1, it ran in ap-southeast-1 (ABR). Without a pin, a caller far from the database runs the function far from it, and every query and gateway call then crosses that distance (inferred; not timed).

Behind a Worker every user reaches Supabase from the Worker’s egress address: through the Worker, the function and Postgres both saw cf-connecting-ip 2a06:98c0:3600::103 (H1, H2), which Cloudflare documents for cross-zone Worker subrequests.7 Auth’s rate limits are per-IP buckets of 30 that ignore Sb-Forwarded-For unless forwarding is enabled and the request carries a secret key, in which case each forwarded address gets its own bucket (auth-rate-limits AR02a, AR02b, in Supabase Auth end to end). Behind a Worker that does not forward, all users would share one bucket; that combination was not run as one test. What else the edge can and cannot gate - the Data API through RLS (row-level security) on request.headers, and Auth and Storage not at all - is covered in restricting access to a Supabase project.

Variant: Cloudflare Tunnel and an Access service token

Section titled “Variant: Cloudflare Tunnel and an Access service token”

When the API side wants no inbound port at all, run cloudflared next to the API, route a hostname to it through a tunnel,8 and protect that hostname with a Cloudflare Access application whose policy admits one service token.9 The function sends the token as two headers alongside the user’s JWT:

await fetch(`${env("TUN_URL")}/rates`, {
headers: {
authorization: `Bearer ${token}`,
"CF-Access-Client-Id": env("TUN_ID"),
"CF-Access-Client-Secret": env("TUN_SECRET"),
},
redirect: "manual",
});

With the token and a user JWT the origin answered 200 and saw cf-access-jwt-assertion; with the token and no user JWT the origin answered 401; without the token Access answered 403 with its block page (TUN1). The same service-token policy in front of a Worker gave 200 with the token and 403 without (SV1). A service token is a shared secret that proves the calling system, not the user, which is why the origin still validates the forwarded user JWT. redirect: "manual" is a guard; with a service-token policy the lab’s refusal was a 403, not a redirect.

If the API side insists on an IP (Internet Protocol) allowlist, a proxy you run on a fixed address can carry the calls. Pass it explicitly on the client:

const viaProxy = Deno.createHttpClient({ proxy: { url: env("PROXY_URL") } });

The option is honoured: pointed at a closed port, the call failed with tcp connect error (P1). An HTTPS_PROXY function secret is not: it was visible in Deno.env, and a plain fetch still went out directly in 3 of 3 calls in each of three passes, the first 30 s after the secret was set (X1-X3). Proxy and client certificate on one client was not run.

Run these from outside your edge, then through it. Each line except the last is a probe row in the lab’s RUNLOG.

CheckExpect
function URL (Uniform Resource Locator) directly, no secret header403
through the edge, no user JWT401
through the edge, valid JWT200, and x-sb-edge-region is your project’s region
function calls the gateway with no certificate403 from the gateway
function calls the gateway with a certificate from another CA403
function calls the gateway with the right certificate and no JWT401
function calls the gateway with both200
change the certificate secrets, then call againthe server you call reports the new certificate’s subject (the lab saw it by 10 s, ROT)
  • An EC key with explicit curve parameters fails while the certificate and key still match, and the error does not mention the curve (E1).
  • Deno.createHttpClient takes the certificate as cert and the key as key in Deno 2.1.4, the version the hosted runtime reports.10
  • A failed mTLS call does not take the worker down: after a v1 certificate error the next request on the same function answered normally (V1, V2).
  • cf-worker read supabase.co in the function through your Worker (H1) and in Postgres both through it and directly (H2, H3), so it cannot show that a request came through your edge. A secret header can.
  • A direct request carrying client-set cf-connecting-ip, cf-worker, x-forwarded-for and x-real-ip together got 403 before reaching Postgres (H4); which of the four triggered it was not isolated.
  • End to end from Singapore through the Worker, calls whose function made one mTLS request to a public echo server had a median of 1.3 s in each of three passes and a maximum of 1.4-1.8 s (run 1 L, n = 20 per pass). Distance and a new client per call dominated that (inferred).
PracticeEvidenceModule
Issue client certificates as X.509 v3, RSA or named-curve EC.v3 RSA and P-256 worked; v1 refused with UnsupportedCertVersion; an explicit-parameters EC key refused.F3, GW1, OWN1, V1, E1
Create the HttpClient once per worker, at module scope.Reused median 12-24 ms vs new client 61-243 ms per call, 6 of 6 sets.L, LAT
Rotate the client certificate by changing the secrets; no redeploy.The first post-change call on each client style presented the new certificate (one change).ROT
Forward the user’s JWT and validate it at the gateway against the JWKS.ES256 token verified against the project JWKS; no token 401.F4, GW1
Make the gateway refuse no-cert and foreign-CA requests.Both got 403 at the gateway trusting the Cloudflare-managed CA and at the one trusting only our CA.GW1, OWN1
Pin the function region at your edge.Unpinned, the function ran in the calling function’s region (us-east-1, eu-central-1); pinned, in ap-southeast-1.ABR
Check a secret header in the function, not cf-worker.Wrong or missing header 403; cf-worker read supabase.co both ways in Postgres.G1, G2, H2, H3
Pass a forward proxy on the client, not as HTTPS_PROXY.Proxy option honoured; the secret ignored by fetch.P1, X1-X3
Use a Tunnel + Access service token when no inbound port is allowed.200 with token and JWT, 401 without JWT, 403 without token.TUN1, SV1
Put a timeout on every outbound call.Design choice: the lab relay used 15 s against the 150 s request idle limit.none
FileRole
supabase/functions/relay/index.tsthe function: header gate, getClaims, every outbound arm
workers/front/index.tsthe edge: secret header, region pin
workers/gateway/index.tsthe gateway stand-in: mTLS gate, JWT check, two internal APIs
workers/gateway/tunnel-origin.tsthe origin behind the tunnel
cf.ts, cf3.tsCloudflare client certificate, mTLS hostnames, own CA, tunnel, Access apps
probe.ts, probe2.ts, probe3.tsthe three probe matrices

The ids are probe rows in the experiment’s RUNLOG and facts table, not harness modules.

ModuleExperimentTestArtifact
G1, G2, F2-F4, R3, T1, L (run 1)edge-private-flowprobe.tsrun-2026-11-23T06-41-57-722Z.json and two repeats, RUNLOG
GW1, SV1, P1, X1-X3, V1, V2, E1, H1-H4, L (run 2)edge-private-flowprobe2.tsrun2-2026-11-23T07-02-14-605Z.json and two repeats
OWN1, TUN1, ABR, ROT, LATedge-private-flowprobe3.tsrun3-2026-11-23T07-32-15-132Z.json
L07iap-lockdownl07-ef-verify-jwt.tsRUNLOG
  1. Supabase, “Why Supabase Edge Functions cannot provide static egress IPs for allow listing,” Supabase Docs. https://supabase.com/kb/troubleshooting/why-supabase-edge-functions-cannot-provide-static-egress-ips-for-whitelisting-3d78b0 ↩

  2. Cloudflare, “mTLS,” Cloudflare Workers Docs. https://developers.cloudflare.com/workers/runtime-apis/bindings/mtls/ ↩

  3. Supabase, “Regional Invocations,” Supabase Docs. https://supabase.com/docs/guides/functions/regional-invocation ↩

  4. supabase/edge-runtime, “fix(ext/runtime): expose Deno.createHttpClient,” pull request 515, merged 2025-03-18, GitHub. https://github.com/supabase/edge-runtime/pull/515 ↩

  5. supabase/edge-runtime, “fix(deno_tls): vendoring deno_tls and removed the unwrap assertions scattered throughout,” pull request 766, merged 2026-11-05, GitHub. https://github.com/supabase/edge-runtime/pull/766 ↩

  6. Supabase, “JWT Signing Keys,” Supabase Docs. https://supabase.com/docs/guides/auth/signing-keys ↩

  7. Cloudflare, “Cloudflare HTTP headers,” Cloudflare Docs. https://developers.cloudflare.com/fundamentals/reference/http-headers/ ↩

  8. Cloudflare, “Cloudflare Tunnel,” Cloudflare One Docs. https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/ ↩

  9. Cloudflare, “Service tokens,” Cloudflare One Docs. https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/ ↩

  10. Deno, “lib.deno_net.d.ts” (TlsCertifiedKeyPem), v2.1.4, GitHub. https://github.com/denoland/deno/blob/v2.1.4/ext/net/lib.deno_net.d.ts ↩