VibeCPR

← All fixes

Supabase · RLS · API keys · Next.js · Edge Functions

Supabase RLS not working on the server? Your API uses the service_role or secret key

Updated · Applies to: Supabase, Next.js, Lovable, Bolt, Cursor, Replit, v0, Vite

TL;DR fix: Row Level Security only applies to the anon and authenticated roles. A Supabase client created with a secret key (sb_secret_...) or the legacy service_role key runs as service_role, which has BYPASSRLS: every policy is skipped, so a route that does supabaseAdmin.from('notes').select() or trusts a userId from the request body hands out or edits anyone's rows. Adding service_role to a policy does nothing. Fix: for anything done on behalf of a user, create a per-request client with the publishable/anon key plus the user's JWT (@supabase/ssr in Next.js, withSupabase({ auth: 'user' }) or a forwarded Authorization header in Edge Functions) so RLS applies. Keep the admin client for cross-user jobs only, and when you must use it, verify the user with getClaims() and take the user id from the verified token, never the request. If the key is in your frontend bundle, remove it and rotate it.

Steps

  1. Find every place the secret or service_role key is used. Grep the repo for service_role, sb_secret_, SUPABASE_SECRET_KEY and supabaseAdmin (excluding node_modules). Every hit is code where RLS does not apply. Note which ones serve normal user requests: API routes, server actions, Edge Functions, loaders.
  2. Check the key never reaches the browser. Look for the key behind a public prefix (NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_) and for 'use client' files importing the admin client, then scan the built JS (or your live site's JS) for sb_secret_ strings and eyJ tokens whose role is service_role.
  3. Run the two-account test. Sign in as test user B, copy one of your app's API requests from DevTools, and replay it with test user A's id or row id. If B gets or changes A's data, that route is using the admin client without its own authorization check.
  4. Switch user-facing code to a per-request client. Create the Supabase client inside each request with the publishable (or anon) key and the caller's JWT: @supabase/ssr createServerClient with cookies in Next.js, withSupabase({ auth: 'user' }) or a forwarded Authorization header in Edge Functions. RLS then applies to every query.
  5. Where you really need the admin client, authorize first. Verify the caller with supabase.auth.getClaims() (not getSession), take the user id from the verified claims, filter and check ownership yourself, and never read the user id from the request body. Treat every Next.js server action and Edge Function as a public endpoint.
  6. Keep separate clients. Never build an SSR cookie client with the secret key, and never call signUp or other auth methods on the admin client. Keep one admin client in a server-only module and a per-request user client everywhere else.
  7. If the key was exposed, rotate it. If a secret or service_role key was ever in client code, a public repo or logs, fix the cause, create a new secret key, replace it everywhere, retire the old one, and review your data for changes.

The bug: RLS is on, the policies are right, and the API still leaks

You did everything the RLS guides say. RLS is enabled on every table, the policies say user_id = auth.uid(), and querying from the browser only shows your own rows. But one of these is true:

  • An API route like /api/notes?userId=... returns whatever user id you send it.
  • A “delete” button in one account can delete another account’s rows if you change the id.
  • An Edge Function returns every user’s records, not just the caller’s.
  • You asked your AI tool to fix a new row violates row-level security policy error and it “fixed” it by switching to the service role key. The error went away, and so did your security.

The cause is the key the server code uses. Supabase’s API keys docs map every key to a Postgres role:

KeyUser signed in?Postgres roleRLS
Publishable (sb_publishable_...) or legacy anonNoanonApplies
Publishable or legacy anon + the user’s JWTYesauthenticatedApplies
Secret (sb_secret_...) or legacy service_rolen/aservice_roleSkipped

“Policies never apply to a secret key, because service_role has the BYPASSRLS attribute.” So any code path that uses the admin client is protected only by the authorization checks you write yourself. Supabase’s Edge Function docs say it directly: a handler that queries a shared table through the admin client without filtering by the caller’s ID “returns every user’s rows”.

This is not the same bug as an insert that says success but writes nothing, where a webhook should use the secret key. This page is about the opposite: the secret key used for requests made on behalf of a signed-in user.

Step 1: the 2-minute check

1. Find every place the key is used (run in your project root):

# Everywhere RLS does not apply
rg -n --hidden -g '!node_modules' -g '!.git' -i 'service_role|sb_secret_|SUPABASE_SECRET_KEY|supabaseAdmin' .

# Secret keys behind a public prefix (these end up in the browser bundle)
rg -n --hidden -g '!node_modules' -g '!.git' '(NEXT_PUBLIC_|VITE_|EXPO_PUBLIC_|PUBLIC_)[A-Z0-9_]*(SERVICE_ROLE|SECRET)' .

# Client components that import the admin client
rg -l --hidden -g '!node_modules' "^['\"]use client['\"]" . | xargs -r rg -H -n -i 'service_role|supabaseAdmin|/admin'

# Handlers that trust a user id sent by the browser
rg -n -g '!node_modules' "\.eq\(['\"]user_id['\"],\s*(userId|body\.|req\.)" .

No rg? Use grep -rnE with the same patterns. For each hit in the first search, ask: does this code run for a normal signed-in user’s request (API route, server action, Edge Function, loader)? If yes, it needs one of the fixes below.

2. Check the key isn’t in the browser. Next.js inlines NEXT_PUBLIC_ variables into the JavaScript bundle at build time, and Vite exposes VITE_ variables to client code. Save this as scan-keys.mjs and run it on your build folder or your live URL (Node 18+):

// node scan-keys.mjs dist/   or   node scan-keys.mjs https://your-app.example
import fs from 'node:fs'; import path from 'node:path';
const target = process.argv[2]; const texts = [];
if (/^https?:/.test(target)) {
  const html = await (await fetch(target)).text(); texts.push(html);
  for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) texts.push(await (await fetch(new URL(m[1], target))).text());
} else {
  const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).forEach((e) => { const p = path.join(d, e.name);
    e.isDirectory() ? walk(p) : /\.(m?js|html|map)$/.test(e.name) && texts.push(fs.readFileSync(p, 'utf8')); });
  walk(target);
}
const found = new Map();
for (const t of texts) {
  for (const [k] of t.matchAll(/sb_secret_[A-Za-z0-9_-]{10,}/g)) found.set(k, 'DANGER: secret key (bypasses RLS)');
  for (const [k] of t.matchAll(/sb_publishable_[A-Za-z0-9_-]{10,}/g)) found.set(k, 'ok: publishable key');
  for (const [k] of t.matchAll(/eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g)) {
    try { const r = JSON.parse(Buffer.from(k.split('.')[1], 'base64url')).role;
      found.set(k, r === 'service_role' ? 'DANGER: legacy service_role key (bypasses RLS)' : r === 'anon' ? 'ok: legacy anon key' : `JWT role=${r}`); } catch {}
  }
}
for (const [k, v] of found) console.log(v.padEnd(48), k.slice(0, 24) + '...');
if (![...found.values()].some((v) => v.startsWith('DANGER'))) console.log('No secret or service_role key found in', texts.length, 'files.');

Any DANGER line means the key shipped to every visitor: do Fix C now. (It only follows <script src> tags on the page you give it; lazy-loaded chunks need a build-folder scan.)

3. Run the two-account test on your own app. Make two test accounts, A and B. Signed in as B, open DevTools > Network, right-click one of your app’s API or Edge Function requests, Copy as fetch, paste it into the console and change the user id or row id to one of A’s. If B gets A’s data, or B’s delete removes A’s row, that endpoint is using the admin client without its own check.

4. Optional: see which roles skip RLS (Supabase SQL Editor):

select rolname, rolbypassrls from pg_roles where rolbypassrls order by rolname;
-- Policies that name service_role do nothing; this lists them so you can stop relying on them
select schemaname, tablename, policyname, roles from pg_policies where 'service_role' = any(roles);
What you seeCauseFix
API route returns another user’s rows when you change userIdAdmin client + user id taken from the requestFix A, or Fix B
Edge Function returns every user’s rowsAdmin client with no caller filterFix A (auth: 'user')
Server action deletes/updates any row by idAdmin client; server actions are public POST endpointsFix A or Fix B
You added to service_role using (...) and nothing changedPolicies never run for service_roleRemove it; use Fix A or B
sb_secret_ or a service_role JWT in your JS bundleKey behind NEXT_PUBLIC_/VITE_, or admin client imported in client codeFix C
Logged-out requests get full data, signed-in ones are filteredSSR cookie client built with the secret keyThe SSR trap
Admin client suddenly hits RLS errorsA user session replaced the key in the Authorization headerThe SSR trap
permission denied for table even with the secret keyNo table grant for service_role (grants are checked before RLS)Permission denied on new tables

Fix A: a per-request client that carries the user’s JWT

For anything done on behalf of a signed-in user, let RLS do the work. Create the client inside the request, with the publishable (or anon) key, and give it the user’s token.

Next.js (App Router), from Supabase’s SSR client guide:

// lib/supabase/server.ts — the user-scoped client for route handlers, server actions, server components
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'

export async function createClient() {
  const cookieStore = await cookies()
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, // publishable/anon, NEVER the secret key
    {
      cookies: {
        getAll() { return cookieStore.getAll() },
        setAll(cookiesToSet) {
          try { cookiesToSet.forEach(({ name, value, options }) => cookieStore.set(name, value, options)) } catch {}
        },
      },
    }
  )
}
// app/api/notes/route.ts
import { createClient } from '@/lib/supabase/server'

export async function GET() {
  const supabase = await createClient()
  const { data: claims } = await supabase.auth.getClaims()
  if (!claims) return new Response('Unauthorized', { status: 401 })
  const { data, error } = await supabase.from('notes').select('*') // RLS returns only this user's rows
  if (error) return new Response(error.message, { status: 500 })
  return Response.json(data)
}

No userId parameter at all: RLS already knows who is asking.

Supabase Edge Functions, from Securing Edge Functions: use auth: 'user' and the RLS-scoped ctx.supabase; keep verify_jwt on (the default).

import { withSupabase } from 'npm:@supabase/server@1'

export default {
  fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
    const { id } = await req.json()
    // ctx.supabase applies the caller's RLS policies; ctx.supabaseAdmin would skip them
    const { error } = await ctx.supabase.from('notes').delete().eq('id', id)
    return error ? Response.json({ error: error.message }, { status: 400 }) : Response.json({ ok: true })
  }),
}

Older functions written with createClient can forward the caller’s token instead. Build it with the anon/publishable key, so a request with no token runs as anon, not as admin:

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

Deno.serve(async (req) => {
  const auth = req.headers.get('Authorization')
  if (!auth) return new Response('Unauthorized', { status: 401 })
  const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_ANON_KEY')!, {
    global: { headers: { Authorization: auth } },
  })
  const { data: { user } } = await supabase.auth.getUser() // verifies the token with Supabase Auth
  if (!user) return new Response('Unauthorized', { status: 401 })
  const { data } = await supabase.from('notes').select('*') // RLS applies
  return Response.json(data)
})

Don’t put an API key in Authorization: Supabase’s authorization headers page says verify_jwt also accepts publishable and secret keys, so “the check alone doesn’t authenticate a caller that sends only an API key”. Check for a real user, as above.

Any other Node server (Express, Hono, a Lovable or Bolt backend route): same idea. Read the bearer token from the request, create createClient(url, publishableKey, { global: { headers: { Authorization: 'Bearer ' + token } } }) per request, and let RLS filter. Never reuse one client across users.

Fix B: keep the admin client, but authorize first

Some work must cross users: Stripe webhooks, cron jobs, admin dashboards, “invite a teammate”. Keep the admin client for those, and give each one its own check, because nothing else will.

// lib/supabase/admin.ts
import 'server-only' // build fails if a client component imports this
import { createClient } from '@supabase/supabase-js'

export const supabaseAdmin = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SECRET_KEY!, {
  auth: { persistSession: false, autoRefreshToken: false },
})
// app/actions.ts
'use server'
import { createClient } from '@/lib/supabase/server'
import { supabaseAdmin } from '@/lib/supabase/admin'

export async function archiveNote(noteId: number) {
  const supabase = await createClient()
  const { data } = await supabase.auth.getClaims()          // verified, not getSession()
  const userId = data?.claims?.sub
  if (!userId) throw new Error('Unauthorized')
  const { data: rows, error } = await supabaseAdmin
    .from('notes').update({ archived: true })
    .eq('id', noteId).eq('user_id', userId)                    // ownership from the token, not the request
    .select('id')
  if (error) throw error
  if (!rows?.length) throw new Error('Not found')
}

Rules for every admin-client code path:

  1. Verify the caller with getClaims() (or getUser()). Supabase’s SSR docs: “Never trust supabase.auth.getSession() inside server code”; it reads the cookie without revalidating it.
  2. Take the user id from the verified claims. Never from the body, the query string or a hidden form field.
  3. Treat server actions and Edge Functions as public. Next.js’s data security guide: a Server Action “is reachable via a direct POST request, not just through your application’s UI”, even if nothing imports it.
  4. Webhooks authenticate with their own signature (for Stripe, see signature errors), then use the admin client.
  5. Use a separate secret key per backend component, as Supabase’s API keys docs recommend, so a leak only means rotating one.

Fix C: get the key out of the browser and rotate it

If the 2-minute check found the key in client code or a bundle:

  1. Rename the variable so it has no public prefix (SUPABASE_SECRET_KEY, not NEXT_PUBLIC_... or VITE_...), move every query that used it to a server route or Edge Function (with Fix A or B), and add import 'server-only' to the admin module.
  2. Rebuild, redeploy and rerun scan-keys.mjs on the live URL until it finds no DANGER lines.
  3. Rotate. Supabase’s API keys docs say a secret key sent from a browser gets a 401, “but an attacker can still use the key from other tools”. Follow Rotate a leaked API key: create a new secret key, replace it everywhere (Edge Functions using withSupabase({ auth: 'secret' }) only accept the key named default unless you name the new one), then retire the old key. For a legacy service_role key, also see Invalid API key after rotating Supabase keys so the switch doesn’t break your app.
  4. The key bypassed every policy while it was public, so check your tables for rows changed or deleted that you didn’t expect. For keys pushed to git, see find and fix leaked API keys.

Supabase decides the role from the Authorization header, not the apikey header (KB article). That causes two opposite bugs:

  • createServerClient(url, SECRET_KEY, { cookies }): when the visitor has a session cookie, the user’s token replaces the key, so the “admin” client is filtered by RLS (the KB’s case 1). When the visitor has no cookie, nothing replaces it, so the client runs with the secret key. In our header test, a signed-in request went out as authenticated and a logged-out one went out with the secret key. In other words, logged-out visitors get admin access. Always build cookie clients with the publishable key.
  • Calling signUp() or other auth methods on the admin client can store a user session in it, which then replaces the key. Supabase says to use auth.admin.createUser() or a separate client.

Paste this into Lovable, Bolt, Replit or Cursor

My Supabase RLS policies are being bypassed because server code uses the
service_role / secret key. Fix it without breaking webhooks or admin jobs:
1. List every file that uses SUPABASE_SERVICE_ROLE_KEY, SUPABASE_SECRET_KEY,
   sb_secret_ or an admin Supabase client. For each, say whether it serves a
   normal signed-in user's request or a cross-user job (webhook, cron, admin).
2. For user requests: replace the admin client with a per-request client
   created with the PUBLISHABLE/anon key and the user's JWT (@supabase/ssr
   createServerClient with cookies in Next.js; withSupabase({ auth: 'user' })
   and ctx.supabase in Edge Functions). Remove userId parameters that the
   browser sends; RLS already knows the user.
3. For cross-user jobs that keep the admin client: verify the caller with
   supabase.auth.getClaims() (never getSession), take the user id from the
   verified claims, check ownership in the query, and return 401/404
   otherwise. Webhooks must verify their provider signature instead.
4. Never create an SSR cookie client with the secret key, never call auth
   methods like signUp on the admin client, and add import 'server-only' to
   the admin module.
5. Make sure no secret key has a NEXT_PUBLIC_, VITE_ or EXPO_PUBLIC_ prefix
   or is imported by a 'use client' file. Tell me if it ever shipped, so I
   can rotate it.
6. Do not "fix" any RLS error by switching to the service role key. Show me
   every change before applying it.

What we verified

  • Tested locally (Nov 20, 2026, Postgres 17 via PGlite, research/pglite-test/t6.mjs): with Supabase-style roles (anon and authenticated without BYPASSRLS, service_role with it) and owner-only policies on a notes table, signed-out anon saw 0 rows, user Alice saw her 2, and service_role saw all 4. Setting Alice’s claims on a service_role session changed nothing: still 4 rows (the role decides, not the claims). A for select to service_role using (false) policy and FORCE ROW LEVEL SECURITY both left service_role reading all 4 rows. Revoking the table grant gave service_role 42501 permission denied for table notes. In simulated server routes, an admin-client route that trusted a userId from the request returned Alice’s notes to Mallory, an unfiltered one returned everyone’s, and admin-client update/insert let Mallory edit Alice’s note and write a row as Alice. The same requests through a per-user (authenticated + verified claims) route returned nothing of Alice’s, updated 0 rows, and the forged insert failed with 42501 new row violates row-level security policy. An admin route that took the user id from the verified claims returned only Mallory’s row. The pg_roles / pg_policies check queries listed service_role and the useless policy.
  • Tested locally (supabase-js 2.119.2, @supabase/ssr 0.12.7, fetch stubbed so nothing left the box, research/service-key-test/headers.mjs): createClient(url, secretKey) sent the secret key as both apikey and Authorization. With global.headers.Authorization set to a user JWT, or with the accessToken option, the user’s JWT was sent as Authorization, including on a client created with the secret key. createServerClient with a user session cookie sent the user’s JWT, both with the publishable key and with the secret key. With the secret key and no cookie, it sent the secret key. The role that results from each header is docs-based (Supabase’s RLS docs and KB); we did not call a real Supabase project.
  • Tested locally (vite 8.3.8, research/service-key-test/app): VITE_SUPABASE_SERVICE_ROLE_KEY and VITE_SUPABASE_SECRET_KEY (fake values) were inlined into the built JS, and an unprefixed variable came out as undefined. The scan-keys.mjs script on this page flagged the secret key and the service_role JWT, both in dist/ and from a local preview URL, labeled the anon JWT and a publishable key as ok, and reported nothing dangerous for a publishable-only file. The four rg commands found every planted usage in a fake Next.js + Edge Function repo (admin module, API route trusting userId, server action, "use client" import, NEXT_PUBLIC_ secret in .env.local) and skipped node_modules.
  • Docs-based (fetched Nov 20, 2026, all HTTP 200; list in research/service-role-bypasses-rls-2026-11-20.md): the key-to-role mapping, secret keys bypassing RLS and returning 401 in browsers, grants before RLS, a secret key obeying RLS when a user token is present, the KB’s three header-override cases and “adding service_role in RLS policies does nothing”, withSupabase modes and the verify_jwt behavior, the default SUPABASE_SERVICE_ROLE_KEY/SUPABASE_ANON_KEY Edge Function secrets, getClaims() vs getSession(), the rotation steps, Next.js server actions being reachable by direct POST and NEXT_PUBLIC_ inlining, Vite’s VITE_ exposure, and Postgres’s BYPASSRLS rule. We did not run the Next.js or Edge Function code on this page against a live project, and we did not test Next.js’s build output or server-only.

Related: Insert says success but no row (webhooks should use the secret key), rules that only live in the frontend, USING (true) policies, security definer functions callable by anyone, views that bypass RLS, Invalid API key after rotating Supabase keys, and Check your Supabase RLS in two minutes.

When to get help

Get help if a secret or service_role key was in your frontend or a public repo, if your API routes and Edge Functions all share one admin client and you aren't sure which ones are user-facing, if your AI tool keeps 'fixing' RLS errors by switching to the service_role key, or if moving to per-request clients breaks queries that only worked because RLS was being skipped.

FAQ

Why do my Supabase RLS policies not apply in my API route or Edge Function?

Because the client there was created with a secret key (sb_secret_...) or the legacy service_role key. Supabase's API keys docs say every key resolves to a Postgres role, and policies never apply to a secret key because service_role has the BYPASSRLS attribute. RLS only filters requests that run as anon or authenticated. Create the client per request with the publishable or anon key and the user's JWT, or check authorization yourself before using the admin client.

Can I write an RLS policy that restricts the service_role key?

No. Supabase's troubleshooting guide says adding service_role in RLS policies does nothing, because service role never runs the policies. Postgres documents that roles with BYPASSRLS always bypass row security. In our local Postgres test, a "to service_role using (false)" policy and FORCE ROW LEVEL SECURITY still let service_role read every row. Only table grants stop it: without a grant, service_role gets "permission denied".

If I pass the user's JWT to a client created with the secret key, does RLS apply?

Per Supabase's RLS docs, yes: a secret key bypasses RLS only when the request carries no user access token; with one, it runs under that user's policies. Supabase decides by the Authorization header, not the apikey header. In our test, supabase-js sent the user's JWT as Authorization when we set it in global.headers. The trap: if a request arrives with no session, the same client falls back to the secret key and full access. Use the publishable key for user-facing clients so a missing session means anon, not admin.

Is it OK to use the service_role key in a Supabase Edge Function?

For work that must cross users (webhooks, cron jobs, admin tools), yes, as long as the function does its own authorization. Supabase's Edge Function docs warn that a handler querying a shared table through the admin client without filtering by the caller's ID returns every user's rows. Also, the default verify_jwt check accepts publishable and secret keys, so on its own it doesn't prove a user called the function. For user calls, use withSupabase({ auth: 'user' }) and its RLS-scoped ctx.supabase.

How do I check if my Supabase service_role key is in my frontend?

Search your repo for NEXT_PUBLIC_, VITE_ or EXPO_PUBLIC_ variables containing SERVICE_ROLE or SECRET (Next.js and Vite inline those into the browser bundle at build time), then scan the built or live JavaScript for sb_secret_ strings and for eyJ tokens whose payload has "role":"service_role". The scanner on this page does both. Supabase blocks secret keys sent from browsers with a 401, but its docs note an attacker can still use the key from other tools, so a key found in a bundle must be rotated.

Should I use getSession() or getClaims() to check the user on the server?

getClaims(). Supabase's server-side docs say never to trust getSession() in server code because it reads the session from the cookie without revalidating it, and anyone can forge a cookie. getClaims() verifies the JWT signature. Use getUser() when you need a fresh user record from the Auth server.

My service_role key leaked. What do I do?

Supabase's rotation guide: fix the cause of the leak first, create a new secret key in Settings > API Keys, replace the old key everywhere it is used, then retire the compromised key (immediately if someone is actively using it). Because the key bypassed every policy, review your tables and logs for changes, and use a separate secret key per backend component so the next leak is smaller.

Sources

Related fixes