zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time π.
Made with by Zahid
views
zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time π.
Made with by Zahid
views

Share
Admin, User, or Guest? How to implement robust Role-Based Access Control (RBAC) using Clerk's custom claims.
Most apps need more than just "logged in" vs "logged out". You need "Admins" who can delete things and "Users" who can only view them. This is RBAC (Role-Based Access Control).
I needed an admin panel for my SaaS. I considered creating a separate database table for
1rolesWe can attach the user's role directly to their session token (JWT). This means we know if they are an Admin instantly, without hitting the database.
You can assign roles in the Clerk Dashboard or via API.
1// Determining access in a component
2import { auth } from "@clerk/nextjs";
3
4export default function AdminDashboard() {
5 const { sessionClaims } = auth();
6
7 // Custom metadata set in Clerk
8 const role = sessionClaims?.metadata?.role;
9
10 if (role !== "admin") {
11 return <p>Access Denied</p>;
12 }
13
14 return <h1>Admin Section</h1>;
15}Protect entire routes using Next.js Middleware.
1import { authMiddleware } from "@clerk/nextjs";
2import { NextResponse } from "next/server";
3
4export default authMiddleware({
5 afterAuth(auth, req) {
6 if (req.nextUrl.pathname.startsWith("/admin")) {
7 if (auth.sessionClaims?.metadata?.role !== "admin") {
8 return NextResponse.redirect(new URL("/", req.url));
9 }
10 }
11 }
12});
13
14export const config = {
15 matcher: ["/((?!.*\..*|_next).*)", "/", "/(api|trpc)(.*)"],
16};1useUser()1global.d.ts1CustomJwtSessionClaims1metadata.roleUsing session claims for RBAC is performant and secure. It keeps your authorization logic close to the authentication source.
Tech Stack: Clerk, Next.js, TypeScript