Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
17 changes: 17 additions & 0 deletions web/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,23 @@ function routeRequest(incomingRequest: NextRequest) {
if (response) return response;

response = intlMiddleware(request);
if (
request.headers.get("next-router-prefetch") === "1" ||
Comment thread
teamleaderleo marked this conversation as resolved.
Resolved
request.headers.get("purpose") === "prefetch"
) {
// A delayed prefetch for the previous locale must not overwrite a newer
// explicit choice. Keep next-intl's routing, but do not publish its cookie.
// Rebuild the response so later cookie writes cannot resurrect that cookie
// from NextResponse's internal cookie map.
const headers = new Headers(response.headers);
headers.delete("set-cookie");
headers.delete("x-middleware-set-cookie");
response = new NextResponse(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
if (featureWorkflowDocRequest) {
setFeatureWorkflowDocLinkHeader(
response,
Expand Down
36 changes: 36 additions & 0 deletions web/tests/locale-prefetch-cookie.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, expect, test } from "bun:test";
import { NextRequest } from "next/server";
import middleware from "../proxy";

describe("locale preference during prefetch", () => {
const prefetchHeaders: Record<string, string>[] = [
{ "next-router-prefetch": "1", rsc: "1" },
{ purpose: "prefetch" },
];
for (const headers of prefetchHeaders) {
test(`does not replace an explicit locale preference for ${JSON.stringify(headers)}`, () => {
const response = middleware(new NextRequest("https://cmux.com/ko/blog/cmux-vault", {
headers: { host: "cmux.com", cookie: "NEXT_LOCALE=en", ...headers },
}));

expect(response.status).toBe(200);
expect(response.headers.get("set-cookie")).toBeNull();
expect(response.headers.get("x-middleware-set-cookie")).toBeNull();
expect(response.cookies.get("NEXT_LOCALE")).toBeUndefined();
expect(response.headers.get("x-middleware-request-x-next-intl-locale")).toBe("ko");
expect(response.headers.get("x-middleware-next")).toBe("1");

response.cookies.set("unrelated", "kept");
expect(response.headers.get("set-cookie")).not.toContain("NEXT_LOCALE");
});
}

test("still persists the destination locale for a real navigation", () => {
const response = middleware(new NextRequest("https://cmux.com/ko/blog/cmux-vault", {
headers: { host: "cmux.com", cookie: "NEXT_LOCALE=en", rsc: "1" },
}));

expect(response.cookies.get("NEXT_LOCALE")?.value).toBe("ko");
expect(response.headers.get("set-cookie")).toContain("NEXT_LOCALE=ko");
});
});
Loading