Next.js middleware.js tends to grow into one giant function handling everything at once: auth token refreshes, forced logouts, URL rewrites, vanity redirects, tracking cookies, access logging, and error handling. Testing or sharing any piece of it across projects gets painful fast.
A clean fix is middleware stacking: composing small, focused middleware factories sequentially with optional per-route configuration and early short-circuiting.
The middleware function contract
Each middleware takes (next, config) and returns an async request handler (req) => Response:
import { NextResponse } from "next/server";
export const exampleMiddleware = (next, config) => async (req) => {
if (config?.shouldSkip?.(req)) {
return next(req);
}
// Optional short-circuit before continuing down the stack
if (req.nextUrl.pathname === "/blocked") {
return new NextResponse(null, { status: 404 });
}
const response = await next(req);
if (config?.addHeader) {
response.headers.set("X-Custom", config.addHeader);
}
return response;
};
The stacker
reduceRight wraps each middleware around NextResponse.next(), supporting both plain factories and [factory, config] tuples:
import { NextResponse } from "next/server";
export const stackMiddlewares = (functions = []) => {
const baseHandler = () => NextResponse.next();
return functions.reduceRight((next, item) => {
const [factory, config] = Array.isArray(item) ? item : [item, null];
return config ? factory(next, config) : factory(next);
}, baseHandler);
};
Composing middleware.js
import { stackMiddlewares } from "@/lib/middleware/stack";
const composedHandler = stackMiddlewares([
headersMiddleware,
[
accessLoggingMiddleware,
{ shouldSkip: (req) => req.nextUrl.pathname.startsWith("/api") },
],
authMiddleware,
[exampleMiddleware, { addHeader: "enabled" }],
]);
export async function middleware(request) {
return composedHandler(request);
}
Each middleware now has one job, can be unit-tested on its own with a stub next, and can be packaged and shared cleanly across multiple Next.js apps.