Next.js Middleware & Headers
Middleware intercepts incoming browser requests globally, allowing you to run security validations, redirects, and header modifications before routes render.
1 middleware.js matching routes rules
Key features of Next.js middleware include:
- middleware.js: Exposes a global hook file at the root level of your project.
- Matcher configurations: Match specific path routes using regex to run middleware only where required (e.g. protecting dashboard views while skipping public home routes).
- Redirects / Rewrites: Dynamically redirect unauthorized requests to a login page, or rewrite URL paths in the background.
2 Writing a Middleware Interceptor
Let's check how to write a route protector middleware script:
TypeScript — middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('session_token')?.value;
// Protect dashboard routes
if (request.nextUrl.pathname.startsWith('/dashboard')) {
if (!token) {
// Redirect unauthorized users to login page
return NextResponse.redirect(new URL('/login', request.url));
}
}
return NextResponse.next();
}
// Config limits middleware to specific paths
export const config = {
matcher: ['/dashboard/:path*']
};
3 Code Challenge
Challenge: Write a middleware function that appends a custom header (e.g.
'x-custom-request-id') to all incoming API requests and verify it using browser DevTools.