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
- Setting Up Auth.js in Next.js App Router
- Session Management & useSession Hook
- Credentials Provider & Custom Login
- Middleware-Based Route Protection