Next.js Discord

Discord Forum

Middleware not called on async data fetching for App router (replacing getStaticParams)

Answered
McKay's Bunting posted this in #help-forum
Open in Discord
McKay's BuntingOP
I have the following middleware that has been confirmed to work for my application.
export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);

  const updatedUrl = request.nextUrl.clone();
  updatedUrl.host = "BACKEND_HOST";
  updatedUrl.protocol = "NEW_PROTOCOL";

  return NextResponse.rewrite(updatedUrl.toString(), {
    request: {
      headers: requestHeaders,
    },
  });
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: "/api/:path*",
};


But when I use it in conjunction with a Page using the NextJS App Router to fetch data asynchronously (like getStaticParams), the middleware does not get called:

export default async function ExercisePage({
  params,
}: {
  params: { id: string };
}) {
  const data = fetch("/api/data")
  ...
}



What should I do in this case? Why is the middleware not called? Is this a bug? I want my traffic to be all proxied through my NextJS app on localhost:3000 to hit my local backend at localhost:8000. The middlework has been working until I tried to add asynchronous data fetching. Running NextJS: 13.5.6
Answered by McKay's Bunting
View full answer

2 Replies

McKay's BuntingOP
I have noticed that this is also a problem with generateStaticParams().
McKay's BuntingOP
Answer