Skip to content

feat: check Content-Length header early when size limit is set#1889

Open
singhvishalkr wants to merge 2 commits into
node-fetch:mainfrom
singhvishalkr:feat/879-content-length-early-check
Open

feat: check Content-Length header early when size limit is set#1889
singhvishalkr wants to merge 2 commits into
node-fetch:mainfrom
singhvishalkr:feat/879-content-length-early-check

Conversation

@singhvishalkr

Copy link
Copy Markdown

When the request specifies a \size\ limit,
ode-fetch\ currently waits until it has streamed enough body content to exceed the limit before throwing. If the server sends a valid \Content-Length\ header, we can check it upfront and fail immediately without consuming any body data.

This change adds an early check in the response handler: if
equest.size > 0\ and the \Content-Length\ header indicates a response larger than the limit, the fetch is rejected with a \max-size\ error right away.

This optimization benefits scenarios where the server provides accurate content length information. When no \Content-Length\ is present or when the header value is smaller than the limit, the existing streaming check still applies.

I added a test endpoint /size/content-length\ that returns a small body with a large \Content-Length\ header, and a test to verify the early rejection.

Closes #879

Currently node-fetch sends the Host header as the last header when it is automatically added. Browsers and other HTTP libraries send Host as the first header.

This change prepends the Host header to match browser behavior. If the user provides a custom Host header, it is still placed first.

Fixes node-fetch#1570
When the request specifies a size limit, the Content-Length response header is now checked before consuming the body. If Content-Length exceeds the limit, the request is rejected immediately with a max-size error instead of waiting to stream the entire response.

This provides faster failure for oversized responses when the server sends a valid Content-Length header.

Closes node-fetch#879
@singhvishalkr singhvishalkr force-pushed the feat/879-content-length-early-check branch from 71739b2 to 8ce96d3 Compare May 25, 2026 17:12
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.

RFC: Content-Length on Response should be taken into account?

1 participant