Middleware runs before a request is completed. It can modify the request, enforce authentication, redirect users, or handle logging before the request reaches a page or API route. Middleware is executed on the Edge Runtime, making it lightweight and efficient.
Middleware should be placed in the root directory of a Next.js project.
middleware.ts
file should exist per project.// middleware.ts
import { NextResponse } from "next/server";
export function middleware(request: Request) {
console.log("Middleware executed");
return NextResponse.next(); // Allows the request to continue
}
Middleware is automatically executed on every request unless configured otherwise.
Authentication and Access Control
Middleware can check if a user is authenticated before allowing access to a protected route.
import { NextResponse } from "next/server";
export function middleware(request: Request) {
const token = request.cookies.get("authToken");
if (!token) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
This ensures that only authenticated users can access certain pages.
Redirects