How to Rotate a Leaked Key Without Taking Your App Down

You found a leaked key. The instinct is to go straight to the dashboard and revoke it. Do that first and your own app goes down along with the attacker’s access, because every deployed copy of your app is still holding the old key.
The order that works is: fix the cause of the leak, create the new key, get it deployed, watch the old key go quiet, then retire it. Supabase’s rotation guide is built on exactly that sequence, and its first line of prerequisites is the one people skip: fix the root cause before you rotate anything, or the new key leaks the same way. (How to find the leak in the first place is in the leaked-keys post; if it was a committed .env, see the .env mistake.)
The one exception
If someone is actively using the leaked key right now, retire it immediately. Supabase’s guide says so directly: components still using it will stop working until you replace it. Downtime beats a drained database. To tell: Supabase’s API logs show requests per key with user agents and IPs, so look for traffic that is not your own app, and Stripe’s request logs can be filtered by key. Everything below is for the common case, where the key leaked but you have a few minutes.
Step 1: create the new key
In Supabase, that is Settings, API Keys, then create a new secret key. Give it its own name, after the component that uses it: cron-billing, edge-send-email. Supabase recommends a separate secret key per backend component, so one leak means rotating one thing instead of everything, and named keys are what make “watch the old key go quiet” readable per component in the logs.
On Stripe the same job is a button: rotating a key in the dashboard revokes it and issues a replacement, and Stripe’s docs on keys give you a grace period of up to 7 days where old and new both work. That grace period is the whole trick. It is what makes zero downtime possible, and you can recreate it by hand anywhere: create the new key without deleting the old.
Step 2: replace it everywhere
This is the step where outages actually happen, because “everywhere” is longer than you think. Check:
- Your host’s environment variables. On Vercel, changing a variable applies only to new deployments; the running deployment keeps the values it was built with (Vercel docs). Update the variable, then redeploy, or nothing changes.
NEXT_PUBLIC_andVITE_variables are baked into the bundle at build time. If the leaked secret key sits in one of those, the variable itself is the leak: rebuilding with the new key in the same variable publishes it again. Move the key to a server-only variable, behind an API route or Edge Function, as part of fixing the root cause, then rebuild. Publishable keys only need the rebuild.- Edge Functions. Supabase’s guide has two gotchas worth knowing. A function that checks the key with
withSupabase({ auth: 'secret' })accepts only the secret key nameddefault, so it must be updated to accept your new key by name, likeauth: 'secret:rotated_secret_key'. And a Database Webhook orpg_netcall that sends the legacyservice_rolekey on theAuthorization: Bearerheader should send the new key on theapikeyheader instead. - Cron jobs, scripts, CI secrets, a teammate’s
.env. Search your repos and dashboards for the old key’s prefix. With more than one backend, roll the new key to one first and watch for errors before updating the rest; Stripe’s docs recommend the same.
If the leaked key is a legacy service_role key, one more step: also swap the legacy anon key in your browser and mobile clients for a publishable key, because retiring the compromised key deactivates both legacy keys. Installed mobile apps keep the old anon key until users update, so for apps in a store “replace it everywhere” can take weeks; the grace period is what carries them.
Step 3: watch, then retire
Supabase says to wait until every component uses the new key before retiring the old one. Stripe’s docs add the practical test: check the old key’s request logs and expire it only after its request volume has been at zero for a few hours or days. A missed client shows up as a straggler in those logs, and you want to find it before the key dies, not after.
Then delete the old secret key. Deleting is permanent, so confirm first. For a legacy key, deactivate the legacy keys. And if you find a forgotten client after you deactivate the legacy keys, move that client to a new key. Do not re-enable them, because Supabase warns that re-enabling restores the compromised key. One more detail from the same guide: a leaked legacy service_role key is a JWT signed by the project’s legacy JWT secret, so you must also move to JWT signing keys and revoke that secret, or anything still trusting it can accept the leaked key.
What if the leaked key is the publishable one?
If the key that leaked is your publishable (or legacy anon) key, do not rotate it in a panic. That key is public by design: it ships in every browser bundle and sits in every installed app, so rotating it changes nothing except breaking your clients until they update. What makes a public key safe is row level security on the tables behind it, and that is where to spend the effort.
A check to run during the rotation
Three runnable checks against your real provider and your real app, one per phase. Export the values first so no key lands in your shell history:
#!/bin/bash# Rotation checks against the real provider and your real app.# export PROVIDER_URL="https://YOUR_PROJECT.supabase.co/rest/v1/YOUR_TABLE?select=id&limit=1"# export NEW_KEY="sb_secret_..." # the replacement key# export OLD_KEY="sb_secret_..." # the leaked key# export APP_URL="https://your-app.example.com/api/health"# Run each phase at its moment: ./rotation.test.sh before | during | afterfail=0say() { if [ "$1" -eq 0 ]; then echo "ok $2 - $3"; else echo "not ok $2 - $3"; fail=1; fi }code() { curl -s -o /dev/null -w '%{http_code}' -H "apikey: $2" "$1"; }
case "${1:?usage: rotation.test.sh before|during|after}" in before) code_out=$(code "$PROVIDER_URL" "$NEW_KEY"); [ "$code_out" = 200 ]; say $? 1 "the new key works against the provider";; during) bad=0 for i in $(seq 1 12); do [ "$(curl -s -o /dev/null -w '%{http_code}' "$APP_URL")" = 200 ] || bad=1; sleep 5; done say $bad 2 "your app stayed up through the rollout";; after) code_out=$(code "$PROVIDER_URL" "$OLD_KEY"); [ "$code_out" = 401 ]; say $? 3 "the old key is dead";; *) echo "usage: rotation.test.sh before|during|after" >&2; exit 2;;esacexit $failRun before as soon as the new key exists: red means do not deploy, the key or its grants are wrong. Run during in a second terminal while you redeploy; it polls your app every five seconds for a minute, and red means a deploy went out still holding the old key. Run after once you retire the old key: red means the retire did not take. Supabase’s secret keys authenticate on the apikey header, as in the script; for Stripe use https://api.stripe.com/v1/balance as the URL and an Authorization: Bearer header instead. Tested against a stand-in provider locally: each phase passed when it should and failed when the accepted-key list said it should.
Why the order works, in a model
The model below is an illustration of the order, not a test of your system. It runs against a stand-in server it scripts itself, so it proves nothing about your app; the checks above are the ones that can fail because of something you did.
Save this stand-in provider (a server that accepts any key in its allowed list) as api.js:
// Stand-in for the provider (Supabase, Stripe...): accepts any key in ACCEPTED_KEYS.const http = require('http');let accepted = new Set();const server = http.createServer((req, res) => { if (req.url === '/_admin') { // test control: set accepted keys let b=''; req.on('data',d=>b+=d); req.on('end',()=>{ accepted=new Set(JSON.parse(b)); res.end('ok'); }); return; } const key = (req.headers.authorization||'').replace('Bearer ',''); res.statusCode = accepted.has(key) ? 200 : 401; res.end(accepted.has(key)?'data':'unauthorized');});server.listen(0, () => console.log(server.address().port));Then this illustration as rotation.test.js next to it, run with node rotation.test.js revoke-first and node rotation.test.js overlap (anything else exits with a usage error). It shows what users and attackers experience:
// Illustration: what users and attackers experience in each rotation order.const { spawn } = require('child_process');const http = require('http');let port, results = [], failed = 0;const call = (key, path='/') => new Promise(r => { const q = http.request({port, path, headers:{authorization:'Bearer '+key}}, res => r(res.statusCode)); q.end(); });const admin = keys => new Promise(r => { const q = http.request({port, path:'/_admin', method:'POST'}, res => { res.resume(); res.on('end', r); }); q.end(JSON.stringify(keys)); });const ok = (cond, name) => { console.log((cond?'ok ':'not ok ')+(results.length+1)+' - '+name); results.push(cond); if(!cond) failed=1; };
(async () => { const srv = spawn('node', ['api.js']); port = await new Promise(r => srv.stdout.once('data', d => r(+d.toString().trim()))); const OLD = 'sk_old_leaked', NEW = 'sk_new_rotated'; const strategy = process.argv[2]; if (strategy !== 'revoke-first' && strategy !== 'overlap') { console.error('usage: node rotation.test.js revoke-first|overlap'); process.exit(2); } let app = OLD; // the key the deployed app uses await admin([OLD]);
if (strategy === 'revoke-first') await admin([NEW]); // revoke old, create new else await admin([OLD, NEW]); // create new, old still valid
ok(await call(app) === 200, 'users are served while the new key is being rolled out'); app = NEW; // redeploy with the new key ok(await call(app) === 200, 'app works on the new key'); await admin([NEW]); // retire the old key ok(await call(OLD) === 401, 'the leaked key no longer works'); srv.kill(); process.exit(failed);})();It is a model, not Supabase itself, and it can only illustrate. Revoke-first:
not ok 1 - users are served while the new key is being rolled outok 2 - app works on the new keyok 3 - the leaked key no longer worksNew key first, overlap, then retire:
ok 1 - users are served while the new key is being rolled outok 2 - app works on the new keyok 3 - the leaked key no longer worksBoth orders end with the leaked key dead. Only one keeps your users served on the way there. The assertions describe outcomes, not mechanics, so they hold whether you rotate in a dashboard, a script or a CI job, and a later change that opens a gap in service fails test 1. They only cover what they check, so add a line for each service that holds a copy of the key.
A prompt to start with
A secret key for this project leaked. List every place the old key could be in use: environment variables per environment, CI secrets, serverless and edge function configs, webhooks, cron jobs, and any build-time inlined variables. Give me the order to create, deploy and retire so there is no downtime. Do not rotate or delete anything yet.
The 20-minute security check is the place to start if you are not sure what else is exposed, and row level security is what keeps the public keys safe by design.
The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.