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.

Understanding Middleware in Next.js

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.

What Is Scoped Middleware?

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.

Folder Structure for Role-Based Access

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.

Step-by-Step: Implementing Role-Based Access

1. Set Up Authentication and Roles

Ensure users are authenticated and their roles are stored in a secure token, such as a JWT saved in cookies.

2. Create Middleware Logic

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’],

};

3. Create an Unauthorized Page

export default function UnauthorizedPage() {

  return <h1>403 - You don’t have access to this page.</h1>;

}

Testing the Middleware

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.

Conclusion

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!

Our Trusted
Partner.

Unlock Valuable Cloud and Technology Credits

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:

  • Google Workspace accounts
  • Microsoft accounts
  • Stripe processing fee waivers up to $25,000
  • And many other valuable benefits

Why Choose Our Partnership?

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.

exclusive-partnersexclusive-partners

Let's TALK

Let's TALK and bring your ideas to life! Our experienced team is dedicated to helping your business grow and thrive. Reach out today for personalized support or request your free quote to kickstart your journey to success.

DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGNUI/UX DESIGNEMAIL MARKETINGBRANDING DESIGNUI/UX DESIGNEMAIL MARKETING
DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGNUI/UX DESIGNEMAIL MARKETINGBRANDING DESIGNUI/UX DESIGNEMAIL MARKETING