Middleware and Request Filtering
To run code before a request finishes loading (such as checking authentication, appending custom headers, or performing regional redirect routing), use Next.js Middleware.
1. Directory Placement and Syntax
To create middleware:
- Create a file named
middleware.ts(ormiddleware.js) in the root of yoursrcdirectory (at the same level as theappfolder). - Export a default middleware function handler.
// src/middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/request";
export function middleware(request: NextRequest) {
// Global intercept logic goes here
return NextResponse.next(); // Continue request pipeline execution
}2. Setting Route Matching Patterns (config)
By default, the middleware function runs on every route load. To target specific routes (and ignore static assets or page icons), export a config object containing a matcher path array:
// Configure path matching rules
export const config = {
matcher: [
// Apply middleware to all admin routes
"/admin/:path*",
// Apply middleware to profile dashboards
"/dashboard/:path*",
],
};3. Redirecting Unauthorized Requests
A common use case for middleware is protecting dashboard routes. If a user attempts to access /admin without a valid authentication token cookie, redirect them to the login page:
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 user is trying to access protected route without token
if (!token) {
// Construct absolute redirect URL
const loginUrl = new URL("/login", request.url);
// Redirect to login page
return NextResponse.redirect(loginUrl);
}
// Continue request execution if token is present
return NextResponse.next();
}4. Modifying Request Headers
You can also use middleware to append custom headers or cookies to incoming requests before they reach your page or API handler:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
// Clone request headers
const requestHeaders = new Headers(request.headers);
// Set custom regional header
requestHeaders.set("x-custom-region-code", "US-EAST");
// Pass modified headers to downstream route handlers
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}Published on Last updated: