Skip to content

Reject json() on an empty body with the JSON.parse SyntaxError - #33658

Closed
robobun wants to merge 1 commit into
mainfrom
farm/9e40529b/json-body-error-message
Closed

robobun wants to merge 1 commit into
mainfrom
farm/9e40529b/json-body-error-message

Conversation

@robobun

@robobun robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • fetch() of a response with an empty body: response.json() resolves null. Node rejects with the JSON.parse SyntaxError. Fixes Response.json behavior is different between bun and node #24955. A Request body in Bun.serve() resolves null the same way.
  • An empty Blob, Response("") or Bun.file() body rejects with a hardcoded Unexpected end of JSON input. A streamed empty body rejects with JSON Parse error: Unexpected EOF, the JSON.parse("") message.
  • The cause is three empty-body checks in src/runtime/webcore/Blob.rs that run before the JSON helpers: to_json_with_bytes (line 2726) throws the hardcoded message, Any::to_json (lines 6336 and 6348) returns null for an InternalBlob or a WTFStringImpl body.

Fix

  • Remove the three checks. The body text goes to EncodedSlice__toJSONObject or BunString__toJSON as any other text does. Since Reject json() with the JSON.parse SyntaxError on the buffered path #41387, both helpers parse an empty input as "" and throw the JSON.parse SyntaxError.
  • Every path now gives one result for an empty body: a rejected promise with the JSON.parse("") SyntaxError. This is what the fetch spec says (json() runs JSON.parse on the text and rethrows) and what Node does.
  • Verified: test/js/web/fetch/body.test.ts (new describe block, 11 of its 13 cases fail on bun 1.4.1, and the <empty> cases of the json() table now check the message). Also test/js/bun/util/bun-file.test.ts, test/js/bun/spawn/readablestream-helpers.test.ts and test/js/bun/http/serve.test.ts on the debug build.

Background

  • A Body holds its bytes in one of several forms: a Blob (a store with bytes or a file), an InternalBlob (an owned byte vector, what a fetch() or Bun.serve() body arrives as), or a WTFStringImpl (a JS string body). Any::to_json dispatches on the form.
  • EncodedSlice__toJSONObject (src/jsc/bindings/bindings.cpp) and BunString__toJSON (src/jsc/bindings/BunString.cpp) are the two C++ helpers that run JSONParseWithException on the text.
  • This PR first changed those helpers too. Reject json() with the JSON.parse SyntaxError on the buffered path #41387 landed that half on 2026-09-04. This PR now holds only the Blob.rs change.
Notes
  • Probe on bun 1.4.1, await (await fetch(url)).json() where the server answers new Response(""): resolves null. With a 204: rejects Unexpected end of JSON input. new Response("").json(), new Blob([]).json(), Bun.file(empty).json(): Unexpected end of JSON input. new Blob([]).stream().json() and a Response over an empty ReadableStream: JSON Parse error: Unexpected EOF.
  • Node 26: new Response("").json() rejects with SyntaxError: Unexpected end of JSON input, the V8 message of JSON.parse(""). JSC's message for the same input is JSON Parse error: Unexpected EOF. The tests compare against JSON.parse("") of the running engine, not against a literal.
  • The BOM-only case (Blob(["\uFEFF"]), a file that holds only a byte order mark) ran through the removed check too. BOM::detect_and_split strips the mark, the helpers see an empty slice and throw the same error.
  • The Temporary lifetime branch in to_json_with_bytes is still freed: the _free guard below the removed check covers the empty slice.
  • A BOM-only Blob now reaches set_is_ascii_flag(true) from json(), as a BOM-prefixed Blob with ASCII content already does from text() and json(). The flag is wrong for the store in both cases, and a later slice(1).text() decodes the BOM bytes as Latin-1. That is the helper bug Blob: keep the caller's Blob intact after a slice read, an array body, and a rejected bytes() #38503 fixes in set_is_ascii_flag. This PR does not add a guard at the call site.
  • Self-review: 3 concerns raised. Addressed: the PR body names the issue and Reject json() with the JSON.parse SyntaxError on the buffered path #41387, and this is the rebase of Reject json() on an empty body with the JSON.parse SyntaxError #33658, not a new PR. Not addressed: the set_is_ascii_flag stamp above (owned by Blob: keep the caller's Blob intact after a slice read, an array body, and a rejected bytes() #38503).
  • bun-file.test.ts pins the message for a BOM-only file. It changes from the hardcoded text to the JSON.parse("") message.
  • Ran with BUN_JSC_validateExceptionChecks=1 on the json() tests of body.test.ts: 81 pass.
  • serve.test.ts: 295 pass, 2 fail (root range port(#7187), /bun:info to loopback clients). Both fail the same way on the released build in this environment, which runs as root.

no test proof · iteration 5 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/web/fetch/body.test.ts

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: b5aaf9af-1c56-40f8-827f-ef6c8f86b1a5

📥 Commits

Reviewing files that changed from the base of the PR and between c01965f and de493a1.

📒 Files selected for processing (3)
  • src/runtime/webcore/Blob.rs
  • test/js/bun/util/bun-file.test.ts
  • test/js/web/fetch/body.test.ts
💤 Files with no reviewable changes (1)
  • src/runtime/webcore/Blob.rs

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


Walkthrough

Changes

Empty JSON handling

Layer / File(s) Summary
Normalize empty JSON conversion
src/runtime/webcore/Blob.rs
Empty byte buffers, InternalBlob contents, and WTF strings now use normal JSON parsing instead of returning early.
Validate body JSON errors
test/js/web/fetch/body.test.ts, test/js/bun/util/bun-file.test.ts
Tests verify that empty and BOM-only inputs reject with the same syntax error as JSON.parse("") across body types, fetch responses, requests, streams, and files.

Suggested reviewers: jarred-sumner

Merge Risk: ⚪ Minimal · up to de493

Empty and BOM-only JSON bodies now reject with parser diagnostics rather than resolving to null, with coverage across the affected JSON body APIs. No current merge-blocking risk is identified.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description explains the problem, fix, affected APIs, verification steps, test results, and linked issue. It does not use the exact template headings, but it provides the required information in e…
Linked Issues check ✅ Passed The description identifies issue #24955 and clearly connects the implementation to the issue objective: rejecting empty JSON bodies with the JSON.parse SyntaxError.
Out of Scope Changes check ✅ Passed The code and test changes directly support empty-body JSON parsing behavior. The changes align with the stated objectives and do not indicate unrelated modifications.
Title check ✅ Passed The title clearly and concisely describes the primary change: rejecting json() calls on empty bodies with the JSON.parse SyntaxError.

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the claude label Jul 7, 2026
@robobun

robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:57 PM PT - Sep 5th, 2026

✅ @robobun, your commit de493a15d0bc0f6248e60a80033e4e8d5ac3b831 passed in Build #110446! 🎉


🧪   To try this PR locally:

bunx bun-pr 33658

That installs a local version of the PR into your bun-33658 executable, so you can run:

bun-33658 --bun

@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Found 3 issues this PR may fix:

  1. Response.json behavior is different between bun and node #24955 - PR fixes Response.json() returning null on empty/invalid body instead of throwing, matching Node behavior
  2. Failed to parse JSON when running Trigger.dev Express server with Bun (tsx works) #8702 - PR replaces the generic "Failed to parse JSON" with the actual parser diagnostic (token, position)
  3. failed to parse JSON #8524 - Same root cause: generic "Failed to parse JSON" error with no useful detail, now fixed by propagating JSONParseWithException

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #24955
Fixes #8702
Fixes #8524

🤖 Generated with Claude Code

@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Of the three suggested issues, linking only #24955: express res.json() with no argument sends an empty body, and this PR makes await response.json() reject on that instead of resolving null, matching Node.

#8702 reports a behavioural difference between bun and tsx on a request body; this PR only improves the rejection message and does not address whatever causes the parse failure there. #8524 is about importing a JSON file via the module loader, which already reports the parser diagnostic and is not touched here.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No bugs found; the change looks correct and well-tested, but it removes the #5859 JSONParseWithException workaround and flips empty-body .json() from resolving null to rejecting — worth a quick human sanity check on that behavior change.

Extended reasoning...

Overview

Two C++ bindings (BunString__toJSON, ZigString__toJSONObject) switch from JSONParse to JSONParseWithException so the parser's own SyntaxError (with token/position) propagates instead of a generic "Failed to parse JSON". Null input strings are normalised to emptyString() so the parser throws its own EOF diagnostic. In Blob.rs, three empty-body shortcuts are removed: the hardcoded "Unexpected end of JSON input" in to_json_with_bytes, and two return Ok(JSValue::NULL) early-returns in Any::to_json for the InternalBlob/WTFStringImpl arms. Four test files are updated with new coverage that pins .json() rejection to exactly what JSON.parse throws for the same bytes.

I traced the memory-safety side of the removed empty-buffer branch in to_json_with_bytes: the _free = ... TemporaryBytes(raw_bytes) guard further down still reclaims the leaked Box<[u8]> on the Temporary path, so removing the early return doesn't leak. I also confirmed via JSC__AnyPromise__wrap that a returned ErrorInstance value (which ZigString__toJSONObject produces after clearing the exception) is converted to a promise rejection, so the fetch-response path rejects rather than resolving with the error object.

Security risks

None. This is error-message plumbing on the JSON body-consumer path; no new input surface, auth, or crypto.

Level of scrutiny

Moderate. The code change is small and mechanical, but two things push it past auto-approval:

  1. User-visible behavior change: await new Response("").json() (and the empty InternalBlob/WTFStringImpl fetch-body paths) previously resolved to null; now they reject with a SyntaxError. That's the spec- and Node-correct behavior, and the PR tests it explicitly, but it's still a breaking change for anyone relying on the old null.
  2. Reverting a documented workaround: the JSONParse fallback carried a // JSONParseWithException does not propagate exceptions as expected. See #5859 comment. The PR argues (plausibly) that #5859's real cause was a scope-nesting bug, not JSONParseWithException itself, and the #5859 regression test in serve.test.ts still passes with the updated assertion. A maintainer who remembers that history should confirm.

Other factors

Test coverage is thorough — the new body.test.ts block exercises Response, Request, Blob, ReadableStream body, Bun.file(), and a live fetch() against the exact JSON.parse message across five malformed inputs including empty, plus a dedicated "empty body rejects (does not resolve null)" case. The exception-scope handling in BunString__toJSON looks correct (RETURN_IF_EXCEPTION after the parse, fallback throw only when no exception is set).

@robobun

robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status on build 69875 (finished): 284 jobs passed, including every test lane that ran. No error-style annotations.

The only failures are both darwin 26 aarch64 - test-bun shards, which exited with buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun' before any tests ran. The darwin 14 shards subsequently ran and passed. None of this touches the diff; ready for review.

@robobun

robobun commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

#41387 makes the JSONParseWithException change in BunString__toJSON and EncodedSlice__toJSONObject, with the same handling of an empty input. It fixes a flaky test on main. It does not change the empty-body checks in Blob.rs. If #41387 lands first, this PR only needs its Blob.rs change for #24955.

Jarred-Sumner pushed a commit that referenced this pull request Sep 4, 2026
…41387)

### Problem
- `test/js/bun/spawn/readablestream-helpers.test.ts` fails at random. On
PR builds 110091 (debian 13 aarch64) and 110186 (windows 11 aarch64), a
case got `Failed to parse JSON` where it expected `JSON Parse error:
Expected '}'`, or the reverse.
- `json()` on a stream that holds the whole body parses it in
`BunString__toJSON` (`src/jsc/bindings/BunString.cpp:522`) or
`EncodedSlice__toJSONObject` (`src/jsc/bindings/bindings.cpp:2748`).
These call `JSC::JSONParse` and throw the generic message. A streamed
body gets the `JSON.parse` message.
- For `proc.stdout`, timing selects the path. #20694 pinned one message
per case. Since #41204, one failure is final.

### Fix
- Both helpers call `JSONParseWithException`, and parse `""` for an
empty input. For the same text, they throw the SyntaxError that
`JSON.parse` throws. The removed "See #5859" comment is stale (see
Notes).
- `Response.json()`, `Request.json()`, `Blob.json()` and
`Bun.file().json()` change the same way. The fetch spec rethrows the
`JSON.parse` exception. Node does too.
- `scripts/verify-baseline-static/allowlist-x64.txt` gets
`llint_op_jmp_wide32`, a documented LLInt decode false positive that
moved with the code layout (see Notes).
- Verified on the ASAN build with `BUN_JSC_validateExceptionChecks=1`:
`readablestream-helpers.test.ts` (new cases), `body.test.ts`,
`serve.test.ts`. Self-reviewed: 5 concerns raised, 4 addressed.

### Background
- A stream that Bun creates has a native source. A Blob source returns
the whole body at once, so `json()` tries it first.
- `JSC::JSONParse` returns an empty value on a syntax error and throws
nothing.
- Bun creates `proc.stdout` when JS first reads it. If the pipe is at
EOF then, it is a Blob stream. `Bun.spawn()` reads the pipe once before
it returns, and on Windows `exited` can resolve before EOF.

<details><summary>Notes</summary>

- Reproduction on the released build (1.4.1):
- `new Blob([s]).stream().json()` rejects with `Failed to parse JSON`. A
stream with a JavaScript source rejects with `JSON Parse error: Expected
'}'`.
- `proc.stdout.json()` with no await after `Bun.spawn()`: 11 of 50 runs
took the buffered path when the parent and a fast child (`/bin/echo`)
share one CPU. This is the debian case.
- After `await proc.exited`, a grandchild that keeps the pipe open makes
the streamed path run. This is the Windows case.
- Empty input: `JSONParseWithException` throws nothing for a null
string, and an empty input converts to one. A child that printed only a
byte order mark got `JSON Parse error: Unexpected EOF` on the streamed
path and `Failed to parse JSON` on the buffered path. Both paths now
give the first. A zero-byte stdout was already the same on both paths.
- #5859: in 2023 the helper caught the exception and returned it as a
value. Today both helpers use a throw scope. The #5859 tests pass with
`BUN_JSC_validateExceptionChecks=1`.
- Baseline scan: the `:linux: x64-musl - verify-baseline` step flagged
one `RDPMC` in `llint_op_jmp_wide32`. Each LLInt opcode handler starts
with an embedded 4-byte opcode id, and the linear-sweep decoder desyncs
on it. The allowlist already covers two sibling handlers for this
reason. The same scan lists those two entries as stale, so the desync
moved to this handler. The emulator phase of the same job passes, and
the step passed on main at the same base commit. The three LLInt entries
are blanket passes, as the triage guide in
`scripts/verify-baseline-static/CLAUDE.md` says for a data-in-.text
misdecode.
- The helpers keep `Failed to parse JSON` for a string that failed to
convert (a dead string, or a failed allocation).
- The empty-body checks in `Blob.rs` run before the helpers. They
resolve `null` or throw `Unexpected end of JSON input`. That is #24955,
and this PR does not change them.
- #33658 (open since July) makes the same change to the two helpers, and
also removes the empty-body checks for #24955. This PR supersedes the
helper half of #33658. After it lands, #33658 only needs its `Blob.rs`
change.
- Self-review, 5 concerns. Addressed: the narrowed claim, the
empty-input case, the note that the failures were on PR builds, and the
relation to #33658. Not addressed: `Blob::to_json_with_bytes` decodes a
body that starts with FF FE as UTF-16LE, and the streamed path decodes
it as UTF-8. That difference is separate from this change.
- Tests on the debug ASAN build. The first three also ran with
`BUN_JSC_validateExceptionChecks=1`.
- `test/js/bun/spawn/readablestream-helpers.test.ts`: 32 pass. The
released build fails 3 (the two new cases and `(after exited)`).
- `test/js/web/fetch/body.test.ts`: 476 pass. The released build fails
34 (17 inputs, for `Request` and `Response`).
- `test/js/bun/http/serve.test.ts`: 295 pass, 2 fail. The 2 failures
(`root range port(#7187)` and `/bun:info to loopback clients`) also fail
on the released build in this environment, which runs as root.
- Also pass: `bun-file.test.ts`, `regression/issue/02367.test.ts`,
`express.json.test.ts`, `spawn.ipc.test.ts`,
`spawn.ipc.bun-node.test.ts`, and the json cases of `fetch.test.ts`. The
one failure there, `bad permissions throws`, also fails as root on the
released build.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 1 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/web/fetch/body.test.ts, test/js/bun/http/serve.test.ts

<!-- robobun:evidence:end -->
Remove the three empty-body checks in Blob.rs that ran before the JSON
helpers. They resolved null for a fetch() or Bun.serve() body and threw
a hardcoded message for a Blob body. The helpers now parse the empty
text and throw the SyntaxError that JSON.parse("") throws.
@robobun
robobun force-pushed the farm/9e40529b/json-body-error-message branch from eecc9a6 to de493a1 Compare September 5, 2026 19:31
@robobun robobun changed the title webcore: propagate JSON.parse diagnostic from Body/Blob .json() Reject json() on an empty body with the JSON.parse SyntaxError Sep 5, 2026
@robobun

robobun commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main and trimmed. #41387 landed the helper change in BunString.cpp and bindings.cpp, so this PR now holds only the Blob.rs change and its tests. On the released build, fetch() of an empty body still resolves null from .json() (#24955). With this branch every empty body path rejects with the JSON.parse("") SyntaxError. The PR body describes the current state.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM — small, well-tested spec-compliance fix.

Checked that the deleted Temporary-lifetime heap::take in to_json_with_bytes is not a leak: the fall-through path already arms TemporaryBytes(raw_bytes) (Blob.rs:2762) before the parse call, so the leaked Box<[u8]> is still reclaimed on empty and BOM-only input.
Verified all three storage arms (Blob / InternalBlob / WTFStringImpl) now uniformly reach the real parser, matching the fetch spec's "reject with what %JSON.parse% throws".
Grepped for other assertions on the old "Unexpected end of JSON input" string — only the one updated in bun-file.test.ts.
New tests follow harness conventions (port: 0, tempDir, await using, test.each, added to existing files) and cover the full .json() entry-point matrix.

Extended reasoning...

Overview

This PR removes three empty-body short-circuits from src/runtime/webcore/Blob.rs so that .json() on an empty body always goes through the real JSON parser and rejects with JSC's native SyntaxError: JSON Parse error: Unexpected EOF — the same error JSON.parse("") throws — instead of the previous divergent behavior where a fetch() Response resolved to null (InternalBlob/WTFStringImpl arms) or threw a hand-rolled V8-style message (Blob arm). One existing test assertion is updated for the new message, and a comprehensive describe.concurrent suite is added covering every body-holding path (fetch Response, Bun.serve incoming Request, constructed Response/Request/Blob, ReadableStream, Bun.file with empty and BOM-only files).

Security risks

None. This is a pure error-path behavioral change in JSON parsing of empty input; no auth, crypto, permissions, or untrusted-input parsing surface is affected. The change actually reduces hand-rolled code by deferring to the engine's own parser.

Level of scrutiny

Moderate, focused on memory safety. The one non-trivial deletion was the early return that explicitly reclaimed a leaked Box<[u8]> when LIFETIME == Temporary. I read the surrounding function and confirmed the fall-through path arms a TemporaryBytes(raw_bytes) RAII guard at line 2762 before any parse call, so the allocation is still freed on empty/BOM-only input — the deleted manual reclaim was only needed because the old early return happened before that guard was armed. The UTF-16LE branch (which has its own manual reclaim) is unreachable for empty input since no BOM is detected. The other two deletions (InternalBlob and WTFStringImpl returning JSValue::NULL) have no resource-ownership implications.

Other factors

The fix satisfies REVIEW.md's "fix the whole class" rule: all three body-storage variants are corrected together, and the test matrix exercises every .json() entry point rather than just the reported repro. Tests follow all harness conventions from CLAUDE.md/test/CLAUDE.md. The user-visible error-message change is the intended fix (aligning with the WHATWG spec and JSON.parse), and a grep confirmed only one existing test asserted the old string. A new commit landed since the prior review on this PR, so posting a fresh verdict is warranted.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-09-05.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Response.json behavior is different between bun and node

1 participant