Skip to content

fix: Ensure cookies set in middleware are available on initial render #851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/breezy-adults-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@opennextjs/aws": patch
---

fix: Ensure cookies set in middleware are available on initial render when using `cookies().get()` from Next.js
7 changes: 7 additions & 0 deletions examples/app-router/app/cookies/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { cookies } from "next/headers";

export default async function Page() {
const foo = (await cookies()).get("foo")?.value;

return <div data-testid="foo">{foo}</div>;
}
5 changes: 5 additions & 0 deletions examples/app-router/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ export function middleware(request: NextRequest) {
const u = new URL("https://opennext.js.org/share.png");
return NextResponse.rewrite(u);
}
if (path === "/cookies") {
const res = NextResponse.next();
res.cookies.set("foo", "bar");
return res;
}
const requestHeaders = new Headers(request.headers);
// Setting the Request Headers, this should be available in RSC
requestHeaders.set("request-header", "request-header");
Expand Down
6 changes: 5 additions & 1 deletion packages/open-next/src/core/requestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@ export async function openNextHandler(
continue;
}
const key = rawKey.slice(MIDDLEWARE_HEADER_PREFIX_LEN);
overwrittenResponseHeaders[key] = value;
// We skip this header here since it is used by Next internally and we don't want it on the response headers.
// This header needs to be present in the request headers for processRequest, so cookies().get() from Next will work on initial render.
if (key !== "x-middleware-set-cookie") {
overwrittenResponseHeaders[key] = value;
}
headers[key] = value;
delete headers[rawKey];
}
Expand Down
1 change: 0 additions & 1 deletion packages/open-next/src/core/routing/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ export async function handleMiddleware(
// These are internal headers used by Next.js, we don't want to expose them to the client
const filteredHeaders = [
"x-middleware-override-headers",
"x-middleware-set-cookie",
"x-middleware-next",
"x-middleware-rewrite",
// We need to drop `content-encoding` because it will be decoded
Expand Down
46 changes: 39 additions & 7 deletions packages/tests-e2e/tests/appRouter/middleware.cookies.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,44 @@
import { expect, test } from "@playwright/test";

test("Cookies", async ({ page, context }) => {
await page.goto("/");
test.describe("Middleware Cookies", () => {
test("should be able to set cookies on response in middleware", async ({
page,
context,
}) => {
await page.goto("/");

const cookies = await context.cookies();
const from = cookies.find(({ name }) => name === "from");
expect(from?.value).toEqual("middleware");
const cookies = await context.cookies();
const from = cookies.find(({ name }) => name === "from");
expect(from?.value).toEqual("middleware");

const love = cookies.find(({ name }) => name === "with");
expect(love?.value).toEqual("love");
const love = cookies.find(({ name }) => name === "with");
expect(love?.value).toEqual("love");
});
test("should be able to get cookies set in the middleware with Next's cookies().get()", async ({
page,
}) => {
await page.goto("/cookies");

expect(await page.getByTestId("foo").textContent()).toBe("bar");
});
test("should not expose internal Next headers in response", async ({
page,
context,
}) => {
const responsePromise = page.waitForResponse((response) =>
response.url().includes("/cookies"),
);

await page.goto("/cookies");

const response = await responsePromise;
const headers = response.headers();

const cookies = await context.cookies();
const fooCookie = cookies.find(({ name }) => name === "foo");
expect(fooCookie?.value).toBe("bar");

expect(headers).not.toHaveProperty("x-middleware-set-cookie");
expect(headers).not.toHaveProperty("x-middleware-next");
});
});
Loading