Based on the documentation, all the middlewares are added in a single file called middleware.ts.
And most of the time, the middlewares are all added to all paths
middleware1(middleware2(middleware3))
This is what I did
Middleware.ts
import { NextFetchEvent, NextResponse, type NextRequest } from "next/server";
import { updateSession } from "@/utils/supabase/middleware";
import { redirect } from "next/navigation";
import { withHeaders } from "./middleware/withHeader";
import { withLogging } from "./middleware/withLogging";
import { StackMiddleware } from "./middleware/stackMiddleware";
export async function middleware(
request: NextRequest,
resposne: NextResponse,
event: NextFetchEvent
) {
const response = NextResponse.next();
if (request.nextUrl.pathname.startsWith("/test")) {
// return NextResponse.rewrite(new URL("/about-2", request.url));
const middlewares = [withLogging, withHeaders];
StackMiddleware(middlewares);
}
const themePreference = response.cookies.get("theme");
if (!themePreference) {
response.cookies.set("theme", "dark");
}
await updateSession(request);
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
"/((?!_next/static|_next/image|favicon.ico|.*\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};
StackMiddleware.ts
import { NextMiddleware, NextResponse } from "next/server";
import { MiddlewareFactory } from "./types";
export function StackMiddleware(
functions: MiddlewareFactory[] = [],
index = 0
): NextMiddleware {
const current = functions[index];
//Base case
if (current) {
const next = StackMiddleware(functions, index + 1);
return current(next);
}
return () => NextResponse.next();
}
How do I conditionally add middleware to certain routes ? In this example how do I stack middleware for /test ?
Thank you