How to implement role-based routing in Next.js 14 with App Router? #81357
-
SummaryI’m building an app using the App Router in Next.js 14 and I need to restrict access to certain routes based on user roles (admin, editor, viewer). What’s the best way to implement role-based route protection in the new App Router? Should I use middleware, server components, or both? Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Answered by
AjayKumbham
Jul 6, 2025
Replies: 1 comment
-
You can implement role-based routing in Next.js 14 (App Router) like this: 🔐 1. Middleware: import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const role = request.cookies.get('role')?.value;
if (!role || role !== 'admin') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
return NextResponse.next();
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
arverse-u
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can implement role-based routing in Next.js 14 (App Router) like this:
🔐 1. Middleware:
Use
middleware.ts
to read cookies or tokens and redirect unauthorized users.