Next.js's CSP-nonce parser, up through v16.2.4, began with one import. import { ESCAPE_REGEX } from '../htmlescape'. The file packages/next/src/server/htmlescape.ts had one regex named ESCAPE_REGEX and one function consuming it, htmlEscapeJsonString. The regex covered five characters: &, <, >, U+2028, U+2029. Those are the characters that close a <script> tag's body or terminate a JavaScript statement inside JSON-in-script-text. The CSP nonce parser imported the regex as the validator that decided whether the nonce extracted from a request header was safe to interpolate into the nonce attribute of a <script> tag. JSON-in-script-text and HTML-attribute escape sets overlap on three characters. They diverge on " and '. CVE-2026-44581 lives in the divergence.
CVE-2026-44581: Next.js Validated a CSP Nonce With the JSON-Escape Regex
vendor
patterns
cve
proof of concept
The CSP request header is something Next.js's own middleware sets
Next.js's documented pattern for nonce-based Content Security Policy lives in a middleware.ts at the project root. The middleware generates a random nonce per request, sets it as part of a Content-Security-Policy response header, and also writes that same header onto the inbound request via NextResponse.next({ request: { headers } }). The renderer downstream reads the request header back, extracts the nonce token, and stamps it onto every <script> tag the framework generates so the browser allows them under the response's CSP.
The header is the framework's own out-of-band channel between two stages of its own pipeline. The middleware writes it. The renderer reads it. The renderer trusts it. The renderer reads it on every inbound network request, with no distinguishing mark between a header the framework's middleware set and a header an attacker sent. The advisory's workaround names the boundary the framework does not enforce: "strip inbound Content-Security-Policy request headers from untrusted traffic."
The status of Content-Security-Policy as a request header is internal only by convention. The convention is that real CDNs and proxies strip CSP from inbound requests, because CSP is a response-header construct and the HTTP spec has no inbound semantics for it. The Next.js renderer has its own. This is the shape that produced CVE-2025-29927, where x-middleware-subrequest was the header the framework set on itself to break recursion and the network was permitted to set it too. It is also the shape behind CVE-2026-44575 and CVE-2026-44573 earlier in the same May 2026 release. The previous two CVEs were URL surfaces. This one is a header again, and the question the renderer asks of the header is what nonce should I echo into my script tags.
The header is the entry. The gate that decides whether the echo is safe is what makes this CVE the CVE.
ESCAPE_REGEX is from htmlEscapeJsonString
getScriptNonceFromHeader lives in packages/next/src/server/app-render/get-script-nonce-from-header.tsx. The pre-patch source:
import { ESCAPE_REGEX } from '../htmlescape'
export function getScriptNonceFromHeader(
cspHeaderValue: string
): string | undefined {
// ... locate the script-src or default-src directive ...
const nonce = directive
.split(' ')
.slice(1)
.map((source) => source.trim())
.find(
(source) =>
source.startsWith("'nonce-") &&
source.length > 8 &&
source.endsWith("'")
)
?.slice(7, -1)
if (!nonce) return
if (ESCAPE_REGEX.test(nonce)) {
throw new Error(
'Nonce value from Content-Security-Policy contained HTML escape characters.'
)
}
return nonce
}Read the import. ESCAPE_REGEX was one of two exports from htmlescape.ts. The other export was the function the regex was authored for:
export const ESCAPE_REGEX = /[&><\u2028\u2029]/g
export function htmlEscapeJsonString(str: string): string {
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match])
}htmlEscapeJsonString does one job. It takes a JavaScript string that has been JSON-serialised and will be embedded inside a <script> tag's body, and it escapes the four characters that would let an attacker break out of that JSON-in-script-text context. &, <, and > would let </script> or its entity-decoded variants close the tag mid-payload. U+2028 and U+2029 are Unicode line separators that JSON tolerates as ordinary whitespace inside string literals but JavaScript treats as statement terminators, so an attacker who could embed one would terminate the JSON literal early as JS. Five characters. One destination. The function's name encoded what destination, JSON inside script-tag text. The regex encoded the threat model that destination required.
The CSP-nonce parser imported the regex and used it as the gate deciding whether the extracted nonce was safe. Safe for what destination? The destination, two files away, was this:
`<script nonce="${nonce}">`That site is not JSON-in-script-text. It is the value of a double-quoted HTML attribute. The character that terminates a double-quoted HTML-attribute value is ". The character that terminates the single-quoted variant is '. Neither is in ESCAPE_REGEX. The validator was filtering for the threat model of a different destination. The destination it was guarding had its own threat model. The two threat models overlapped on three characters. The two characters they did not overlap on were the only ones the destination's threat model actually needed.
JSON.stringify wrapped the nonce. The destination was an HTML attribute.
The wrong-sink mistake at the validator was the first half. The second half lived at the two call sites that emitted the <script nonce="..."> tag.
packages/next/src/server/app-render/use-flight-response.tsx assembled the inline boot script that carries the Flight payload. Pre-patch:
const startScriptTag = nonce
? `<script nonce=${JSON.stringify(nonce)}>`
: '<script>'JSON.stringify(nonce) returns a JSON-encoded string literal, complete with its own wrapping double quotes. JSON encoding escapes " as \". JSON encoding does not escape characters HTML-attribute parsing treats as terminators, because JSON encoding does not know it is being concatenated inside an HTML attribute. The output of JSON.stringify("foo") is the six-character string "foo". The wrap that survives in the rendered HTML for a malicious nonce looks like a JS string literal with JS-style backslash escapes, which the HTML attribute lexer reads as literal backslashes followed by attribute-terminating quotes.
The second emission site is packages/next/src/server/app-render/metadata-insertion/create-server-inserted-metadata.tsx, which emits the <script> tag that re-inserts head metadata. Pre-patch:
return `<script ${nonce ? `nonce="${nonce}"` : ''}>${REINSERT_ICON_SCRIPT}</script>`Zero encoding. The value that the parser returned is the value that lands inside the attribute. The validator decided.
Three sites in three files. The validator filtered for JSON-in-script-text escape characters. The first emitter wrapped its input with JSON-string encoding. The second emitter wrapped its input with nothing at all. None of the three spoke the grammar of the destination.
The attribute breakout
The exploit lays all three layers bare with one request header. The literal byte between " and onerror below is a TAB (0x09), not a space:
Content-Security-Policy: script-src 'nonce-" onerror="alert(1)'The legacy parser does directive.split(' ') with a single literal space. The TAB is not a space, so the entire 'nonce-"\tonerror="alert(1)' survives split(' ') as one element. The token starts with 'nonce-. The token ends with '. Its length exceeds 8. The .find() predicate matches. The ?.slice(7, -1) strips the wrapping 'nonce- and ', returning the body: "\tonerror="alert(1).
That body is tested against ESCAPE_REGEX = /[&><\u2028\u2029]/g. The body contains a ", a TAB, an =, an a, an l, an e, an r, an t, a (, a 1, a ). None of those are in &><\u2028\u2029. The regex does not match. The validator returns the value.
create-server-inserted-metadata.tsx interpolates the value:
<script nonce="" onerror="alert(1)">/* ... */</script>Read the bytes left to right as an HTML attribute parser does. <script opens the tag. Whitespace. nonce= then " opens a double-quoted attribute value. The next byte is ", which closes it; the attribute value is the empty string. The next byte is TAB, which the HTML spec treats as inter-attribute whitespace. Next is onerror=, then ", then alert(1), then ". The script element now carries both a nonce attribute (empty) and an onerror attribute (alert(1)), neither of which the developer composed.
When the script element's body fails to execute, or when the element is processed in a way that fires its error handler, onerror runs. Arbitrary JavaScript executes in the victim's origin under the response's CSP. The page's own script-src 'nonce-...' directive does not gate event-handler attributes; script-src-attr does, and the framework's CSP middleware does not set it.
The pre-patch behaviour was half-open
The validator did have a fail-closed branch. If ESCAPE_REGEX matched, the parser threw. A payload like script-src 'nonce-"><script></script>"' contains < and >, so on most runtimes the throw fired and the request handler returned a 500.
The throw was not fail-closed on every runtime. The patched test in test/production/app-dir/subresource-integrity/subresource-integrity.test.ts records the runtime split. Pre-patch:
it('throws when escape characters are included in nonce', async () => {
const res = await fetchWithPolicy(
`script-src 'nonce-"><script></script>"'`
)
if (runtime === 'node' && process.env.__NEXT_CACHE_COMPONENTS) {
expect(res.status).toBe(200)
} else {
expect(res.status).toBe(500)
}
})Read what that test asserted. On the cacheComponents runtime, the response status is 200. The throw fires inside the parser, but by the time it fires the streaming renderer has already flushed leading bytes of the response to the client. The throw aborts further streaming. The bytes already on the wire carry the broken-out attribute. The server logs an internal error. The client receives a 200 with the reflected payload.
The post-patch test rewrites the assertion:
it('ignores malformed nonce values without failing the request', async () => {
const policies = [
`script-src 'nonce-"><script></script>"'`,
`script-src 'nonce-" onerror="alert(1)'`,
]
for (const policy of policies) {
const $ = await renderWithPolicy(policy)
expect($('script[nonce]').length).toBe(0)
}
})The patched gate silently drops a malformed nonce, returns undefined, and the emission sites omit the nonce attribute entirely. The throw that the cacheComponents runtime turned into a partial reflection is gone. The behaviour is silent-drop, on every runtime.
The patch admits both wrongs
Commit b4c6705c70, authored by JJ Kasper on April 21 2026 with the commit message "Ignore malformed CSP nonce headers," changes four source files plus tests. The shape of the four changes is the shape of the bug.
get-script-nonce-from-header.tsx. The fragile startsWith / endsWith / length > 8 predicate and the ESCAPE_REGEX post-filter are replaced with one strict regex applied per source token. The import of ESCAPE_REGEX is deleted:
-import { ESCAPE_REGEX } from '../htmlescape'
+const CSP_NONCE_SOURCE_REGEX = /^'nonce-([A-Za-z0-9+/_-]+={0,2})'$/
export function getScriptNonceFromHeader(
cspHeaderValue: string
): string | undefined {
// ... locate the script-src or default-src directive ...
- const nonce = directive
- .split(' ')
- .slice(1)
- .map((source) => source.trim())
- .find(
- (source) =>
- source.startsWith("'nonce-") &&
- source.length > 8 &&
- source.endsWith("'")
- )
- ?.slice(7, -1)
-
- if (!nonce) return
-
- if (ESCAPE_REGEX.test(nonce)) {
- throw new Error(
- 'Nonce value from Content-Security-Policy contained HTML escape characters.'
- )
- }
-
- return nonce
+ for (const source of directive.split(/\s+/).slice(1)) {
+ const match = source.trim().match(CSP_NONCE_SOURCE_REGEX)
+ if (match) return match[1]
+ }
}The new regex /^'nonce-([A-Za-z0-9+/_-]+={0,2})'$/ is the CSP spec's definition of a nonce source value: the literal 'nonce-, then a base64 alphabet run, then optional = padding, then the closing '. Anything else is not a nonce source. The validator no longer asks the JSON-script-text regex about an HTML attribute. The validator no longer reaches into htmlescape.ts at all.
htmlescape.ts. A second function and a second regex are added next to the first:
export const ESCAPE_REGEX = /[&><\u2028\u2029]/g
+const ATTRIBUTE_ESCAPE_LOOKUP: { [match: string]: string } = {
+ '&': '&',
+ '"': '"',
+ "'": ''',
+ '<': '<',
+ '>': '>',
+}
+
+const ATTRIBUTE_ESCAPE_REGEX = /[&"'<>]/g
+
export function htmlEscapeJsonString(str: string): string {
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match])
}
+
+export function htmlEscapeAttributeString(str: string): string {
+ return str.replace(
+ ATTRIBUTE_ESCAPE_REGEX,
+ (match) => ATTRIBUTE_ESCAPE_LOOKUP[match]
+ )
+}The two functions sit side by side. The name of each says which destination it speaks for. htmlEscapeJsonString covers & > < U+2028 U+2029 because that is JSON-in-script-text. htmlEscapeAttributeString covers & " ' < > because that is HTML attribute. Five characters each. Three of those characters overlap. The two characters that do not overlap are the two characters that distinguish the destinations: " and ' for the attribute, U+2028 and U+2029 for the script-tag body.
use-flight-response.tsx. The wrap changes from JSON.stringify to htmlEscapeAttributeString:
-import { htmlEscapeJsonString } from '../htmlescape'
+import { htmlEscapeAttributeString, htmlEscapeJsonString } from '../htmlescape'
// ...
const startScriptTag = nonce
- ? `<script nonce=${JSON.stringify(nonce)}>`
+ ? `<script nonce="${htmlEscapeAttributeString(nonce)}">`
: '<script>'Two things changed in those three lines. The JSON.stringify wrap is gone, replaced by the HTML-attribute encoder. And the literal " quotes around the attribute value have moved into the template itself instead of being inherited from JSON.stringify's output. The wrap now matches the surrounding grammar.
create-server-inserted-metadata.tsx. The bare interpolation is wrapped:
-return `<script ${nonce ? `nonce="${nonce}"` : ''}>${REINSERT_ICON_SCRIPT}</script>`
+return `<script${
+ nonce ? ` nonce="${htmlEscapeAttributeString(nonce)}"` : ''
+}>${REINSERT_ICON_SCRIPT}</script>`Both emitters now speak HTML attribute. The validator no longer speaks JSON.
The Shell Was Not The Sink, applied to script tags
The defender-frame name for this is the-shell-was-not-the-sink, and the canonical exhibit is cacti_escapeshellarg, where Cacti's sanitiser was correct, complete behaviour for the POSIX shell and the value never reached a shell. Between Cacti's quote-wrap and rrdtool's read loop there is no shell. The wrap does not bind.
Next.js stages the same shape one floor up the stack. Between Next.js's getScriptNonceFromHeader and the <script> tag rendered to the browser there is no JSON. The validator's regex was written for htmlEscapeJsonString, and htmlEscapeJsonString's destination is the body of a <script> tag, where JSON is the language the browser will parse. The emitter wrapped its input with JSON.stringify, whose output is the language the browser will parse only when concatenated inside script-tag text. The destination in this codepath is the nonce attribute, which the browser parses as HTML attribute. The grammar between the regex and the destination is not JSON. The wrap does not bind.
The function's name encoded what the developer was thinking about. ESCAPE_REGEX lived in a file called htmlescape.ts, and reading the file name alone the import looks like it covers HTML in general. Reading the function the regex was authored for, htmlEscapeJsonString, the actual scope is one destination inside HTML: text inside a <script> tag, not attributes anywhere else. The CSP-nonce parser was the consumer that read the file name and not the function name. The patch separates the two concerns into two functions whose names cannot be confused that way again.
Third Next.js post in the May 2026 release
This is the third CVE we have covered from Next.js's May 8 2026 coordinated security release. The earlier two were CVE-2026-44575, where getMiddlewareMatchers compiled a regex whose only optional suffix was the Pages Router's .json data convention and not the App Router's .rsc, and CVE-2026-44573, where resolveRoutes applied the default locale at the first of its two locale-resolution sites and forgot to apply it at the second. Both prior posts named the same shape: the framework has two functions that classify some artifact, and one of them is on a vocabulary the other one updated past.
This CVE is that shape moved inside the renderer. The two functions are getScriptNonceFromHeader and the emitters that consume its output. The vocabulary they shared was the file htmlescape.ts. The vocabulary the file contained, until April 21 2026, was JSON-in-script-text. The vocabulary the destination required was HTML attribute. The renderer ran for three years on the assumption that the file's single function and single regex were a general HTML utility. The file's name suggested that. The file's contents did not.
htmlescape.ts has two functions now. Before April 21 2026, it had one, and Next.js used it for two.