← All posts
·7 min read·GuardLayer

Supabase service role key not bypassing RLS? Here's why

SupabaseRLSSecretsNext.js

If a client built with the service role key still gets new row violates row-level security policy or returns empty rows, the request isn't reaching Postgres as service_role. Either a user's access token is riding along and overriding the key, or the key isn't the service role key at all. Build a separate admin client with createClient from @supabase/supabase-js, give it no cookies, no Authorization header and no sign-in calls, and leave your policies alone.

The service role does bypass RLS. Supabase's API keys page says policies never apply to it, because service_role has Postgres's BYPASSRLS attribute. The catch is the role a request runs as. Supabase's RLS guide puts it plainly: a secret key bypasses RLS "only when the request carries no user access token." When a user's JWT is in the Authorization header, the request runs as authenticated, and your policies apply exactly as they would in the browser.

The causes, in the order to check them

Supabase's troubleshooting article names the first three. The last two are the ones that look like RLS but aren't.

1. An SSR client built with the service role key. createServerClient from @supabase/ssr exists to read the auth cookie and send the signed-in user's session with every request. Hand it the service role key and the cookie still wins:

// Looks like an admin client. It isn't: the cookie session overrides the key.
const supabase = createServerClient(url, process.env.SUPABASE_SERVICE_ROLE_KEY!, {
  cookies: {
    getAll: () => cookieStore.getAll(),
    setAll: (list) => list.forEach(({ name, value, options }) => cookieStore.set(name, value, options)),
  },
});

A signed-in user's request runs as that user. With no one signed in (a webhook, a cron job), it may work, which is why this one shows up as "works locally, fails for real users."

2. A user's Authorization header passed into the client. The pattern for acting as the caller inside an Edge Function or a Route Handler forwards the incoming header:

const supabase = createClient(url, serviceRoleKey, {
  global: { headers: { Authorization: req.headers.get("Authorization")! } },
});

That header replaces the key's own token, so every query runs as the caller. Use one client per purpose: a user client with the forwarded header for reads that should respect RLS, and an admin client without it for the privileged write.

3. Auth calls on the admin client. signUp, signInWithPassword or setSession on the service-role client store a user session in it, and every later query from that client runs as that user. Keep auth flows on a separate client. For creating users from the server, use supabase.auth.admin.createUser, which doesn't sign anyone in.

4. The key isn't the service role key. An env var copied from the wrong field, or a fallback like process.env.SUPABASE_SERVICE_ROLE_KEY ?? process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY that silently picks the public key. New-style keys show their type in the prefix: sb_secret_ is the secret key, sb_publishable_ is not. A legacy key is a JWT whose payload says "role": "service_role" or "role": "anon". And a secret key won't work from a browser at all: Supabase checks the User-Agent and returns 401.

5. It's not RLS, it's a missing grant. BYPASSRLS skips policies, not privileges. Postgres checks table grants first, so if service_role has lost its privileges on a table you get 42501, permission denied for table orders, and no policy change will help. Check and restore them:

select has_table_privilege('service_role', 'public.orders', 'insert') as can_insert;

grant select, insert, update, delete on public.orders to service_role;

More on that error: permission denied for table.

The fix that makes it worse

When the webhook keeps failing, the tempting move is a policy "for the service role":

create policy "service role full access" on public.orders
  for all
  using (true)
  with check (true);

It makes the error go away, and it does nothing for the service role, which never evaluated your policies in the first place. Supabase's troubleshooting article makes the same point: adding service_role to a policy doesn't help. What it does do: with no to clause, the policy applies to public, so anyone with your publishable key can now read, change and delete every order. And it only "worked" because the webhook was never running as the service role: the catch-all policy let the user's token through.

guardlayer scan · supabase/migrations/20261122120000_orders_service_role.sqlLive engine output
Passed with warnings
92/100 · A
  • Warningsupabase/migrations/20261122120000_orders_service_role.sql:15

    Overly permissive RLS policy

    Scope the policy to the requesting user, e.g. USING (auth.uid() = user_id). Reserve (true) for genuinely public, read-only data.

The other two shortcuts are just as bad. Disabling RLS on the table opens it to the same people. Moving the key into a NEXT_PUBLIC_ variable so the browser can "bypass RLS" publishes it to everyone who loads your site (what to do if that happened). If you've already added a catch-all policy, drop it:

drop policy "service role full access" on public.orders;

How do I make the service role key bypass RLS?

Give it a client of its own, in a server-only module, with nothing that can carry a user session:

// lib/supabase/admin.ts
import "server-only";
import { createClient } from "@supabase/supabase-js";

export const supabaseAdmin = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!, // or SUPABASE_SECRET_KEY (sb_secret_...)
  { auth: { persistSession: false, autoRefreshToken: false } }
);

import "server-only" makes the build fail if a Client Component ever imports this file (why that matters). Use supabaseAdmin only for the writes that genuinely need to skip RLS, like a payment webhook marking an order paid, and check who's asking yourself before you call it, because the database no longer will. Keep using the cookie-based SSR client for everything a signed-in user reads and writes, so RLS keeps doing its job there.

If the failing request is a user's own action, the service role is the wrong tool: write a policy that allows it. new row violates row-level security policy covers the usual causes.

Quick self-check

Find policies that apply to everyone with a constant true:

select tablename, policyname, cmd, roles, qual, with_check
from pg_policies
where schemaname = 'public'
  and roles = '{public}'
  and (qual = 'true' or with_check = 'true');

Then grep for service-role clients that can pick up a session or end up in the browser:

grep -rn "createServerClient" --include=*.ts --include=*.tsx . | grep -i "service_role\|secret"
grep -rn "NEXT_PUBLIC_.*SERVICE_ROLE\|NEXT_PUBLIC_.*SECRET" --include=*.ts --include=*.tsx --include=.env* .

Does GuardLayer catch this?

Partly. The code scan flags the catch-all policy above: a using (true) policy with no to clause, with a message that names who can read and write the table. It flags the service role key in a NEXT_PUBLIC_ variable or a Client Component as critical, and a service role JWT pasted into the code. It doesn't flag an SSR client built with the service role key, because that's a client that runs as the wrong role, not one that leaks anything. Live check connects to the running project read-only and shows which tables anyone with your publishable key can read.

FAQ

Does the Supabase service role key bypass RLS? Yes, when the request carries no user access token. service_role has the BYPASSRLS attribute, so policies never apply to it. A user's JWT in the same request makes it run as authenticated instead.

Do I need an RLS policy for the service role? No. Policies don't apply to service_role, so a policy for it does nothing. A policy with using (true) and no to clause applies to everyone else.

Why does my service role client work locally but fail in production? Usually cause 1 or 2: locally you tested with no one signed in, so no user token was sent. In production the cookie or forwarded header carries a real user's token, and RLS applies.

Can I use the service role key in the browser? No. Anyone who loads the page can read it and use it to bypass RLS on every table. New sb_secret_ keys are refused from browsers with a 401.

What's the difference between this and "permission denied for table"? An RLS error (new row violates row-level security policy, or empty results) means policies ran. 42501 permission denied for table means the role has no grant on the table, and that applies to service_role too.

See which of your Supabase tables anyone can read, free

Connect your Supabase project read-only. GuardLayer checks RLS, policies, grants and functions as they are right now, and gives you the SQL to fix each problem. It never reads your rows and can't change anything.

Check my Supabase project

Prefer to check code instead? Scan your repo, no signup.

Keep reading