Middleware is used to process requests between the client and the server before they reach the final destination.
Middleware runs between a userβs request and the final response.
Middleware is a powerful tool in Next.js used to run logic between a request and the response. It's ideal for:
middleware.js at the root level of your project.middleware.request object and can optionally return a Response.export function middleware(request) {
console.log('Middleware triggered');
return NextResponse.next(); // Allow request to continue
}Middleware can check if a user is logged in using cookies or headers. If not logged in, redirect to `/login` or `/` page.
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('authToken');
if (!token) {
return NextResponse.redirect(new URL('/', request.url));
}
return NextResponse.next();
}β
req.nextUrl.pathname != "/" condition is important to avoid **infinite redirects**.
import { NextResponse } from "next/server";
// Simulated user login status (replace with real logic later)
let login = true;
export function middleware(req) {
if (!login && req.nextUrl.pathname !== "/") {
return NextResponse.redirect(new URL('/', req.url));
}
return NextResponse.next();
}
// β οΈ Without this pathname check (req.nextUrl.pathname !== "/"), it will keep redirecting to '/' infinitely
You can apply middleware only to a specific route like a payment or dashboard page.
import { NextResponse } from "next/server";
export function middleware(req) {
return NextResponse.redirect(new URL('/', req.url));
}
export const config = {
matcher: ["/pay/:path*"],
// β
Apply middleware to pay route /:path* all subroutes
// β
Only run on /pay or subroutes like /pay/confirm
};