Skip to content
Myr

fix(pretty-json): don't break responses with unparseable JSON bodies (#5377)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(pretty-json): don't break responses with unparseable JSON bodies When prettification is active, responses with a JSON content-type but an empty or invalid body (e.g. a 204, or JSON passed through from an upstream) turned into 500 errors because c.res.json() threw after next(). Parse a clone of the response so the original stays intact when parsing fails, and remove the stale Content-Length after replacing the body, since the prettified body is longer than the original. * test(pretty-json): cover 304 passthrough and header preservation * refactor(pretty-json): narrow the pass-through catch to body parsing Only the clone and JSON parse should lead to a pass-through; response construction and header mutation run outside the try. Use the actual byte length (19) for the stale Content-Length fixture, assert Content-Length survives an unchanged pass-through, and state the consumed-body guarantee precisely: the response passes through with its body still consumed. ---------

authored by Neil Daquioag · committed by GitHub · parent 00ee875 · Browse files · 2 files+106 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: ndycode <ndycode@users.noreply.github.com>

Diff stats

2 files+106 added−1 removed

  • tests:+96 added−0 removed
  • other:+10 added−1 removed

2 files+106 added−1 removed

modified:src/middleware/pretty-json/index.test.ts+96 added
modified:src/middleware/pretty-json/index.ts+10 added-1 removed
50 unmodified lines
51 const pretty = options?.force || c.req.query(targetQuery) || c.req.query(targetQuery) === ''52 await next()53 const contentType = c.res.headers.get('Content-Type')54 if (pretty && contentType && jsonContentTypeRegex.test(contentType)) {55 const obj = await c.res.json()55 // Read from a clone so that the response is kept intact when the body is not parseable as JSON56 let obj: unknown57 try {58 obj = await c.res.clone().json()59 } catch {60 // e.g. an empty 204 response or a body that is not valid JSON61 return62 }63 c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res)64 // The length of the body has changed, so remove the stale Content-Length65 c.res.headers.delete('Content-Length')66 }67 }68}