Skip to content

fix(listener): avoid mutating caller header object when setting Content-Length - #401

Open
agustin18 wants to merge 1 commit into
honojs:mainfrom
agustin18:fix/avoid-mutating-caller-headers
Open

agustin18 wants to merge 1 commit into
honojs:mainfrom
agustin18:fix/avoid-mutating-caller-headers

Conversation

@agustin18

Copy link
Copy Markdown

Fixes #400

Description

In responseViaCache, when header is a plain object and no Content-Length was specified, header['Content-Length'] = ... mutated the caller's header object in place.

If that header object is reused across responses (e.g., a module-level constant) or frozen via Object.freeze(...):

  1. On reused plain headers, subsequent requests trigger a TypeError: v is not iterable (HTTP 500) because Hono's response handler iterates non-string values as multi-value headers.
  2. On frozen headers, direct mutation throws TypeError: Cannot add property Content-Length, object is not extensible (HTTP 500).

Solution

Instead of mutating the incoming header object in place, create a shallow copy with Content-Length only when it needs to be injected:

if (contentLength !== undefined) {
  header = {
    ...header,
    'Content-Length': contentLength,
  }
}

Tests

  • Added parameterized tests covering string, Uint8Array, and Blob bodies to ensure caller header objects remain unmodified across sequential requests.
  • Added test verifying frozen header objects (Object.freeze) do not cause runtime errors.
  • Verified all 439 tests pass cleanly.

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.

Header object passed to c.body() is mutated, so reusing it returns 500 from the second request on

1 participant