Next.js Discord

Discord Forum

Middleware header rewrite not working

Unanswered
martinm posted this in #help-forum
Open in Discord
I am writing a middleware handler to rewrite the requests to specific paths as a proxy to my backend. In this process I am adding to the headers an authentication header. Based on the docs and multiple examples, passing a header object to the NextResponse.rewrite function should rewrite the headers sent to the URL. This doesnt seem to work for me.

Heres how I define my middleware:
export const config = {
    matcher: "/api/analysis/:path*",
};

export function middleware(request: NextRequest) {
    const requestHeaders = new Headers(request.headers);
    requestHeaders.set("x-api-key", "my key");

    request.nextUrl.href = new URL(
      request.nextUrl.pathname.split("/").splice(3).join("/"),
      "https://my.api.baseurl.com/"
    ).toString();

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


I've verified on my backend server that the headers are not rewritten at all. Is my implementation wrong?

2 Replies

aparently this only occurs in the dev runtime, once deployed to vercel, everything functions as expected...