Advertisement
Intermediate Next.js, Authentication & Authorization in Next.js

How can you use middleware to protect multiple routes at once for authentication?

Short answer

Middleware runs before a request reaches a page, so you can check the user's session cookie there and redirect unauthenticated users away from any protected route defined in your matcher configuration, without repeating the same check inside every individual page.

Save Next.js mock interview
Advertisement
AModel answer
Middleware runs before a request reaches a page, so you can check the user's session cookie there and redirect unauthenticated users away from any protected route defined in your matcher configuration, without repeating the same check inside every individual page.
// middleware.ts
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('session');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}

export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'] };
Real-world example
An application protects every route under dashboard and settings using one middleware file, so new pages added under those folders are automatically protected without extra code.
Likely follow-ups
  • What is the performance impact of running authentication checks in middleware?
  • How do you allow public pages to bypass this middleware check?
Related topics