How do you implement role-based access control (RBAC) in Next.js?
Store each user's role (and optionally fine-grained permissions) on the server, include it in the session, and enforce it in a central authorization layer called by every data read, Server Function and Route Handler. Use Proxy and UI hiding only for user experience, never as the enforcement point.
Model
- Roles:
viewer,editor,admin, often scoped to an organization (orgId + role). - Permissions: map roles to actions such as
post:read,post:update,billing:manage. Check permissions, not role names, so roles can change without touching every check. - Ownership rules: "editors can update their own posts" requires the resource, so checks happen where the data is loaded.
Enforcement points
- Data Access Layer:
can(user, "post:update", post)before every query or mutation. - Server Functions and Route Handlers: authorize at the start; return 403 or throw.
- Pages: call
forbidden()(experimentalauthInterrupts) to renderforbidden.tsxwith a 403, ornotFound()to hide the resource. - Proxy: optional redirect for whole sections such as
/adminusing the role claim in a signed token. - UI: hide buttons the user cannot use; purely cosmetic.
Freshness
Role claims in a JWT can be stale after a role change. For sensitive actions, re-check the role from the database (cached per request), or keep tokens short-lived.
Libraries
CASL, Permit.io, Oso or your auth provider's organizations feature (Clerk, WorkOS, Better Auth) can model roles and permissions.
Testing
Unit test the permission function exhaustively; it is pure and easy to test. Add E2E tests that try forbidden actions directly against Server Functions and APIs.
Code example
1// lib/permissions.ts2type Role = "viewer" | "editor" | "admin";3type Action = "post:read" | "post:create" | "post:update" | "post:delete";45const GRANTS: Record<Role, Action[]> = {6 viewer: ["post:read"],7 editor: ["post:read", "post:create", "post:update"],8 admin: ["post:read", "post:create", "post:update", "post:delete"],9};1011export function can(user: { id: string; role: Role }, action: Action, post?: { authorId: string }) {12 if (!GRANTS[user.role].includes(action)) return false;13 // Editors may only update their own posts14 if (action === "post:update" && user.role === "editor") return post?.authorId === user.id;15 return true;16}1718// app/posts/actions.ts19// "use server";20// import { forbidden } from "next/navigation"; // requires experimental.authInterrupts21// export async function deletePost(id: string) {22// const user = await verifySession();23// const post = await db.post.findUniqueOrThrow({ where: { id } });24// if (!can(user, "post:delete", post)) forbidden();25// await db.post.delete({ where: { id } });26// updateTag("posts");27// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.