Traditional authentication checks inside layout files cause unnecessary page renders and redirect latency. By verifying user credentials at the Edge Middleware layer, you can block unauthenticated requests before they reach your page render pipeline.
This guide explains how to configure Edge Middleware with JWT validation.
How Edge Authentication Works
Next.js Edge Middleware executes on edge nodes (geographically close to users) before a request is resolved. This allows us to check for authentication cookies and redirect users instantly if they are unauthorized.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';
export async function middleware(request: NextRequest) {
const token = request.cookies.get('auth_token')?.value;
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
await jwtVerify(token, secret);
return NextResponse.next();
} catch (err) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
export const config = {
matcher: ['/dashboard/:path*', '/profile/:path*'],
};Best Practices
- Use Light Cryptography: Use lightweight libraries like
josesince Node's nativecryptomodule is not supported in the Edge runtime. - Keep Matchers Focused: Only match routes requiring authentication to avoid adding middleware latency to static assets.