From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Next.js 16 middleware: Restrict admin page

Next.js 16 middleware: Restrict admin page

Hello and welcome! In this session, I'm going to guide you through using Next.js middleware to protect a specific admin-only page in your application. The goal is to ensure that only users who are both logged in and have administrative privileges can access sensitive routes. We will build a piece of middleware that inspects incoming requests, checks the user's authentication status using NextAuth.js and then verifies their authorization by checking for an admin flag in their session token. This is a fundamental security practice for any application with different user roles. Let's scroll down just above our last return statement inside the proxy function. Okay, let's add the main structure for our admin route check. I am adding a new if statement that checks our isAdminRoute boolean. As you'll recall, this variable becomes true if the user is trying to access a path that starts with anything in our admin paths array, like debug.db. By placing this if block here, I am creating a…

Contents