Next.js
Beginner
1 min read
Middleware for Auth, Redirects, and Edge Logic
Example
// middleware.ts (at project root)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { verifyJwt } from '@/lib/jwt'; // must be edge-compatible
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Protected routes
const isProtected = pathname.startsWith('/dashboard') ||
pathname.startsWith('/settings');
if (isProtected) {
const token = request.cookies.get('session')?.value;
if (!token) {
// Redirect to login with a return URL
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(loginUrl);
}
try {
await verifyJwt(token);
} catch {
const loginUrl = new URL('/login', request.url);
return NextResponse.redirect(loginUrl);
}
}
// Forward the pathname to server components via a header
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-pathname', pathname);
return NextResponse.next({ request: { headers: requestHeaders } });
}
export const config = {
matcher: [
// Skip Next.js internals and all static files
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};