Skip to content

fix: Replace malformed UTF-8 and strip BOM in Response and Request text() and json() - #348

Merged
andreiltd merged 2 commits into
bytecodealliance:mainfrom
arayaryoma:body-text-utf8-replacement
Nov 2, 2026
Merged

andreiltd merged 2 commits into
bytecodealliance:mainfrom
arayaryoma:body-text-utf8-replacement

Conversation

@arayaryoma

Copy link
Copy Markdown
Contributor

Currently, Response and Request's text() and json() decode the body using JS_NewStringCopyUTF8N. However, this deviates from the spec because malformed UTF-8 throws a TypeError instead of being replaced with U+FFFD, and any leading UTF-8 BOM is preserved (causing things like json() to fail on BOM-prefixed bodies).

According to the Fetch spec, both methods should run UTF-8 decode on the body bytes (text(), or json() via parse JSON from bytes).

This PR introduces a utf8_decode() helper. It strips any leading UTF-8 BOM, then continues to use JS_NewStringCopyUTF8N if the remaining bytes are valid UTF-8.
Otherwise, it falls back to encoding_rs in replacement mode, matching the existing behavior of Blob.text() and TextDecoder.

…xt() and json()

Signed-off-by: araya <araya@araya.dev>
Signed-off-by: araya <araya@araya.dev>
Comment thread builtins/web/fetch/request-response.cpp Resolved

@andreiltd andreiltd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good, thank you!

@andreiltd
andreiltd merged commit 54b3329 into bytecodealliance:main Nov 2, 2026
7 checks passed
@arayaryoma
arayaryoma deleted the body-text-utf8-replacement branch November 2, 2026 13:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants