Learn how to protect admin routes with Supabase by setting up projects, creating role-based policies, configuring middleware, and testing access control in your app.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Your Supabase Project
Step 2: Define Your User Roles
Step 3: Create a Custom Table Policy in Supabase for Admin Routes
create policy "Allow admin access only"
on your_table_name
for all
using (
auth.role() = 'admin'
);
Step 4: Connect Supabase with Your Application
npm install @supabase/supabase-js
SUPABASE_URL
and SUPABASE_ANON_KEY
with your project's credentials:
import { createClient } from '@supabase/supabase-js';
const supabaseUrl = 'https://SUPABASE\_URL';
const supabaseAnonKey = 'SUPABASE_ANON_KEY';
export const supabase = createClient(supabaseUrl, supabaseAnonKey);
Step 5: Implement Admin Route Protection in Your Application
In your application, define middleware or a guard to check if the user has the admin role before allowing access to admin routes.
Example for a Node.js Express middleware:
const adminRouteProtection = async (req, res, next) => {
const { user, error } = await supabase.auth.api.getUser(req.headers['access-token']);
if (error || !user || user.role !== 'admin') {
return res.status(403).json({ error: 'Access denied. Admins only.' });
}
next();
};
app.use('/admin', adminRouteProtection);
Step 6: Test Your Setup
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.