Back to roadmaps authjs Course

Route Protection using Auth.js Middleware

To enforce global route protection policies without writing authentication checks inside every page component, use the Next.js Middleware.


1. Implementing the Middleware File

Create a middleware.ts file in the root of your application folder:

// middleware.ts
import { auth } from "./auth";
import { NextResponse } from "next/server";

export default auth((req) => {
  const isLoggedIn = !!req.auth;
  const isDashboardPage = req.nextUrl.pathname.startsWith("/dashboard");

  // If visitor is not logged in and tries to access /dashboard, redirect to /login
  if (isDashboardPage && !isLoggedIn) {
    const loginUrl = new URL("/login", req.nextUrl.origin);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
});

// Configure patterns to intercept
export const config = {
  matcher: ["/dashboard/:path*", "/admin/:path*"],
};

2. Advanced: Role-Based Routing Filters

You can read user metadata claims inside the middleware payload to block unauthorized roles:

export default auth((req) => {
  const isLoggedIn = !!req.auth;
  
  if (isLoggedIn) {
    const userRole = req.auth?.user?.role || "user";
    const isAdminRoute = req.nextUrl.pathname.startsWith("/admin");

    if (isAdminRoute && userRole !== "admin") {
      // Return 403 Forbidden redirect
      const errorUrl = new URL("/unauthorized", req.nextUrl.origin);
      return NextResponse.redirect(errorUrl);
    }
  }
});
Published on Last updated: