imageimage
Schedule a Call

Get in Touch

  • Email Now
    contact@indusvalley.io
  • Headquarters
    Long Meadows Road Bedminster, New Jersey, 07921 United States
Social Link
  • Instagram
  • LinkedIn
  • X
  • Facebook
  • Youtube
  • Home
  • Services
    • AI Development
      • Generative AI
      • Machine Learning
      • Predictive Analytics
    • Mobile App Development
      • iOS App Development
      • Android App Development
      • Cross Platform App Development
    • Web Development
    • Digital Marketing
      • SEO
      • Social Media Marketing
      • Performance Marketing
      • Content Marketing
    • Design
      • UI/UX Design
      • Logo & Branding
      • Video Animation
    • IT Staff Augmentation
    • Cloud Services
  • IVY
  • Chat With IVY
  • Portfolio
  • Game Dev
  • Blogs
  • About Us
  • Contact Us
imageimage
image
  • Home
  • Services
    • AI Development
      • Generative AI
      • Machine Learning
      • Predictive Analytics
    • Mobile App Development
      • iOS App Development
      • Android App Development
      • Cross Platform App Development
    • Web Development
    • Digital Marketing
      • SEO
      • Social Media Marketing
      • Performance Marketing
      • Content Marketing
    • Design
      • UI/UX Design
      • Logo & Branding
      • Video Animation
    • IT Staff Augmentation
    • Cloud Services
  • IVY
  • Portfolio
  • Game Dev
  • Blogs
  • About Us
  • Contact Us
  • Sun-Tue (9:00 am-7.00 pm)
  • infoaploxn@gmail.com
  • +91 656 786 53
Get in Touch
Schedule a CallLet's Talk

Developer Insights & Best Practices / Scoped Middleware in Next.js 14: Implementing Role-Based Access in Routes

Scoped Middleware in Next.js 14: Implementing Role-Based Access in Routes
6/27/2025 | Shahzaib Mazhar

Scoped Middleware in Next.js 14: Implementing Role-Based Access in Routes

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!

Related Blogs

Explore More
Model Context Protocol (MCP): The Future of Agentic, Real-Time AI
  • February 16, 2026

A Deep Dive into the Model Context Protocol: The Universal Port for Agentic AI

Building a Real-Time Financial Agent with MCP and YFinance
  • February 16, 2026

A Practical Application: Building a Financial Data Server with MCP

Building Strength Through Unity in Teams
  • February 16, 2026

How Teams Become Stronger Without Competition

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
E-Commerce

Shopify

Hosting

Hostinger

Technology

Sentry

CMS

Hubspot

MARKETING

Semrush

HOSTING

Namecheap

Productivity

Evernote

Hosting

Bluehost

Success Stories

Explore More

Fynder.AI

Underdog Apparel

Toast DXB

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.

Connect Us
Contact Now
DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGNUI/UX DESIGNEMAIL MARKETINGBRANDING DESIGNUI/UX DESIGNEMAIL MARKETING
DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGN

Subscribe our newsletter

Company

  • About Us
  • Portfolio
  • Game Development
  • Blogs
  • IVY
  • Services
UI/UX DESIGN
EMAIL MARKETING
BRANDING DESIGN
UI/UX DESIGN
EMAIL MARKETING
  • Contact Us
  • Our Services

    • AI Development
    • Web Development
    • Mobile App Development
    • Digital Marketing
    • IT Staff Augmentation
    • Facebook
    • Youtube
    • X
    • Linkedin
    • Instagram
    footer-logo
    • Email Now
      contact@indusvalley.io

    Copyright © 2025 Indus Valley Technologies | All rights reserved ®

    Terms & ConditionsPrivacy Policy