Multiple middleware functions #37978
-
I'm not sure if I'm missing something very obvious here... but I can't figure out how to run more than one middleware function. Is this supported? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Got this question as well with the 12.2 release - would be great if a single request can be routed through multiple layers of middleware for separation of concerns |
Beta Was this translation helpful? Give feedback.
-
Starting with |
Beta Was this translation helpful? Give feedback.
-
I propose to provide a compose function very similar to what koa-compose does export type EdgeMiddlewareNextFunction = () => Promise<NextResponse> | NextResponse;
export type EdgeMiddleware = (
req: NextRequest,
ev: NextFetchEvent,
next: EdgeMiddlewareNextFunction
) => Promise<NextResponse> | NextResponse;
export const compose = (...middleware: EdgeMiddleware[]) => {
return async (req: NextRequest, ev: NextFetchEvent): Promise<NextResponse> => {
let index = -1;
const dispatch = async (i: number): Promise<NextResponse> => {
if (i <= index) throw new Error('next() called multiple times');
index = i;
let fn = middleware[i];
if (i === middleware.length) {
fn = () => NextResponse.next();
}
if (!fn) return NextResponse.next();
return fn(req, ev, () => dispatch(i + 1));
};
return dispatch(0);
};
}; |
Beta Was this translation helpful? Give feedback.
Starting with
next@12.2.0
there's only one top level middleware. So to OP's question, not anymore, it was only possible on a per level basis, but now it is all from the root in one single function/file.