Skip to content
← All guides

Security

Supabase service_role key leaked in a Lovable or Bolt app: what to do now

By Jan Lipmann, appienceChecked against sources on 10 min read

A Supabase secret key or legacy service_role key bypasses every Row Level Security policy, so whoever has it can read, change and delete everything your API exposes. Supabase's documented order is: fix the cause of the leak, create a new secret key, move everything to it, then retire the old one - and for a legacy service_role key, also revoke the legacy JWT secret. If the key is being abused right now, retire it first and fix the app afterwards.

SupabaseLovableBoltEdge Functions

What you are seeing

You usually find out from someone else. The signals:

  • An email from Supabase saying a secret key was found in a public GitHub repository. Supabase says it automatically revokes new-format secret keys detected in public GitHub repositories and notifies the project owner with instructions to rotate (Supabase security retro). If you got that email, the key is already dead - and anything in your app that used it has stopped working.
  • A GitHub secret scanning alert on your repository.
  • Lovable's Deep scan reports leaked secrets or credentials in your source code (Lovable security).
  • A security researcher or a user emails you saying they found your key - sometimes with a sample of your own data.
  • You remember pasting the service_role key into the AI chat or an .env file to make an admin feature, account deletion or a data import work.
Note: Two kinds of key can be the problem. New-format secret keys start with sb_secret_. Legacy keys are long JWTs that start with eyJ, and the public anon key and the secret service_role key look the same at a glance. Supabase blocks new secret keys in browsers (it checks the User-Agent header and answers 401), so a front end that works while calling Supabase with a secret key is almost certainly using the legacy service_role key (API keys). That browser block does not protect you: Supabase notes a leaked key still works from any other tool.

How to check it yourself

Check your own project only. Everything below is read-only.

1. Find out where the key is

Search the code Lovable or Bolt synced to GitHub, and the build output that actually ships to the browser. Run this from the project root after npm run build:

grep -rnoE "sb_secret_[A-Za-z0-9_-]+|service_role|eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+" \
  --exclude-dir=node_modules --exclude-dir=.git .
Covers the source, .env files and the build folder (dist, .output or similar). Matches inside supabase/functions/ are server code and expected, as long as the key is read from an environment variable there rather than written into the file.

Each eyJ... match is a JWT. Decode its middle part locally to see which role it carries - do not paste keys into websites:

node -e 'console.log(Buffer.from(process.argv[1].split(".")[1], "base64url").toString())' "PASTE.THE.JWT"
"role":"anon" is the public key and may ship. "role":"service_role" in front-end code, a front-end .env file or the build output means the key is leaked.

Then check the Git history. Deleting the key from the current code does not remove it from earlier commits:

git log --all --oneline -S "sb_secret_"
git log --all --oneline -S "service_role"
Lists every commit that added or removed one of these strings. If the repository is or ever was public, treat the key as leaked even if the latest version is clean.
  • Any variable whose name starts with VITE_ is written into the JavaScript the browser downloads. Vite's docs say these variables should not contain sensitive information such as API keys (Vite env variables). The name of the variable proves nothing - a service_role key stored as VITE_SUPABASE_KEY ships just the same.
  • In Bolt, environment variables can be read by code running in the visitor's browser; only values saved as Secrets stay on the server (Bolt secrets).

2. Find out what the key is used for

Before you rotate, list every place that uses the key: front-end files from step 1, Edge Functions, scheduled jobs, Database Webhooks, scripts on your laptop, and any outside service (an automation tool, a form backend) where you pasted it. Each of these breaks when the old key is retired, so you need the list to replace them all.

3. Look for signs of misuse

With the key, someone could read and change every table your API exposes, use all Storage APIs ("Service keys entirely bypass RLS policies", per Storage access control) and call the Auth admin API, which lists, creates, updates and deletes users (Admin API). Look in those places. In the SQL Editor:

-- Accounts created or changed recently
select id, email, created_at, updated_at, last_sign_in_at
from auth.users
order by greatest(created_at, updated_at) desc
limit 50;
Look for accounts you do not recognise and for changes you did not make.
-- Rows inserted, updated and deleted per table
select relname, n_tup_ins, n_tup_upd, n_tup_del, n_live_tup
from pg_stat_user_tables
where schemaname = 'public'
order by n_tup_del desc;
These are running totals, not a timeline (PostgreSQL statistics views), and they reset after a crash or a restore. Use them to spot a table with far more deletes than your app could explain.
-- Files uploaded or changed recently
select bucket_id, name, created_at, updated_at
from storage.objects
order by updated_at desc
limit 50;
Read only - Supabase says to treat the storage tables as read-only and change files through the API (Storage schema).

Then open Logs in the dashboard, choose the API Gateway source, and filter by method, path and status for the period the key was exposed. Look for traffic you do not recognise: requests from unfamiliar IP addresses or countries, DELETE or PATCH requests your app does not make, or bulk reads of whole tables. Logs only go back so far - 1 day on the Free plan, 7 on Pro, 28 on Team (Logs) - and Supabase notes an empty result does not prove there was no activity. Write down what you find before you rotate.

Why it happens

Supabase gives every project two kinds of key. The publishable key (or legacy anon key) is meant for the browser and only reaches what Row Level Security allows. The secret key (or legacy service_role key) maps to the service_role database role, which has the BYPASSRLS attribute. Supabase lists where it must never go: a web page, source code, a bundled mobile or desktop app, or a browser, "even on localhost" (API keys).

AI builders produce front-end apps, and some features genuinely need more power than the public key has: deleting a user's account, an admin screen that lists all users, a data import, anything that has to read across users. When RLS blocks the feature, the quickest way to make the error disappear is to use the key that ignores RLS - and if that happens in front-end code, the key ships to every visitor. Lovable's own docs put it plainly: "Secrets stored in frontend code are visible to users and should be considered compromised" (Lovable docs).

  • The key was put in a VITE_ variable or written straight into a file, so the build put it in the JavaScript bundle.
  • The .env file was committed to a public GitHub repository.
  • The key was pasted into a chat, a ticket or a no-code tool that is not under your control.

How to fix it

Warning: If someone is using the leaked key right now - data disappearing, unknown admin accounts, odd traffic in the logs - skip to step 3 and retire the key immediately, and for a legacy service_role key go straight on to step 4 and revoke the legacy JWT secret without waiting for tokens to expire. Supabase's rotation guide says to do exactly that, accepting that every component still using the key stops working until you replace it (Rotate a leaked key).

Otherwise, follow Supabase's order. Its guide says to fix the cause first, or the new key can leak the same way.

1. Move the privileged code to an Edge Function

Whatever needed the secret key in the browser has to run on the server instead. Edge Functions get the project's keys as built-in environment variables (SUPABASE_SECRET_KEYS, SUPABASE_PUBLISHABLE_KEYS; the legacy SUPABASE_SERVICE_ROLE_KEY holds the legacy key and stops working once you deactivate the legacy keys), so the key never appears in your code (Edge Function secrets). Supabase's withSupabase wrapper checks the caller and gives the function both a normal client and an admin client (Securing Edge Functions). For example, account deletion:

// supabase/functions/delete-account/index.ts
import { withSupabase } from "npm:@supabase/server@1";

export default {
  fetch: withSupabase({ auth: "user" }, async (_req, ctx) => {
    const userId = ctx.userClaims?.id;
    if (!userId) {
      return Response.json({ error: "Not signed in" }, { status: 401 });
    }

    // supabaseAdmin bypasses RLS - only ever act on the caller's own id here.
    const { error } = await ctx.supabaseAdmin.auth.admin.deleteUser(userId);
    if (error) {
      console.error("delete-account failed", { userId, message: error.message });
      return Response.json({ error: "Could not delete the account" }, { status: 500 });
    }
    return Response.json({ deleted: true });
  }),
};
auth: "user" means only a signed-in user's request gets through, and userClaims comes from their verified token, not from anything the browser sends in the body.

The front end then calls the function with the ordinary client and the publishable key - the user's session is sent along automatically:

const { data, error } = await supabase.functions.invoke("delete-account");
  • An admin client ignores RLS, so the function has to check permissions itself. Lovable's docs say the same about any server code that uses the service role (Lovable docs). For an admin screen, check the caller's role in the database inside the function, not a flag the browser sends.
  • Remove every trace of the secret key from front-end code and front-end .env files, and make sure npm run build plus the search from the check section finds nothing.
  • Keys for other services (Stripe, OpenAI, email) go in Edge Function secrets too: supabase secrets set NAME=value, or Edge Functions > Secrets in the dashboard.

2. Create a new secret key and switch everything to it

  1. In the dashboard open Settings > API Keys and create a new secret key (Rotate a leaked key).
  2. Update every component on your list from the check section: Edge Function secrets you set by hand, scheduled jobs, webhooks, outside services.
  3. If the leaked key was the legacy service_role key, search supabase/functions/ for SUPABASE_SERVICE_ROLE_KEY and SUPABASE_ANON_KEY. Supabase lists these built-in variables as the legacy keys (Edge Function secrets), so they stop working when you deactivate the legacy keys in step 3. Switch those functions to withSupabase or to a key from SUPABASE_SECRET_KEYS / SUPABASE_PUBLISHABLE_KEYS before you go further.
  4. Edge Functions using withSupabase({ auth: 'secret' }) accept only the key named default. If your new key has another name, change the setting to auth: 'secret:your_key_name', as Supabase's guide shows.
  5. If the leaked key was the legacy service_role key: also switch the browser and mobile app from the legacy anon key to a publishable key (Settings > API Keys; see migrating to the new API keys). Supabase warns that "Retiring the compromised key deactivates both legacy keys", so an app still on the anon key will stop working in the next step.
  6. Test the app end to end before you go further.
Note: A mobile app already in the App Store keeps the key it was built with. If it uses the legacy anon key, ship an update with the publishable key and give users time to install it before you deactivate the legacy keys - or accept that the old version stops working if the key is being abused.

3. Retire the old key

  • New-format secret key: delete it in Settings > API Keys. Supabase notes this cannot be undone.
  • Legacy service_role key: deactivate the legacy keys in Settings > API Keys. Do not turn them back on if you find a client you missed - Supabase says re-enabling restores the compromised key. Move that client to a new key instead.

4. For a legacy service_role key: revoke the legacy JWT secret

Legacy keys are JWTs signed with your project's legacy JWT secret, so anything that still trusts that secret can still accept the leaked key (Rotate a leaked key). The fix is to move to JWT signing keys and then revoke the old secret (JWT signing keys):

  1. Open Settings > JWT signing keys and click Migrate JWT secret. This imports the legacy secret and creates a new standby key.
  2. Make sure nothing in your app verifies tokens with the legacy JWT secret directly. The signing keys guide lists what to change, including Edge Functions that verify JWTs.
  3. Click Rotate keys. Supabase says this does not cause downtime and that no users are forcefully signed out - tokens that have not expired yet keep working.
  4. Revoke the legacy JWT secret. Supabase suggests waiting until existing tokens have expired (at least 1 hour and 15 minutes with a 1-hour access token expiry) and says you may revoke immediately during an active incident. From then on, nothing signed with the old secret is accepted.

5. Clean up the repository, then verify

  • Rotating the key is what makes the leak harmless. GitHub's own guide says to revoke or rotate the secret first and that this may be enough on its own (Removing sensitive data). Rewriting history does not reach existing clones and forks.
  • Add .env to .gitignore so the next key does not end up in a commit.
  • Rerun the search from the check section on a fresh build. It should find no sb_secret_ key and no JWT with "role":"service_role" outside supabase/functions/.
  • Click through every feature that used the key - especially the one that needed it in the first place.

If data was changed or deleted

Pro, Team and Enterprise projects have daily backups, and Point-in-Time Recovery is an add-on for those plans. For Free projects, Supabase recommends exporting data regularly yourself with the CLI (Backups). A restore makes the project inaccessible while it runs, so plan for downtime and export the current state first.

When to get help

  • The logs or the database show the key was actually used by someone else, and you need to work out what was read or changed.
  • The key was used by many components and you are not sure you found them all.
  • The feature that needed the key involves roles or other users' data, and you need the permission checks inside the Edge Function done right.
  • A shipped mobile app depends on the legacy keys and you need to plan the update.
  • The app holds personal data and the key was exposed on a live site. If you are subject to the GDPR, a personal data breach generally has to be reported to the supervisory authority within 72 hours of becoming aware of it, unless it is unlikely to result in a risk to people (GDPR, Article 33). Get legal advice on that part.

Sources

Primary documentation this guide was checked against. Platforms change - if something here no longer matches, the source wins.

Frequently asked questions

Is it enough to delete the key from my code?
No. Anyone who downloaded your site or cloned the repository before you removed it still has a working key. The key has to be retired in Settings > API Keys, and for a legacy service_role key the legacy JWT secret has to be revoked as well.
My anon or publishable key is visible in the browser. Is that the same problem?
No. That key is meant to be public and only reaches what Row Level Security allows. The secret key and the legacy service_role key are the ones that bypass RLS and must never reach the browser.
Supabase emailed me that it revoked my key. Am I safe now?
The key no longer works, so it cannot be used from now on. Anything that used it - Edge Functions, jobs, outside services - needs a new secret key. Check the logs and the database for what happened while it was exposed, and fix whatever put it in the repository, or the next key will leak the same way.
Will rotating keys sign out my users?
Moving to JWT signing keys and rotating them does not force anyone to sign out, according to Supabase: tokens that have not expired keep working. Revoking the legacy JWT secret right away, during an incident, means tokens still signed with it are no longer accepted. Deactivating the legacy keys does break any app version that still uses the legacy anon key, so switch the app to a publishable key first.
Do I need to rewrite my Git history?
Rotate the key first - that is what makes the leak harmless. GitHub says rotation may be sufficient on its own. Rewriting history with git-filter-repo removes the key from your copy, but not from forks or other people's clones.

Related guides

Fixed-price audit

Want someone to check the whole app, not just this?

A review of data security, production readiness and App Store readiness for apps built with AI tools. 900 USD, a ranked list of fixes within 5 business days.