- Home
- Services
- IVY
- Portfolio
- Blogs
- About Us
- Contact Us
- Sun-Tue (9:00 am-7.00 pm)
- infoaploxn@gmail.com
- +91 656 786 53
Next.js 14 introduces powerful enhancements to its middleware capabilities, allowing developers to handle server-side logic at the edge more efficiently. One especially useful application is role-based access control (RBAC). In this post, you’ll learn how to use scoped middleware to restrict access to specific routes based on user roles.
Middleware in Next.js runs before a request is completed. It can modify requests or responses and operates at the edge—making it fast and efficient. Common use cases include authentication, redirects, and logging.
Scoped middleware applies only to specific routes or folders. This improves performance by avoiding unnecessary checks and simplifies route-specific logic. You can define scopes through the file structure or using the matcher option in middleware.ts.
Here’s an example project structure:
/app /admin page.tsx /dashboard page.tsx /api /auth login.ts /middleware.ts
We’ll implement role-checking logic in the global middleware.ts file and use the matcher option to apply it selectively.
Ensure users are authenticated and their roles are stored in a secure token, such as a JWT saved in cookies.
import { NextResponse } from ’next/server’; import type { NextRequest } from ’next/server’; export function middleware(request: NextRequest) { const token = request.cookies.get(’token’)?.value; if (!token) { return NextResponse.redirect(new URL(’/login’, request.url)); } // Decode token (for demonstration only; use a secure library like `jsonwebtoken` in production) const payload = JSON.parse(Buffer.from(token.split(’.’)[1], ’base64’).toString()); const role = payload.role; const pathname = request.nextUrl.pathname; if (pathname.startsWith(’/admin’) && role !== ’admin’) { return NextResponse.redirect(new URL(’/unauthorized’, request.url)); } return NextResponse.next(); } export const config = { matcher: [’/admin/:path’, ’/dashboard/:path’], };
export default function UnauthorizedPage() { return <h1>403 - You don’t have access to this page.</h1>; }
Start your development server and try accessing /admin. If the user does not have the admin role, they will be redirected to /unauthorized. Otherwise, access will be granted.
Scoped middleware in Next.js 14 makes it simple and efficient to enforce role-based access control. By limiting checks to only relevant routes, you maintain both performance and security. Start with basic roles and expand your logic as your app grows.
Happy coding!
Imagine reducing your operational costs by up to $100,000 annually without compromising on the technology you rely on. Through our partnerships with leading cloud and technology providers like AWS (Amazon Web Services), Google Cloud Platform (GCP), Microsoft Azure, and Nvidia Inception, we can help you secure up to $25,000 in credits over two years (subject to approval).
These credits can cover essential server fees and offer additional perks, such as:
By leveraging these credits, you can significantly optimize your operational expenses. Whether you're a startup or a growing business, the savings from these partnerships ranging from $5,000 to $100,000 annually can make a huge difference in scaling your business efficiently.
The approval process requires company registration and meeting specific requirements, but we provide full support to guide you through every step. Start saving on your cloud infrastructure today and unlock the full potential of your business.