DEV Community

SYED SHAAMEER Ali
SYED SHAAMEER Ali

Posted on

Supabase + Express: stop using the service role key for every request

Most Express + Supabase tutorials start the same way: create one Supabase client at the top of the file with the service role key, and use it everywhere. It works on the first try, which is why so many projects do it.
It also quietly turns off the main security feature of Supabase. This post explains why, and shows the pattern I use instead: a small client created per request, using the caller’s own token.
The common setup
// supabase.js
import { createClient } from '@supabase/supabase-js';

export const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_SERVICE_ROLE_KEY
);
// a route
router.get('/todos', requireAuth, async (req, res) => {
const { data } = await supabase
.from('todos')
.select('*')
.eq('user_id', req.user.id); // you must remember this line, every time
res.json(data);
});
The service role key bypasses Row-Level Security completely. Your policies exist, but they never run for these queries. The only thing standing between one user and everyone else’s data is that .eq('user_id', ...) line, written by hand in every route. Miss it once, in one route, and that route returns everyone’s rows.
The pattern: one client per request, using the user’s token
Instead of a shared all-powerful client, build a client for each request from the anon key plus the caller’s JWT. Postgres then sees the real user, and RLS applies to every query automatically.
// middleware/auth.js
import { createClient } from '@supabase/supabase-js';

export async function requireAuth(req, res, next) {
const header = req.headers.authorization || '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (!token) return res.status(401).json({ error: 'Missing token' });

// Anon key + the user's JWT, so RLS applies to every query on this client
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_ANON_KEY,
{
global: { headers: { Authorization: Bearer ${token} } },
auth: { persistSession: false, autoRefreshToken: false },
}
);

// Verify the token with Supabase Auth
const { data, error } = await supabase.auth.getUser(token);
if (error || !data?.user) {
return res.status(401).json({ error: 'Invalid or expired token' });
}

req.user = data.user;
req.supabase = supabase; // use this in your routes
next();
}
Now a route looks like this:
router.get('/todos', requireAuth, async (req, res) => {
const { data, error } = await req.supabase.from('todos').select('*');
if (error) return res.status(400).json({ error: error.message });
res.json(data);
});
No .eq('user_id', ...) needed for safety. If a route forgets to filter, the policy still limits the result to that user’s rows. A mistake in your code now returns fewer rows instead of leaking them. (You can still filter for clarity or performance. It just isn’t what protects you anymore.)
Why create a client per request?
A client built from the caller’s token carries that one user’s identity. If you share a single client and swap sessions on it (for example by calling setSession), concurrent requests can step on each other. Building a fresh client per request, with persistSession: false, keeps each request isolated. It’s cheap: creating a client is just object setup, not a network call.
Where the service role key still belongs
Some things really do need to bypass RLS: admin tasks, background jobs, creating users from your server, test setup. Keep that in a separate, clearly named file and don’t hand it to ordinary routes:
// admin-client.js, used only by admin-only code
import { createClient } from '@supabase/supabase-js';

export const supabaseAdmin = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_SERVICE_ROLE_KEY,
{ auth: { persistSession: false } }
);
Rules of thumb:
• The service role key lives in server environment variables only. Never in a browser, a mobile app, or a repo.
• If a route uses supabaseAdmin, treat it like a loaded tool: write the ownership checks by hand and review them.
• Ordinary user-facing routes use req.supabase.
RLS and grants still have to be set up
This pattern only protects you if the database side exists: RLS enabled on the table, policies that check auth.uid(), and the right grants for the authenticated role. Supabase no longer auto-grants API access to new tables, so a table with a policy but no grant will return 42501 permission denied. If that bites you, [LINK TO ARTICLE 1] covers the grants.
A 2-minute check
Call your route with two different users’ tokens. Each should see only their own rows. If either one sees everything, the route is using the wrong client or the table has no working policy. [LINK TO ARTICLE 2] has a script that automates this.
Summary
• One global client with the service role key means RLS never runs, and every route has to filter by hand.
• A per-request client with the anon key and the user’s JWT makes Postgres enforce your policies for every query.
• Keep the service role key in a separate admin client for the few places that truly need it.
Want it already set up?
My Express + Supabase starter uses this per-request pattern: auth routes, a JWT middleware that attaches req.supabase, rate limiting, and a signup trigger that creates profiles. Disclosure: I’m the author, and it’s a paid starter, not a security audit. It covers the profiles table, so any tables you add need their own policies and grants.

https://shaameer.gumroad.com/l/SupabaseExpressjsProductionBackend/Launch10
The code above is free to copy either way. If you spot something I got wrong, tell me in the comments and I’ll fix it.

Top comments (0)