Supabase Admin
Published: Thursday, 23 Sep 2021
Updated: Wednesday, 18 Oct 2023
This is the Supabase equivalent of the Firebase Admin SDK.
Why do I need Supabase Admin?
You need this capability for certain actions in your server side code.
Your server will (generally) not have a valid user session, which means it cannot interact with your database tables with row level security (RLS) implemented.
E.g. you have an endpoint that receives Stripe webhooks and want to persist some details from the webhook to a RLS enabled table.
⚠️ Warning ⚠️
The entire point of the Supabase Admin is to bypass your security. Therefore, ensure the admin is never exposed client-side, and only use the admin if absolutely necessary.
Again, never use the admin in client-side code. If you set it up as per this page, SvelteKit itself will prevent you from accidentally importing Supabase Admin into your client-side code!
How do I do it?
It’s really simple.
Grab the service_role_key
secret
from your Supabase > Settings > API and add it as an environment variable.
// .env.local
SUPABASE_SERVICE_ROLE_KEY = blablabla;
Then create a client like normal but use the service_role_key
instead of the anon
key.
// src/lib/utils/supabaseAdmin.js
import { createClient } from '@supabase/supabase-js';
import {
PUBLIC_SUPABASE_URL,
SUPABASE_SERVICE_ROLE_KEY
} from '$env/static/private';
export const supabaseAdmin = createClient(
PUBLIC_SUPABASE_URL,
SUPABASE_SERVICE_ROLE_KEY
);
Note that this imports via $env/static/private
. Check out my post on Environment Variables in SvelteKit
Now you can use supabaseAdmin
in your project’s server-side code to bypass all row level security.
You use supabaseAdmin
the same way you use the normal supabase client.
E.g.
import { supabaseAdmin } from '$lib/utils/supabaseAdmin';
await supabaseAdmin.from('table_name').select('*');