Short answer
An Edge Function is a public URL, so it must decide for itself who is calling and what they may do. Read the user from the verified token in the Authorization header, never from the request body; query with the caller’s rights so RLS still applies; keep the secret key and every other secret in Supabase secrets; validate input; rate-limit expensive calls; and log IDs, not personal data. verify_jwt alone does not prove who the user is.
Ask an AI about this page:ChatGPTClaude
On this page
Key takeaways
- An Edge Function is a public URL. Anyone who knows the address can call it with any body they like.
verify_jwtis a gate at the door, not an ID check. It does not tell your code which user is calling.- Take the user from the verified token, never from the body. A
userIdin the request is just a suggestion from the caller. - Query with the caller’s rights so RLS keeps working. Use the secret key only for the one step that needs it, filtered by the verified user ID.
- Secrets live in Supabase secrets, never in the frontend, never in a response. Validate input, rate-limit expensive calls, and log IDs instead of personal data.
Why Edge Functions need their own security
Most apps built with Lovable, Bolt or Cursor on Supabase start with the browser talking straight to the database, protected by row level security. Sooner or later something needs a server: calling an AI model, creating a Stripe checkout, sending an e-mail, exporting data. That code goes into a Supabase Edge Function: a small TypeScript program that runs on Deno at https://<project>.supabase.co/functions/v1/<name>.
Two things make Edge Functions riskier than they look:
- They are reachable by anyone. Your app calls them with
supabase.functions.invoke, but nothing stops someone from calling the same URL with their own tool and their own body. - They often hold the keys to everything. Functions can read the secret key (
sb_secret_…, or the legacyservice_rolekey), which skips RLS completely, plus your OpenAI, Stripe or Resend keys. A mistake in a function is a mistake with admin rights.
So the question every function must answer for itself is the same one RLS answers for tables: who is calling, and may they do this?
Is verify_jwt enough?
Every Supabase Edge Function has a platform check called verify_jwt. It is on by default. When it is on, the platform looks at the Authorization header before your code runs and returns 401 if there is no valid token.
That sounds like authentication, and AI tools often write a comment like “the platform already verified the JWT” and move on. But there are three gaps:
- It doesn’t tell your code who the user is. It only lets the request through. Your code still has to read the token.
- It accepts more than user tokens. Supabase’s docs state that, for migration compatibility, the check also accepts the new publishable and secret API keys. The publishable key is in your frontend, so anyone has it. In their words: “The check alone doesn’t authenticate a caller that sends only an API key.”
- It says nothing about which records the caller may touch. A signed-in user is still only allowed to see their own data.
The mistake we see most: trusting the request body
Here is a function from one of our own test apps, a small trip planner we built with deliberate mistakes. It loads a user’s trips for the dashboard:
import { createClient } from "npm:@supabase/supabase-js@2";
Deno.serve(async (req) => {
// "The platform already verified the JWT (verify_jwt is on)."
const { userId } = await req.json();
const admin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
const { data } = await admin.from("trips").select("*").eq("user_id", userId);
return Response.json({ trips: data });
});It looks careful: verify_jwt is on, and it filters by user_id. But the userId comes from the body, which the caller writes, and the query runs with the service role key, which ignores RLS. Anyone with the public key can send another user’s ID and get their trips back. Because user IDs often show up in URLs, shared links or API responses, “they would have to guess a UUID” is not a defence.
This is broken object level authorization (BOLA), number one in the OWASP API Security Top 10, also known as CWE-639 (opens in a new tab): the server lets a caller-controlled key decide whose data comes back. The fix page Edge function trusts user_id from the request body covers this exact pattern.
A second variant from another test app: the function checks that the caller is signed in, then loads a project by an ID from the body with the service role. Signed in, yes, but not necessarily a member of that project’s workspace. Being logged in is not the same as being allowed. See Edge function without auth check.
How do I get the user inside an Edge Function?
From the token in the Authorization header, verified by your code or a library, and nothing else. Supabase now documents two ways, depending on which keys your project uses.
Projects on the new API keys: @supabase/server
Supabase’s current docs use the withSupabase wrapper from the @supabase/server package. You declare which credential the function accepts, and the handler receives clients that are already set up:
import { withSupabase } from "npm:@supabase/server@1";
export default {
fetch: withSupabase({ auth: "user" }, async (_req, ctx) => {
// ctx.supabase acts as the caller: RLS decides which trips come back.
const { data, error } = await ctx.supabase
.from("trips")
.select("id, destination, starts_on, ends_on");
if (error) return Response.json({ error: "Could not load trips" }, { status: 500 });
return Response.json({ trips: data });
}),
};With auth: "user", the wrapper verifies the user’s JWT against your project’s signing keys and rejects the request otherwise. Then:
ctx.supabaseruns every query as the caller, so your RLS policies apply. This is the client you want almost always.ctx.supabaseAdminuses the secret key and skips RLS. Supabase’s docs warn that a query through it without a filter on the caller’s ID returns every user’s rows.ctx.userClaims.idis the verified user ID, if you need it for an insert or a filter.
The package works with the new key format only (sb_publishable_…, sb_secret_…) and asymmetric JWT signing keys. Its own docs say legacy anon and service_role keys and HS256-signed tokens are rejected.
Projects still on the legacy keys: a caller-scoped client
Many projects created by AI builders still use the legacy anon and service_role keys. The pattern is the same idea, written by hand: create a client that forwards the caller’s Authorization header, verify the token, and take the user ID from the verified claims.
import { createClient } from "npm:@supabase/supabase-js@2";
Deno.serve(async (req) => {
const authHeader = req.headers.get("Authorization");
if (!authHeader) return Response.json({ error: "Not signed in" }, { status: 401 });
// A client that acts as the caller, so RLS applies to every query below.
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: authHeader } } },
);
// Verify the token and read the user id from it, never from the body.
const token = authHeader.replace(/^Bearer\s+/i, "");
const { data: auth, error: authError } = await supabase.auth.getClaims(token);
if (authError || !auth) return Response.json({ error: "Not signed in" }, { status: 401 });
const userId = auth.claims.sub;
const { data, error } = await supabase
.from("trips")
.select("id, destination, starts_on, ends_on")
.eq("user_id", userId);
if (error) return Response.json({ error: "Could not load trips" }, { status: 500 });
return Response.json({ trips: data });
});getClaims verifies the token: locally against the published keys if your project uses asymmetric signing keys, otherwise by asking the Auth server, as Supabase’s reference describes. The older getUser(token) also works and always asks the Auth server.
When is the secret key okay?
Sometimes a function must do something the caller can’t do through RLS: write an export log, update a credit balance, read a table users never see. That is what the secret key is for. Do it in this order:
Check access with the caller's rights
Load the record with the caller-scoped client. If RLS hides it from them, you get nothing back and stop with a 404.
Then do the one privileged step
Use the admin client only for the write the caller may not do, and use the verified user ID, not a value from the body.
Never return what you didn't need to
Send back only the fields the screen shows. Admin queries with select("*") are how private columns end up in a response.
import { withSupabase } from "npm:@supabase/server@1";
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const userId = ctx.userClaims!.id; // verified by withSupabase
const { projectId } = await req.json();
// Check with the caller's rights first: RLS only returns the project
// if the caller is a member of its workspace.
const { data: project } = await ctx.supabase
.from("projects")
.select("id, workspace_id")
.eq("id", projectId)
.maybeSingle();
if (!project) return Response.json({ error: "Not found" }, { status: 404 });
// Only now use admin rights, for the one write the caller may not do.
const { error } = await ctx.supabaseAdmin.from("project_exports").insert({
workspace_id: project.workspace_id,
project_id: project.id,
exported_by: userId,
});
if (error) return Response.json({ error: "Export failed" }, { status: 500 });
return Response.json({ ok: true });
}),
};This relies on RLS policies that really check workspace membership. If your policies only say “any signed-in user”, the first query proves nothing; multi-tenant data isolation explains how to write them.
Check your own functions in ten minutes
List every function and how it is called
Open supabase/functions/ and your supabase/config.toml (or config.jsonc). Note which functions have verify_jwt = false. Each of those must check a signature or a secret itself, or be genuinely public.
Search for IDs read from the body
Search your functions for userId, user_id, ownerId and req.json(). Any user ID that comes from the request instead of the token is a finding.
Search for the admin client
Search for SERVICE_ROLE, SECRET_KEY and supabaseAdmin. For every query through it, ask: what stops a caller from pointing it at someone else’s row?
Search for secrets in responses
Look for Deno.env.get values that end up in Response.json(...). A function must never hand an API key to the browser.
Call it as a second user
Sign in as a test user, call the function with an ID that belongs to another test user, and check that you get a 404 or 403, not their data. Only do this against your own project.
Never return a secret from a function
Another function in the same test app was written to “keep the app fast”: instead of calling the AI provider itself, it returned the OpenAI key so the browser could call the provider directly. It also had verify_jwt = false.
Deno.serve(() => {
const apiKey = Deno.env.get("OPENAI_API_KEY");
return Response.json({ apiKey, model: "gpt-4o-mini" });
});Putting the key in a Supabase secret was right; handing it to anyone who asks undoes that. The function must be the one that calls the provider, after checking the user and their limits, and it returns only the result. See OpenAI or Anthropic key in client code and the guide on calling AI APIs safely.
Where do secrets belong?
In Supabase secrets, read with Deno.env.get inside the function:
supabase secrets set OPENAI_API_KEY=sk-...
supabase secrets listWhat Supabase’s docs say, in short:
- Locally, functions read
supabase/functions/.env. Add it to.gitignorebefore your first commit. - In production, set secrets in the dashboard under Edge Function Secrets or with
supabase secrets set. Functions see a new secret immediately, without a redeploy. - Names starting with
SUPABASE_are reserved:SUPABASE_URL, the publishable and secret keys and the JWKS are injected for you. - The secret keys bypass RLS, so they belong in functions and never in a browser.
The browser-side rule is the mirror image: nothing secret in VITE_ variables or frontend code. If a secret key ever shipped to the browser or into git, rotate it; leaked service_role key and secrets in git history walk through that. The overview of which keys may live where is in API keys in AI-built apps.
Does CORS protect my function?
No, and that misunderstanding causes both over- and under-protection. CORS headers tell a browser which other websites may read your function’s responses. They don’t stop curl, scripts or servers, which ignore CORS entirely.
Browsers need the headers to call your function at all, so every function that the frontend calls must answer the OPTIONS preflight. withSupabase does this for you; its default headers come from @supabase/supabase-js/cors and allow any origin (*). Without the wrapper, Supabase’s docs recommend importing corsHeaders from npm:@supabase/supabase-js@^2/cors so the allowed request headers stay in sync with the client library.
Is * dangerous? For a function that authenticates with a bearer token in the Authorization header, another website can’t read anything useful, because it doesn’t have the user’s token. It becomes dangerous when a function authenticates with cookies and reflects any origin together with Access-Control-Allow-Credentials: true; see CORS wildcard with credentials. As defence in depth, you can still allow only your own site:
import { withSupabase } from "npm:@supabase/server@1";
export default {
fetch: withSupabase(
{
auth: "user",
cors: {
headers: {
"Access-Control-Allow-Origin": "https://your-app.example",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
"Access-Control-Allow-Methods": "POST, OPTIONS",
Vary: "Origin",
},
},
},
async (_req, ctx) => Response.json({ id: ctx.userClaims?.id }),
),
};If the browser later complains about a blocked header, add that header to the list rather than going back to defaults you don’t understand. The longer explanation is in CORS explained for vibe coders.
Validate every input
TypeScript types disappear at runtime. A body typed as { tripId: string } can arrive as a number, an object, a 5 MB string or nothing at all. Check the shape before you use it, and reject everything else with a 400:
import { withSupabase } from "npm:@supabase/server@1";
import { z } from "npm:zod@4";
const Body = z.object({
tripId: z.uuid(),
note: z.string().trim().min(1).max(2000),
});
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const parsed = Body.safeParse(await req.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Invalid input" }, { status: 400 });
const { tripId, note } = parsed.data;
const { error } = await ctx.supabase.from("trip_notes").insert({
trip_id: tripId,
user_id: ctx.userClaims!.id,
body: note,
});
if (error) return Response.json({ error: "Could not save" }, { status: 400 });
return Response.json({ ok: true });
}),
};Notice what the schema does not contain: no userId, no price, no role, no status. Fields the server decides must not be accepted from the client at all. Length limits matter too, especially for text you pass to an AI model, where every extra token costs money and can carry prompt injection.
Rate-limit the expensive calls
A function that calls an AI model, sends e-mails or hits a paid API is a way for anyone with an account (or a script with many accounts) to spend your money. Rate limiting caps how often one user can call it.
Supabase’s own example uses Upstash Redis and limits by the user ID from Supabase Auth. If you’d rather keep it in your database, a small counter works for moderate traffic. Each call adds one to the caller’s counter for the current time window and says whether they are still under the limit:
create table public.api_usage (
user_id uuid not null references auth.users (id) on delete cascade,
window_start timestamptz not null,
calls integer not null default 0,
primary key (user_id, window_start)
);
alter table public.api_usage enable row level security;
revoke all on table public.api_usage from anon, authenticated;
create or replace function public.consume_rate_limit(
p_user uuid,
p_limit integer,
p_window_seconds integer
)
returns boolean
language plpgsql
set search_path = ''
as $$
declare
v_window timestamptz := to_timestamp(
floor(extract(epoch from now()) / p_window_seconds) * p_window_seconds
);
v_calls integer;
begin
insert into public.api_usage as u (user_id, window_start, calls)
values (p_user, v_window, 1)
on conflict (user_id, window_start)
do update set calls = u.calls + 1
returning u.calls into v_calls;
return v_calls <= p_limit;
end;
$$;
revoke execute on function public.consume_rate_limit(uuid, integer, integer)
from public, anon, authenticated;
grant execute on function public.consume_rate_limit(uuid, integer, integer)
to service_role;The two revoke lines matter. Supabase grants new functions in public to anon and authenticated by default (and new tables too in projects that still use the old default), and Postgres lets everyone execute a new function. Without the revokes, a user could call the function with someone else’s ID, or reset their own counter. Only your function, with the secret key, can call it:
import { withSupabase } from "npm:@supabase/server@1";
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const { data: allowed, error } = await ctx.supabaseAdmin.rpc("consume_rate_limit", {
p_user: ctx.userClaims!.id,
p_limit: 20,
p_window_seconds: 3600,
});
if (error) return Response.json({ error: "Try again later" }, { status: 503 });
if (!allowed) {
return Response.json(
{ error: "Too many requests" },
{ status: 429, headers: { "Retry-After": "3600" } },
);
}
// ... call the AI provider with a key that stays on the server
return Response.json({ ok: true });
}),
};A rate limit per user is not a budget. Also set a hard spending cap at your AI provider; see no AI spend cap and the full guide on rate limiting for AI-built apps.
Webhooks and cron jobs: verify_jwt off, your own check on
Some callers never have a user token. Stripe, GitHub and other providers sign their requests with their own secret; cron jobs and database webhooks send your secret key. For those, Supabase’s docs say to turn the platform check off for that one function:
[functions.stripe-webhook]
verify_jwt = falseTurning it off moves all the responsibility into your code:
- Provider webhooks must verify the provider’s signature over the raw body before doing anything. Supabase’s own Stripe example uses
constructEventAsyncwith Stripe’sSubtleCryptoProvider, because the synchronous version fails on Deno. The full pattern is in Stripe in vibe-coded apps. - Cron jobs and internal calls should send a secret key on the
apikeyheader and useauth: "secret"(or a named key like"secret:automations") so only that caller gets in. - Truly public functions, like a health check, use
auth: "none"and must not touch private data.
Log enough to debug, not enough to leak
Supabase’s logging docs say invocation logs keep the method, path, status, execution time and a few headers, and that request and response bodies are not kept. What you write with console.log is kept, though. That’s where personal data leaks happen: a debug line that prints the whole body, the user’s e-mail or the Authorization header, readable later by anyone with dashboard access.
console.log("checkout failed", { body, email: user.email, auth: req.headers.get("Authorization") });console.error("checkout failed", { userId, step: "create_session", code: err.code ?? "unknown" });Log the user ID, the step and an error code. Return a short, generic message to the client; stack traces and database errors in responses help attackers map your schema. More in personal data in logs or error messages.
A fix prompt for your AI builder
Paste this into Lovable, Cursor, Claude Code or Bolt, then review every change before you deploy:
Review every function in supabase/functions. For each one:
- Identify the caller from the verified token only. Use withSupabase with auth: “user” from npm:@supabase/server@1 if the project uses the new sb_publishable and sb_secret keys; otherwise create a supabase-js client with the caller’s Authorization header and call auth.getClaims(token). Remove every user ID, owner ID or role that is read from the request body or query string.
- Run queries with the caller-scoped client so RLS applies. Use the secret or service role key only for steps the caller cannot do through RLS, after checking access with the caller-scoped client, and filter those queries by the verified user ID.
- Never return an environment secret in a response. If a function returns an API key, change it to call the provider itself and return only the result.
- Validate the request body with a zod schema that lists only the fields the client may set, with length limits. Respond 400 on invalid input.
- Keep verify_jwt on in supabase/config.toml for every function users call. For functions with verify_jwt off, show me how each one authenticates its caller (webhook signature or secret key).
- Replace console.log calls that print bodies, e-mail addresses, tokens or headers with logs of the user ID, step and error code.
Do not change the database schema. List every function you changed and what you changed in it.
What our audit reports for these bugs
We keep small, deliberately broken test apps to measure ShipRely’s audit engine. Three of the functions in this guide come from them. In our latest benchmark run on 3 December 2026, the Security audit reported all three:
get-ai-keyreturning the OpenAI key to any unauthenticated caller, rated critical.list-tripsreading any user’s trips by a body-supplieduserIdwith the service role client, rated high. The misleading “verify_jwt is on” comment in that function is there on purpose; the engine must not take it at face value.export-projectreturning any project and its tasks without a membership check, rated critical.
Each finding points to the function file, says why it matters and comes with a fix prompt. The same test apps also contain correct functions (for example a checkout function that verifies the user and reads data under RLS), and the audit must stay quiet about those.
Checklist before you launch
Edge Functions launch checklist
0/10 done
Your progress is saved in this browser only.
Frequently asked questions
Is verify_jwt enough to secure a Supabase Edge Function?
No. verify_jwt makes the platform reject requests without a valid token before your code runs, which is a useful first gate. Supabase’s docs also say the check still accepts the new publishable and secret API keys for migration compatibility. It does not tell your code which user is calling or what they may touch. Your function still has to read the user from the verified token and check access to every record.
Can I take the user ID from the request body if the user is signed in?
No. The body is written by whoever sends the request, so anyone can put another person’s ID there. Read the user ID from the verified token (ctx.userClaims with @supabase/server, or getClaims on a caller-scoped client) and ignore any user ID in the body.
When should an Edge Function use the secret or service_role key?
Only for the one step the caller is not allowed to do themselves, such as writing an audit row or updating billing state from a webhook. Check the caller’s access first with a client that carries their token, then filter every admin query by the verified user ID.
Should I turn off verify_jwt to fix a 401 error?
Not for a function your users call. A 401 usually means the request carried the wrong credential, for example an API key in the Authorization header. Turn verify_jwt off only for functions that are called without a user token, such as a Stripe webhook that checks its own signature, or a cron job that checks a secret key.
Does Supabase log request bodies of Edge Functions?
According to Supabase’s logging docs, invocation logs keep the method, path, status, timing and a few headers, but not request or response bodies. Whatever you print with console.log does end up in the logs, so log IDs and error codes, not e-mail addresses, tokens or payloads.
Sources
- 1.Securing Edge Functions — Supabase Docs
- 2.Authorization headers — Supabase Docs
- 3.CORS support for invoking from the browser — Supabase Docs
- 4.Environment variables — Supabase Docs
- 5.Edge Functions logging — Supabase Docs
- 6.Rate Limiting Edge Functions — Supabase Docs
- 7.API1:2023 Broken Object Level Authorization — OWASP API Security Top 10
- 8.CWE-639: Authorization Bypass Through User-Controlled Key — MITRE