Supabase Edge Function returns 401 "Invalid JWT": find who rejected the call and fix it
By AI App Medic · Updated · Supabase · Edge Functions · Auth · Lovable
Your app calls an Edge Function, nothing happens, and the Network tab shows a 401 with one of these bodies:
{"code":"UNAUTHORIZED_INVALID_JWT_FORMAT","message":"Invalid JWT"}
{"code":401,"message":"Missing authorization header"}
In the app itself, supabase.functions.invoke usually surfaces it as FunctionsHttpError: Edge Function returned a non-2xx status code, which tells you nothing. This shows up a lot in Lovable and Bolt projects because the AI writes the function, deploys it, and calls it with whatever key happens to be in the front end. The fix depends on one question: who rejected the request?
Step 1: find out who sent the 401
Supabase Edge Functions have a built-in check, controlled by verify_jwt, that runs before your code. It is on by default. When it fails, your function never starts. When it passes, your code can still return its own 401.
Add one log line at the very top of the handler and redeploy:
Deno.serve(async function (req) {
console.log("hit", req.method, new URL(req.url).pathname);
// ...
});
Then open Edge Functions, pick the function, and look at Logs and Invocations. A 401 in Invocations with no hit line in Logs means the platform rejected it. A hit line followed by a 401 means your code did. The rest of this guide covers the platform case first, since it is the common one.
Step 2: read the headers that were actually sent
In DevTools, click the failed request and look at the request headers. You are looking for two of them:
Authorization: Bearer ...carries a JWT. For a signed-in user that is their session access token. With legacy keys, the anon key also works here, because it is a JWT.apikey: ...carries the project API key.
Copy the value after Bearer and decode the middle part in the console. A JWT has three parts separated by dots:
const t = "PASTE_TOKEN_HERE";
console.log(JSON.parse(atob(t.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))));
Check three fields. exp is a Unix timestamp, so compare it with Date.now() / 1000. iss or ref must match your project ref, the subdomain in your Supabase URL. role should be authenticated for a user call. If the decode throws, the value is not a JWT, which leads to the most common cause below.
The causes, in the order we see them
1. A new API key sent as a Bearer token
Supabase is replacing the anon and service_role keys with publishable (sb_publishable_...) and secret (sb_secret_...) keys, and the legacy keys are being deprecated by the end of 2026. The new keys are not JWTs. If your code, or an example the AI copied, sends Authorization: Bearer sb_publishable_..., the platform tries to parse it as a JWT and returns Invalid JWT.
The rule is simple: API keys go in apikey, user tokens go in Authorization. A signed-in call sends both:
const { data: { session } } = await supabase.auth.getSession();
const res = await fetch(`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/generate-report`, {
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({ reportId }),
});
If the function has no signed-in user to check, for example a public form, send only apikey and turn verify_jwt off for that function (Step 4).
2. No Authorization header at all
Missing authorization header almost always means a plain fetch or an HTML form posting straight to the function URL. The simplest fix is to stop calling the URL by hand and use the client, which attaches the current session token and the API key for you:
const { data, error } = await supabase.functions.invoke("generate-report", {
body: { reportId },
});
3. An expired or missing session
Access tokens are short-lived, an hour by default. Code that stored a token in state, in localStorage under its own key, or in a module variable keeps sending it after it expires. Another version of this bug is calling the function on page load before the session is restored, so the anon key is sent and a function that expects a user rejects it. Always read the session right before the call, and wait for it on first load. If the session itself is broken and refresh fails, the Invalid Refresh Token: Refresh Token Not Found guide covers that side.
4. A key or token from the wrong project
Remixed Lovable projects, a staging project, or an old .env on Vercel or Netlify can leave the front end pointing at one project while the function lives in another. The decoded iss shows which project issued the token. Fix the environment variables on the host and rebuild, because Vite bakes them in at build time.
5. The project moved to asymmetric JWT signing keys
Newer projects, and older ones that rotated to the new signing keys, issue user tokens signed with asymmetric keys. Supabase documents that the legacy verify_jwt check only understands the legacy format and recommends turning it off and checking auth in your code. If valid, fresh user tokens still get Invalid JWT, this is the likely reason.
6. A caller that never has a Supabase token
Stripe, GitHub, a cron job, pg_net or a database webhook cannot send a user JWT. These functions need verify_jwt off and their own check, such as a signature or a shared secret. For Stripe specifically, see Stripe webhook not working in a Supabase Edge Function.
Step 3: turn the check off the right way
Set it per function in supabase/config.toml, which is the file Lovable and the CLI read on deploy:
[functions.generate-report]
verify_jwt = false
Or deploy with supabase functions deploy generate-report --no-verify-jwt. You can also flip the toggle on the function page in the dashboard, but if the setting is not in config.toml, the next deploy can turn the check back on and the 401 returns with no code change.
Step 4: check the caller in your own code
Turning off verify_jwt without adding a check makes the function public. For a function that only signed-in users should call, verify the token in the handler:
import { createClient } from "npm:@supabase/supabase-js@2";
const cors = {
"Access-Control-Allow-Origin": "https://your-app.com",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
Deno.serve(async function (req) {
if (req.method === "OPTIONS") return new Response("ok", { headers: cors });
const authHeader = req.headers.get("Authorization") ?? "";
const token = authHeader.replace("Bearer ", "");
if (!token) return new Response("Unauthorized", { status: 401, headers: cors });
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: authHeader } } },
);
const { data, error } = await supabase.auth.getUser(token);
if (error || !data.user) return new Response("Unauthorized", { status: 401, headers: cors });
// data.user.id is the verified caller. Queries through this client run under their RLS.
return Response.json({ ok: true }, { headers: cors });
});
On projects using the new keys, read the publishable key from SUPABASE_PUBLISHABLE_KEYS instead of SUPABASE_ANON_KEY, or use Supabase's @supabase/server package, whose withSupabase({ auth: "user" }) wrapper does this check for you. With asymmetric signing keys, supabase.auth.getClaims(token) verifies the token locally and skips the round trip to the Auth server.
Note the CORS headers on the 401 responses. Without them, the browser hides your 401 and reports a CORS error instead. If that is what you are seeing, read Lovable + Supabase Edge Function CORS errors next.
If your own code returns the 401
Look for a role check, an admin flag lookup or a missing secret. A frequent one: the function reads Deno.env.get("SOME_SECRET"), the secret was set in local .env but never added under Edge Functions, Secrets, so the comparison fails for every request.
Prevention
Decide the auth model for each function when you create it: signed-in user, server-to-server secret, signed webhook, or truly public. Write it down in config.toml next to the function name. Call functions through supabase.functions.invoke wherever you can. Never put the secret or service role key in the front end to make a 401 go away, since that hands full database access to every visitor. When you migrate to the new API keys, search the codebase for Bearer and check each place that sends a key.
FAQ
What is the difference between Invalid JWT and Missing authorization header?
Both come from the platform check that runs before your function. Missing authorization header means the request had no Authorization header at all, usually a plain fetch call. Invalid JWT means a header was sent but the value is not a valid token for this project: expired, from another project, or not a JWT at all, like a publishable key.
Is it safe to turn off verify_jwt?
Only if your function checks the caller itself. With the check off, anyone who knows the URL can call it. That is fine for a Stripe webhook that verifies the signature, and dangerous for a function that calls OpenAI or reads user data without checking who is asking.
Why did it work yesterday and fail today?
The usual reasons are an expired session in a tab that was left open, a switch to the new publishable and secret keys, a change to asymmetric JWT signing keys, or a redeploy that reset verify_jwt because the setting was flipped in the dashboard but not saved in config.toml.
Why does the browser say CORS error instead of 401?
If a response comes back without CORS headers, the browser hides it and reports a CORS failure. Your own 401 responses need the same CORS headers as your success responses, or you will be debugging the wrong error.
Related guides
- Lovable + Supabase Edge Function CORS error: why the browser says failed to fetch
- Stripe webhook not working in a Supabase Edge Function: 401s, signature errors and missing upgrades
- Supabase AuthApiError: Invalid Refresh Token: Refresh Token Not Found
- Supabase auth email not sending in a Lovable app: the SMTP setup that actually works
- Supabase login redirects to localhost (or the preview URL) after deploy: how to fix it