Next.js Discord

Discord Forum

Setting headers in NextResponse.redirect not working.

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Hello, I'm trying to remove searchParam and add it to headers instead, the removing param part works it removes the param, but setting the header dosen't when I try to get the header on a page it just returns as null, I also tried with NextResponse.next, there passing the header works but then I can't remove search params.

middleware.ts (part of it)
const callbackUrl = request.nextUrl.searchParams.get("callbackUrl");
const headers = new Headers(request.headers);

if (callbackUrl) {
  console.log(
    "setting callbackUrl header",
    typeof callbackUrl,
    callbackUrl
  );
  headers.set("callbackUrl", callbackUrl);
  request.nextUrl.searchParams.delete("callbackUrl");

  return NextResponse.redirect(request.nextUrl, {
    headers,
  });
}


Console log returns: setting callbackUrl header string http://localhost:3000/login null

page.tsx
import { headers } from "next/headers";

export default function ServerPage() {
  const headerList = headers();
  console.log(headerList.get("callbackUrl"));

  return <div>asf</div>;
}


Console log returns null.

3 Replies

Giant pandaOP
next@13.4.19
Tried both ways but it did't work it just either wont set the headers, or it wont remove the maram, can't get it to remove the param and set the header.