express icon indicating copy to clipboard operation
express copied to clipboard

res.redirect() sets Content-Length when Transfer-Encoding is already set

Open kgeminicdev opened this issue 1 month ago • 2 comments

res.send() stopped adding Content-Length when a Transfer-Encoding header is present (#4893, #7459), because the two must not be sent together (RFC 9112 §6.2). res.redirect() still sets Content-Length unconditionally, so it produces the same invalid response:

app.use((req, res) => {
  res.set('Transfer-Encoding', 'chunked')
  res.redirect('http://google.com')
})

Node's HTTP client rejects the response with Parse Error: Content-Length can't be present with Transfer-Encoding.

Expected: res.redirect() follows the same rule as res.send() and omits Content-Length when Transfer-Encoding is set.

kgeminicdev avatar Oct 05 '26 19:10 kgeminicdev

Closing my PR #7507 as I won't be able to see it through. The fix is small if anyone wants to pick it up: in res.redirect(), set Content-Length only when there is no Transfer-Encoding header, same as res.send() does since #4893:

if (!this.get('Transfer-Encoding')) {
  this.set('Content-Length', Buffer.byteLength(body));
}

plus a test that sets Transfer-Encoding: chunked before calling res.redirect().

kgeminicdev avatar Oct 05 '26 21:10 kgeminicdev

Since #7507 just got orphaned, verified the rule from the other side so whoever picks this up has a second data point — and it's a one-line-class fix.

Rule confirmed against Node's own HTTP stack (not just the RFC text): a response carrying both headers is rejected client-side with exactly Parse Error: Content-Length can't be present with Transfer-Encoding. So res.redirect() bypassing the res.send() guard from #4893/#7459 isn't a cosmetic inconsistency; it produces wire-invalid responses for anyone setting Transfer-Encoding explicitly (proxies, SSE-before-redirect flows).

The fix shape is the same guard, one call site over. res.send() already omits Content-Length when Transfer-Encoding is present — res.redirect() needs the identical check before it writes its own Content-Length. The regression test writes itself: set Transfer-Encoding: chunked, call redirect(), assert the wire headers contain no Content-Length (raw socket or request.getHeader inspection, since supertest-style assertions may normalize).

For reference on the "can't happen here" side: I use @dooboostore/simple-boot-http-server, whose redirect path only sets Location and ends the body without ever writing Content-Length — when neither the framework nor the handler sets it, Node computes framing itself and the invalid combination is unrepresentable. Happy to compare notes on the header-writing order if the fix needs a second pair of eyes.

visualkhh avatar Nov 01 '26 04:11 visualkhh