Supabase "Invalid API key" or "Legacy API keys are disabled": find the wrong key and fix it

By AI App Medic · Updated · Supabase · API keys · Auth · Env variables

Your app loads, but every Supabase request fails. In the browser Network tab, or in the logs of an Edge Function or a cron job, you see one of these responses with status 401:

{"message":"Invalid API key","hint":"Double check your Supabase `anon` or `service_role` API key."}
{"message":"Invalid API key","hint":"Double check the provided API key for typos. This API key might also be owned by another Supabase project."}
{"message":"Legacy API keys are disabled","hint":"Your legacy API keys (anon, service_role) were disabled on 2026-11-02T14:10:11+00:00. Re-enable them in the Supabase dashboard, or use the new publishable and secret API keys."}

Or AuthApiError: Invalid API key from supabase-js, or No API key found in request with the response header sb-error-code: UNAUTHORIZED_MISSING_API_KEY. Sometimes the app never gets that far and the console shows supabaseKey is required. when the client is created.

These are all key problems, not database problems, and nothing you change in RLS will fix them. It usually starts right after a deploy to a new host, after someone "cleaned up" keys in the Supabase dashboard, or after a project was remixed or copied from a template.

Two kinds of Supabase keys

Supabase now has two key systems that work side by side:

Creating the new keys does not turn the old ones off. Disabling legacy keys is a separate switch in Settings, API Keys, and when someone flips it, every client that still sends an eyJ key gets Legacy API keys are disabled. Supabase's API keys documentation says the legacy keys are deprecated in early 2027, so even if nothing is broken today, this is worth doing now.

Step 1: find the key your deployed app really sends

Do not trust your local .env. Check the live app:

  1. Open the deployed site, then DevTools, Network.
  2. Filter on supabase.co and click a failing request.
  3. Under Request Headers, look at apikey.

Then compare:

Step 2: check the key belongs to the same project as the URL

This is the most common cause after a remix, a template clone, or a second Supabase project for staging. The URL points at one project and the key at another. A legacy key carries its project ref inside. Decode the middle part on your own machine (do not paste keys into websites):

echo 'PASTE_THE_KEY' | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null; echo

You get something like:

{"iss":"supabase","ref":"abcdefghijklmnop","role":"anon","iat":1712000000,"exp":2027000000}

The ref must match the subdomain in your Supabase URL, https://abcdefghijklmnop.supabase.co, and role should be anon for browser code. If the ref differs, copy the URL and the key again from the same project.

New keys do not carry a readable ref. Open the project that matches your URL, go to Settings, API Keys, and compare the first characters. A quick test from a terminal tells you whether the project accepts the key at all:

curl -s -o /dev/null -w "%{http_code}\n" \
  "https://YOUR-PROJECT-REF.supabase.co/auth/v1/health" \
  -H "apikey: YOUR_KEY"

200 means the key is valid for that project. 401 means it is not. Do not test a publishable key against /rest/v1/ on its own: that root route only accepts secret keys and returns 401 for a publishable key that is perfectly fine.

If the ref matches and the key still fails, someone may have rotated the legacy JWT secret. That invalidates the old anon and service_role keys at once. Copy the current keys from the dashboard, or better, move to the new keys.

Step 3: fix the environment variables on the host

Works locally, fails after deploy: the host does not have the variable, or has it under a different name. The browser only sees variables with your framework's public prefix:

# Vite (Lovable, Bolt)
VITE_SUPABASE_URL=https://YOUR-PROJECT-REF.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=sb_publishable_...

# Next.js (Cursor, v0)
NEXT_PUBLIC_SUPABASE_URL=https://YOUR-PROJECT-REF.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_...

# Server only. Never give these a public prefix.
SUPABASE_URL=https://YOUR-PROJECT-REF.supabase.co
SUPABASE_SECRET_KEY=sb_secret_...

Then check three things that cause most of these failures:

More on build-time variables: Bolt app works in preview, breaks on Netlify and Next.js environment variables undefined on Vercel.

Step 4: switch the frontend to the publishable key

Create the new keys in Settings, API Keys, on the Publishable and secret API keys tab. If you only see a Create new API keys button, the project has never had them. Creating them is safe; the legacy keys keep working until you disable them.

Then swap the key in the browser client:

import { createClient } from '@supabase/supabase-js'

export const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY // was the anon key (eyJ...)
)

Update @supabase/supabase-js to a current 2.x release while you are there. The publishable key resolves to the same anon role, and to authenticated once a user signs in, so your RLS policies behave exactly as before. Signed-in users keep their sessions.

supabase-js puts the key in the apikey header for you. If you have hand-written fetch calls to /rest/v1 or /auth/v1, send the new key on apikey. New keys are not JWTs, so anything that tries to verify one from Authorization: Bearer fails.

Step 5: keep the secret key out of the browser

If the failing request from the browser carries sb_secret_..., Supabase is doing its job: it blocks secret keys in browsers and returns 401. Do not look for a way around that. The secret key bypasses every RLS policy, so it belongs in a server route or an Edge Function that checks who is calling first. Because it was shipped in your JavaScript, assume someone has it: create a new secret key, update every backend, then delete the old one. The same applies to a legacy service_role key in the frontend; see service role key exposed in the frontend and which VITE_ variables end up public.

Step 6: fix Edge Functions, cron jobs and webhooks

The browser is often fixed first and the server side is forgotten. After legacy keys are disabled, these break quietly:

import { createClient } from 'npm:@supabase/supabase-js@2'

const secretKeys = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS')!)
const supabaseAdmin = createClient(Deno.env.get('SUPABASE_URL')!, secretKeys['default'])

Supabase also offers the @supabase/server SDK, which checks the caller's key and hands you an admin client without your code touching the key. Whichever you use, a function that is called with a key instead of a user's token needs verify_jwt = false and its own check in code, because the platform check alone does not authenticate a caller that sends only an API key. If the function returns 401 for signed-in users, that is a token problem, covered in Edge Function 401 Invalid JWT.

select vault.create_secret('sb_secret_...', 'cron_function_key');

select cron.schedule('daily-report', '0 6 * * *', $$
  select net.http_post(
    url := 'https://YOUR-PROJECT-REF.supabase.co/functions/v1/daily-report',
    headers := jsonb_build_object(
      'Content-Type', 'application/json',
      'apikey', (select decrypted_secret from vault.decrypted_secrets where name = 'cron_function_key')
    ),
    body := '{}'::jsonb
  );
$$);

To find what still uses legacy keys before you disable them, search the repo and your hosting settings for eyJ, anon and service_role, and run select jobname, command from cron.job; to read the cron jobs.

Disable the legacy keys last

Once the frontend, every function, every job and every integration use the new keys, disable the legacy keys in Settings, API Keys. Watch the API Gateway logs for a day. If something you missed starts failing, you can re-enable them, fix the straggler and try again. The exception is a leak: if a legacy key leaked, leave them disabled and fix the clients.

Prevention

FAQ

Is the publishable key safe in the browser?

Yes, it is meant for the browser, the same way the old anon key was. It only reaches what your Row Level Security policies allow, so the protection comes from RLS, not from hiding the key. The secret key is different: it bypasses RLS and must never be in frontend code.

Should I just re-enable the legacy keys?

As a short stopgap while you find the last place that uses them, yes. Supabase documents disabling as reversible, under Settings, API Keys, Legacy API keys. Do not re-enable them if they were turned off because a key leaked. And plan the move anyway, since Supabase's docs say the anon and service_role keys are deprecated in early 2027.

Do I have to change my RLS policies when I switch keys?

No. The publishable key maps to the same anon role, or authenticated once a user signs in, and the secret key maps to service_role. Policies written for anon and authenticated keep working as they are.

Why does the secret key fail in the browser but work in curl?

Supabase blocks secret keys when the request looks like it comes from a browser, based on the User-Agent header, and returns 401. That is on purpose. Move that code to a server route or an Edge Function. If the key was ever shipped to the browser, treat it as leaked and replace it.

My mobile app still ships the old anon key. What happens if I disable legacy keys?

Every installed copy that still has the old key stops working, and users have to update. Ship a release with the publishable key, wait until most users are on it, and only then disable the legacy keys.

Related guides