OK
Olamilekan KilaniDeveloper
Back to Notes
TutorialMARCH 20265 min read

Understanding Protected Routes in Next.js with Middleware

OK
Olamilekan KilaniFrontend Engineer

Securing Next.js App Router with Middleware

Route protection in Next.js has evolved significantly with the introduction of edge middleware.

Why Middleware?

Before middleware, route protection happened on the client side (causing flash of unauthenticated content) or inside each getServerSideProps function individually. Middleware allows us to intercept incoming HTTP requests at the edge before any route handler runs.

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 && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

Key Practices

  • Store auth tokens in HttpOnly, SameSite=Lax cookies.
  • Match routes carefully using the matcher configuration.
  • Handle token expiration gracefully with redirects.