Skip to content

fix: handle web response body lengths correctly - #2010

Open
jakezwang wants to merge 1 commit into
koajs:masterfrom
jakezwang:fix-web-response-length
Open

jakezwang wants to merge 1 commit into
koajs:masterfrom
jakezwang:fix-web-response-length

Conversation

@jakezwang

@jakezwang jakezwang commented Sep 18, 2026

Copy link
Copy Markdown

response.length currently treats Web ReadableStream and Response bodies as JSON and returns 2. This also makes HEAD responses send Content-Length: 2 when the actual body length is unknown.

Leave those lengths undefined, and use Blob.size when a Blob has no Content-Length header. Explicit Content-Length values still take precedence. Tests cover the getter, HEAD responses, and preserving headers from a Response.

Validation: lint, build, commitlint, and all 464 tests with coverage on Node 22, 24, and 26.

Checklist

  • I have ensured my pull request is not behind the main or master branch of the original repository.
  • I have rebased all commits where necessary so that reviewing this pull request can be done without having to merge it first.
  • I have written a commit message that passes commitlint linting.
  • I have ensured that my code changes pass linting tests.
  • I have ensured that my code changes pass unit tests.
  • I have described my pull request and the reasons for code changes along with context if necessary.

Summary by Sourcery

Handle Web response body lengths correctly without inventing Content-Length values for bodies whose size is unknown.

Bug Fixes:

  • Correct response body length detection for Web ReadableStream and Response bodies by leaving unknown lengths undefined instead of guessing a serialized length.
  • Use Blob size when no explicit Content-Length header is present while preserving explicitly supplied Content-Length values.

Tests:

  • Add coverage for unknown Web body lengths, Blob size fallback, HEAD responses, and preservation of explicit Response headers.

Summary by CodeRabbit

  • Bug Fixes
    • Improved response length handling for ReadableStream and Response bodies when no Content-Length is available.
    • Blob-based response bodies now correctly report their size.
    • HEAD responses no longer infer or expose an incorrect content length.
    • Explicitly provided content lengths continue to take precedence.

@coderabbitai

coderabbitai Bot commented Sep 18, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 74b0856c-62a6-4b9f-9770-77e6e51c6f40

📥 Commits

Reviewing files that changed from the base of the PR and between c3c14b6 and d23c14e.

📒 Files selected for processing (3)
  • __tests__/application/respond.test.js
  • __tests__/response/length.test.js
  • lib/response.js

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


📝 Walkthrough

Walkthrough

The response length getter now returns undefined for ReadableStream and Response bodies. It returns the size of a Blob body when no Content-Length header exists. Tests cover manual length overrides, HEAD responses, and preservation of an explicit Content-Length header.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to d23c1

No concrete merge-blocking regression remains; the response-length changes are covered by targeted tests.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: correcting Web response body length handling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 3…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@sourcery-ai

sourcery-ai Bot commented Sep 18, 2026

Copy link
Copy Markdown

Reviewer's Guide

Corrects response length detection by leaving Web ReadableStream and Response bodies unknown, using Blob.size when applicable, and preserving explicit Content-Length values; regression tests cover the length getter and HEAD response behavior.

Flow diagram for response body length detection

flowchart TD
    A[Response body] --> B{Explicit Content-Length?}
    B -->|Yes| C[Use explicit length]
    B -->|No| D{Body type}
    D -->|ReadableStream or Response| E[Leave length undefined]
    D -->|Blob| F[Use Blob.size]
    D -->|String| G[Use Buffer.byteLength]
    D -->|Buffer| H[Use buffer length]
    D -->|Other value| I[Use JSON byte length]
Loading

File-Level Changes

Change Details Files
Treat Web stream and Response bodies as having unknown lengths instead of serializing them for size calculation.
  • Return undefined for ReadableStream and Response bodies.
  • Continue allowing explicitly assigned lengths to override the unknown value.
  • Verify HEAD responses omit Content-Length for bodies whose size cannot be determined.
lib/response.js
__tests__/response/length.test.js
__tests__/application/respond.test.js
Derive Blob response lengths from the Blob’s intrinsic size when no header is present.
  • Use Blob.size as the fallback length after Content-Length is absent.
  • Add coverage for length calculation after removing the header.
lib/response.js
__tests__/response/length.test.js
Preserve explicit response headers and validate corrected length behavior across response handling.
  • Update Response-based HEAD coverage to assert an explicit zero Content-Length is preserved.
  • Add regression tests for Web ReadableStream and Response bodies.
__tests__/application/respond.test.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Sep 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.90%. Comparing base (c3c14b6) to head (d23c14e).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #2010   +/-   ##
=======================================
  Coverage   99.90%   99.90%           
=======================================
  Files           9        9           
  Lines        2127     2128    +1     
=======================================
+ Hits         2125     2126    +1     
  Misses          2        2           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've reviewed your changes and they look great!

Sourcery assessment

Approved.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@yowainwright

Copy link
Copy Markdown
Member

@jakezwang this is a good PR. Thank you!

I want to hold off on approving for a bit because even though this fix is correct, it reads like it could lead to a breaking change for products that have already configured workarounds for the content length being 2 vs. unknown—which you are right to address. If I'm incorrect in this concern, I'm all ears! @sourcery-ai @coderabbitai can you take a first-pass on my concern?

If other teammates approve because I'm overthinking, I'm all for that as well!

I will merge this PR for sure, moving towards v4.

Thank you! 🥇

@coderabbitai

coderabbitai Bot commented Sep 19, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- PR diff ---'
git diff --no-ext-diff HEAD^ HEAD -- lib/response.js __tests__/response/length.test.js __tests__/application/respond.test.js

echo
echo '--- response.js outline ---'
ast-grep outline lib/response.js --items all --view expanded

echo
echo '--- relevant response implementation ---'
rg -n -C 12 'get length|set length|Content-Length|respond|ReadableStream|Response|Blob' lib/response.js lib/application.js

echo
echo '--- HEAD and Response test contexts ---'
rg -n -C 16 'when HEAD is used|\.body is a Response|ReadableStream|Response\(' __tests__/application/respond.test.js __tests__/response/length.test.js

echo
echo '--- package version ---'
rg -n -C 2 '"version"' package.json

Length of output: 42134


@yowainwright Your concern is valid, with a narrow scope.

This PR changes an observable HEAD response behavior for ReadableStream and Response bodies that have no explicit Content-Length.

Before this PR, Koa calculated response.length by serializing these Web objects. Serialization produces {}, so Koa sent:

Content-Length: 2

That value did not describe the body. It was an implementation artifact.

After this PR, Koa leaves the length unknown and does not send Content-Length for that case. This is correct HTTP behavior.

The change does not affect these cases:

  • String and Buffer bodies continue to get a computed Content-Length.
  • Blob bodies use Blob.size.
  • An explicit Content-Length, including one supplied by a Response, remains unchanged.
  • Applications can still set ctx.length or Content-Length explicitly when they know the length.

A product that specifically detects or compensates for Content-Length: 2 can observe a behavior change. That makes this semver-relevant in practice, even though it fixes invalid output. Since this is targeted for v4, the timing is appropriate.

I recommend merging with a release note that states: HEAD responses for Web ReadableStream and Response bodies no longer emit the incorrect fallback Content-Length: 2 when the length is unknown.

You are interacting with an AI system.

@koajs koajs deleted a comment from coderabbitai Bot Sep 19, 2026
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