Short answer: every Supabase Edge Function is a public URL that anyone can call. The built-in verify_jwt check only confirms the request carries a JWT signed for your project, and the legacy anon key that ships in your frontend is itself such a JWT, so that check alone does not mean a real user is signed in. Inside each function, read the Authorization header, call supabase.auth.getUser(token) to get the actual user, take the user ID from that result (never from the request body), keep the service role key server-side and use it only after you've checked who is asking, and verify signatures on webhook functions that have JWT verification turned off.
Lovable, Bolt and Cursor love Edge Functions. Anything that needs a secret (calling OpenAI, sending email, creating a Stripe checkout, running admin actions) gets moved into a function, which is the right instinct. The problem is that the generated function often trusts whatever the browser sends and then does the work with full database privileges.
Why the default JWT check is not enough
By default, Supabase checks that requests to a function include a valid JWT in the Authorization header. If you use the legacy keys, the anon key is a long-lived JWT with role: anon. It's in your JavaScript bundle, so anyone can copy it and send:
curl -X POST https://<project>.supabase.co/functions/v1/send-invoice \
-H "Authorization: Bearer <your public anon key>" \
-H "Content-Type: application/json" \
-d '{"user_id": "someone-elses-id"}'
That passes the gateway check. If the function then does whatever the body says with the service role key, an attacker can act as any user. Many functions are also deployed with --no-verify-jwt (or verify_jwt = false in supabase/config.toml) to get past errors during development, which removes even that check.
Treat the gateway check as a convenience. Do the real authentication inside the function.
Step 1: Get the real user inside the function
Create a Supabase client that forwards the caller's token, then ask Supabase Auth who it belongs to:
import { createClient } from "npm:@supabase/supabase-js@2";
Deno.serve(async (req) => {
const authHeader = req.headers.get("Authorization") ?? "";
const token = authHeader.replace("Bearer ", "");
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: authHeader } } }
);
const { data: { user }, error } = await supabase.auth.getUser(token);
if (error || !user) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { "Content-Type": "application/json" },
});
}
// From here on, use user.id. Never trust a user_id from the body.
const { data, error: dbError } = await supabase
.from("invoices")
.select("*")
.eq("user_id", user.id);
return Response.json({ data, error: dbError?.message });
});
Two things make this safe. First, getUser(token) asks Supabase Auth to validate the token and returns the real user, so a bare anon key gets rejected. Second, because the client forwards the user's own token, database queries run as that user and your RLS policies still apply. The same reasoning is why getUser beats getSession on the server.
Step 2: Use the service role key only after an authorization check
Edge Functions get SUPABASE_SERVICE_ROLE_KEY as an environment variable, and it bypasses RLS completely. AI-generated functions often create one service role client at the top and use it for everything. That turns every function into a way around your database rules.
Use the service role only for the specific operation that needs it, and only after you've confirmed the caller is allowed:
// After getUser() succeeded
const { data: roleRow } = await supabase
.from("user_roles")
.select("role")
.eq("user_id", user.id)
.single();
if (roleRow?.role !== "admin") {
return new Response("Forbidden", { status: 403 });
}
const admin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
await admin.auth.admin.deleteUser(targetUserId);
Don't decide admin status from user_metadata, which users can edit themselves. See how to add admin roles in Supabase securely.
If the function accepts an ID for a record (an order, a document, a project), check that the record belongs to user.id before acting on it, even with the service role. Skipping this is the classic IDOR bug.
Step 3: Keep secrets in Supabase secrets, not in code
Set secrets with the CLI or the dashboard (Edge Functions, then Secrets):
supabase secrets set OPENAI_API_KEY=sk-... STRIPE_SECRET_KEY=sk_live_...
Read them with Deno.env.get("OPENAI_API_KEY"). Things to check in your repo:
- No keys hardcoded in
supabase/functions/**/index.ts. AI tools sometimes paste the key in "temporarily". - No
.envfile with real values committed undersupabase/functions/. Add it to.gitignore. - The function never returns a secret, the full upstream error object, or
Deno.env.toObject()in a response or log.
If a key was ever committed, removing it is not enough. Rotate it and check whether it leaked on GitHub.
Step 4: Handle CORS deliberately
Browser calls to a function need CORS headers and a response to the OPTIONS preflight. The generated version is almost always Access-Control-Allow-Origin: *:
const allowed = ["https://yourapp.com", "http://localhost:5173"];
function corsHeaders(origin: string | null) {
return {
"Access-Control-Allow-Origin": origin && allowed.includes(origin) ? origin : allowed[0],
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Vary": "Origin",
};
}
Deno.serve(async (req) => {
const headers = corsHeaders(req.headers.get("Origin"));
if (req.method === "OPTIONS") return new Response("ok", { headers });
// ... auth check, then work
return new Response(JSON.stringify({ ok: true }), {
headers: { ...headers, "Content-Type": "application/json" },
});
});
Be clear on what CORS does: it stops other websites from reading responses in a visitor's browser. It does not stop curl or a script, so it is never a replacement for Step 1. More detail in our CORS guide.
Step 5: Secure webhook functions
Stripe, Resend, GitHub and other services can't send a Supabase user JWT, so webhook functions are deployed with JWT verification off:
# supabase/config.toml
[functions.stripe-webhook]
verify_jwt = false
That makes the function fully open, so it must verify the provider's signature before doing anything. For Stripe in Deno, use the async verifier with the Web Crypto provider and the raw body:
import Stripe from "npm:stripe";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
const cryptoProvider = Stripe.createSubtleCryptoProvider();
Deno.serve(async (req) => {
const signature = req.headers.get("Stripe-Signature");
const body = await req.text(); // raw body, not parsed JSON
let event;
try {
event = await stripe.webhooks.constructEventAsync(
body,
signature!,
Deno.env.get("STRIPE_WEBHOOK_SECRET")!,
undefined,
cryptoProvider
);
} catch {
return new Response("Invalid signature", { status: 400 });
}
// handle event.type ...
return new Response("ok");
});
The same rules from our Stripe webhook signature guide apply: verify first, handle duplicate deliveries, and look up amounts from Stripe rather than trusting metadata the browser set.
Only turn off verify_jwt for functions that really receive third-party webhooks or run on a schedule with their own shared secret. Every other function should keep it on and also do Step 1.
Step 6: Validate input and limit abuse
- Parse the body and reject anything unexpected. A small check with
zodor plaintypeoftests is enough to stop most surprises. - Don't pass raw user input into SQL strings, shell commands, or
fetchURLs. A function that fetches any URL the user supplies is a server-side request forgery risk. - Functions that call paid APIs (OpenAI, Anthropic, email sending) need a per-user limit, or one person can run up your bill. Store counts in a table keyed by
user.idand reject requests over the limit. Our rate limiting guide shows the pattern. - Return generic error messages to the client and log details server-side.
How to test your own functions
Run these against each function in supabase/functions/:
- Call it with only the public anon key (or publishable key) and no user token. It should return 401.
- Sign in as user A and call it with user B's IDs in the body. It should return 403 or only act on user A's data.
- For webhook functions, send a request with no signature or a made-up one. It should return 400.
- From a different website's origin, check that the browser blocks reading the response.
- Search the function code for
SUPABASE_SERVICE_ROLE_KEYand confirm every use happens after an auth and ownership check.
Related guides
Get an automated check
PreflightPR reviews AI-built apps for Edge Functions that trust the request body, service role keys used without auth checks, unsigned webhooks, missing RLS and leaked keys. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to check every pull request before it merges.