Rolebased Access Control in Next.js (original) (raw)

Role-based Access Control in Next.js

Last Updated : 13 Sep, 2025

Role-Based Access Control (RBAC) is an authorization method where access to resources, pages, or features in an application is determined by the role assigned to a user.

define_roles

Example of RBAC in a Web App

Defining Roles in Next.js

Before enforcing permissions, we need a clear way to define roles. Keeping them in a centralized file avoids errors and makes the system scalable.

JavaScript `

// utils/roles.js export const roles = { ADMIN: "admin", EDITOR: "editor", USER: "user", };

`

Protecting Pages & Components

RBAC can be applied at two levels:

Page-Level Protection

// pages/admin.js import { roles } from "../utils/roles";

export default function AdminPage({ user }) { if (user.role !== roles.ADMIN) { return

Access Denied

; } return

Welcome Admin

; }

`

Component Protection

function DeleteButton({ user }) { if (user.role !== "admin" && user.role !== "editor") { return null; // hide button } return Delete Post; }

`

This improves both security (no unauthorized access) and UX (users don’t see what they can’t use).

Middleware-Based RBAC

Middleware runs before a request reaches a page, making it perfect for RBAC.

// middleware.js import { NextResponse } from "next/server";

export function middleware(req) { const role = req.cookies.get("role")?.value;

const adminRoutes = ["/admin", "/dashboard"];

if (adminRoutes.includes(req.nextUrl.pathname) && role !== "admin") { return NextResponse.redirect(new URL("/unauthorized", req.url)); }

return NextResponse.next(); }

`

Middleware blocks access before rendering. This prevents sensitive pages from even loading.

RBAC with Authentication

Authentication systems (JWT, NextAuth, Clerk) allow us to store roles securely and enforce RBAC across sessions.

RBAC with JWT(JSON Web Tokens)

import jwt from "jsonwebtoken";

export function signToken(user) { return jwt.sign({ id: user.id, role: user.role }, process.env.JWT_SECRET); }

export function verifyToken(token) { return jwt.verify(token, process.env.JWT_SECRET); }

`

Roles are embedded in tokens, making APIs and frontend checks easier.

RBAC with NextAuth

// [...nextauth].js callbacks: { async session({ session, token }) { session.user.role = token.role; return session; }, async jwt({ token, user }) { if (user) token.role = user.role; return token; }, },

`

RBAC with Clerk

Clerk provides authentication + role management out-of-the-box.

JavaScript `

import { useUser } from "@clerk/nextjs";

function AdminPanel() { const { user } = useUser();

if (user.publicMetadata.role !== "admin") { return

Access Denied

; } return

Welcome Admin

; }

`

**Advantages of Role-based Access Control

**Disadvantages of Role-based Access Control