0Pricing
React Academy · Lesson

Middleware-Based Route Protection

Use Next.js middleware and auth callbacks to redirect unauthenticated users at the edge.

What Is Next.js Middleware?

Middleware runs at the edge before a request reaches a route. It can redirect, rewrite, or add headers — ideal for auth checks without loading server components.

Creating Middleware

Create middleware.ts at the project root. Export a middleware function and a config matcher.

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token')?.value;
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/profile/:path*'],
};

All lessons in this course

  1. Setting Up Auth.js in Next.js App Router
  2. Session Management & useSession Hook
  3. Credentials Provider & Custom Login
  4. Middleware-Based Route Protection
← Back to React Academy