fix: NextJS does not support non-ascii in NextResponse headers (#25148)

* fix: NextJS does not support non-ascii in NextResponse headers

* Fixed type error
This commit is contained in:
Alex van Andel authored and GitHub committed 2025-11-14 01:27:17 +00:00
1 parent 38738c1a3a
commit 4282cd221c
2 files changed
+94 -2

No files matched your search

+43 -1
View File
@@ -85,6 +85,48 @@ export function checkPostMethod(req: NextRequest) {
return null;
}
// Vercel/Edge rejects non‑ASCII header values (see: https://github.com/vercel/next.js/issues/85631)
const isAscii = (s: string) => {
for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) > 0x7f) return false;
return true;
};
const stripNonAscii = (s: string) => {
let out = "";
for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) <= 0x7f) out += s[i];
return out;
};
const sanitizeRequestHeaders = (headers: Iterable<[string, string]>): Headers => {
const out = new Headers();
for (const [name, raw] of Array.from(headers)) {
if (!isAscii(name)) continue;
let value = raw;
if (!isAscii(value)) {
// Heuristic: if the string contains common mojibake markers (Ã: 0xC3, Â: 0xC2),
// prefer a simple strip (avoids introducing spurious ASCII letters like 'A').
let hasMojibakeMarker = false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code === 0xc3 || code === 0xc2) {
hasMojibakeMarker = true;
break;
}
}
if (hasMojibakeMarker) {
value = stripNonAscii(value);
} else {
try {
value = stripNonAscii(value.normalize("NFKD"));
} catch {
value = stripNonAscii(value);
}
}
}
if (value) out.set(name, value);
}
return out;
};
const isPagePathRequest = (url: URL) => {
const isNonPagePathPrefix = /^\/(?:_next|api)\//;
const isFile = /\..*$/;
@@ -145,7 +187,7 @@ const middleware = async (req: NextRequest): Promise<NextResponse<unknown>> => {
const res = NextResponse.next({
request: {
headers: requestHeaders,
headers: sanitizeRequestHeaders(requestHeaders),
},
});