Short answer
The Supabase secret key (sb_secret_…, or the legacy service_role key) maps to a role that bypasses row level security. If it is in your frontend, for example in a VITE_ variable, every visitor can copy it and read, change or delete all data, and manage your users. Rotate the key first, then remove it from the browser code and move the admin action into an edge function that checks the caller before using the key.
Ask an AI about this page:ChatGPTClaude
On this page
The Supabase secret key (sb_secret_…, or the legacy service_role key) skips every row level security policy. If it is anywhere in your frontend code, every visitor can copy it from your JavaScript and use it to read, change or delete all data, and to list, create or delete your users. It is rated critical: it takes no account and no skill, and no policy you wrote can stop it.
Why it matters
Supabase’s docs describe two kinds of keys. The publishable key (or legacy anon key) belongs in the browser and is limited by your policies. The secret key (or legacy service_role key) maps to the service_role database role, which has the BYPASSRLS attribute. You can see that in any Supabase project:
select rolname, rolbypassrls
from pg_roles
where rolname in ('anon', 'authenticated', 'service_role')
order by rolname;Only service_role shows true. The key usually ends up in the frontend because an admin feature didn’t work with the normal key. This is the pattern from one of our test apps:
const SERVICE_ROLE_KEY = import.meta.env.VITE_SUPABASE_SERVICE_ROLE_KEY as string;
export const supabaseAdmin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
auth: { persistSession: false, autoRefreshToken: false },
});Vite puts every VITE_ variable into the JavaScript it builds, so the key ships to every visitor even though the admin page itself checks the user’s role first. Our audit engine found this in our test apps and reported it as a critical finding, pointing at the admin client, the admin page that uses it and the .env.example that documents the variable.
How to find it in your app
Search your source and env files for the names:
grep -rnE "service_role|SERVICE_ROLE|sb_secret_|SECRET_KEY" src/ .env* 2>/dev/nullThen check what actually ships. After npm run build, new-style secret keys are easy to spot because they start with sb_secret_. Legacy keys are JWTs (long strings starting with eyJ) and the word service_role is hidden inside their encoded middle part, so a plain search misses them. This one-liner lists every JWT in your build with the role it carries:
node -e 'const fs=require("fs"),path=require("path");const walk=(d)=>fs.readdirSync(d,{withFileTypes:true}).flatMap((e)=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)]);for(const f of walk("dist"))for(const t of fs.readFileSync(f,"utf8").match(/eyJ[\w-]+\.eyJ[\w-]+\.[\w-]+/g)??[])console.log(f,JSON.parse(Buffer.from(t.split(".")[1],"base64url")).role)'anon is fine. service_role means the secret key is public. On your live site you can do the same check in the browser: open DevTools, search all sources (Ctrl+Shift+F, or Cmd+Option+F on a Mac) for sb_secret_ and eyJ.
How to fix it
Rotate the key first
Assume the key is known. For a new-style secret key, create a new one in Settings → API Keys, put it into your servers and edge functions, then delete the leaked one. For the legacy service_role key, Supabase’s docs note that creating new keys does not revoke the legacy ones: switch your servers to the new secret key, then disable the legacy keys on the same page. The leaked service_role key guide walks through the first hour.
Remove the key from the frontend
Delete the admin client from src/, remove VITE_SUPABASE_SERVICE_ROLE_KEY from every .env file and from your hosting settings, and rebuild. Secret values for edge functions belong in the function secrets, never in a VITE_ variable (see secret key in a VITE_ variable).
Move the admin action to an edge function
The function checks who is calling, and only then uses the key from its environment:
import { createClient } from "npm:@supabase/supabase-js@2";
Deno.serve(async (req) => {
const url = Deno.env.get("SUPABASE_URL")!;
const asCaller = createClient(url, Deno.env.get("SUPABASE_ANON_KEY")!, {
global: { headers: { Authorization: req.headers.get("Authorization") ?? "" } },
});
const { data: { user } } = await asCaller.auth.getUser();
if (!user || user.app_metadata?.role !== "admin") {
return new Response("Forbidden", { status: 403 });
}
const admin = createClient(url, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!);
const { data, error } = await admin.auth.admin.listUsers({ page: 1, perPage: 200 });
if (error) return new Response("Could not list users", { status: 500 });
return Response.json(data.users.map((u) => ({ id: u.id, email: u.email })));
});app_metadata can only be written with the secret key, so users cannot give themselves the admin role there. The frontend calls supabase.functions.invoke("admin-list-users") with its normal client. The sketch leaves out CORS headers; add the ones your project already uses.
The Supabase service role key is used in browser code through import.meta.env.VITE_SUPABASE_SERVICE_ROLE_KEY (in src/lib/admin.ts or similar). Remove every browser-side Supabase client that uses it and remove the variable from all .env files. Move each admin operation it performed into a Supabase edge function that reads the key with Deno.env.get, verifies the caller with auth.getUser() using the Authorization header, and returns 403 unless the user’s app_metadata role is admin. Change the frontend to call these functions with supabase.functions.invoke.
Do not put the key or any other secret into a VITE_ variable or into source code. Remind me to rotate the key in the Supabase dashboard, because it was exposed.
Check that the fix works
Build the app again and run both searches from “How to find it”: the source search must find nothing in src/, and the build check must show no service_role role and no sb_secret_ string. Open your live site, search the sources in DevTools once more, and sign in as a non-admin: calling the admin function must return 403. Finally, try the old key from a terminal against your project; after rotation it must be rejected. The secret key in a VITE_ variable fix covers other secrets with the same problem.
Frequently asked questions
How is the service_role key different from the anon or publishable key?
The publishable (or legacy anon) key is meant for the browser and is limited by your RLS policies. The secret (or legacy service_role) key maps to the service_role database role, which has the BYPASSRLS attribute and ignores every policy.
Is it enough to delete the key from my code?
No. Anyone who loaded your site while the key was in it may have a copy, and old builds may still be cached. Rotate the key first, then remove it from the code.
Supabase says secret keys don’t work in browsers. Am I safe?
No. Supabase rejects requests with a secret key that come from a browser, but the docs themselves point out that a leaked key still works from other tools. Anyone who copied it from your JavaScript can use it from a script or a server.
Where should admin features run instead?
In an edge function or your own server. It verifies who is calling, checks that they are an admin, and only then uses the secret key from its environment.
Sources
- 1.Understanding API keys — Supabase Docs
- 2.Environment variables in Edge Functions — Supabase Docs
- 3.Managing user data — Supabase Docs
- 4.Env variables and modes — Vite
- 5.CWE-798: Use of Hard-coded Credentials — MITRE
- 6.A07 Identification and Authentication Failures — OWASP Top 10