From aa98a454e8544709b817d9623e623ef8e1d3b368 Mon Sep 17 00:00:00 2001 From: princejain756 Date: Wed, 21 Oct 2026 12:19:58 +0530 Subject: [PATCH] fix(res.redirect): add Content-Length only if Transfer-Encoding is not present res.redirect() always set Content-Length, even when Transfer-Encoding was already set. That is the same conflict #4893 fixed for res.send(), and Node's HTTP client rejects such responses with a parse error. Apply the same guard as res.send(): Content-Length is only set when no Transfer-Encoding header is present. Fixes #7506. --- lib/response.js | 6 +++++- test/res.redirect.js | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/response.js b/lib/response.js index 0d5a4ae4d4d..7f6d0664e97 100644 --- a/lib/response.js +++ b/lib/response.js @@ -857,7 +857,11 @@ res.redirect = function redirect(url) { // Respond this.status(status); - this.set('Content-Length', Buffer.byteLength(body)); + // Because Content-Length and Transfer-Encoding can't be present in the response headers together, + // Content-Length should be added only if there is no Transfer-Encoding header + if (!this.get('Transfer-Encoding')) { + this.set('Content-Length', Buffer.byteLength(body)); + } if (this.req.method === 'HEAD') { this.end(); diff --git a/test/res.redirect.js b/test/res.redirect.js index 8d2b164e4a2..cad1d2fcf3c 100644 --- a/test/res.redirect.js +++ b/test/res.redirect.js @@ -78,6 +78,32 @@ describe('res', function(){ }) }) + describe('when Transfer-Encoding header is present', function(){ + var transferEncodings = [ + 'chunked', + 'compress', + 'deflate', + 'gzip' + ]; + + transferEncodings.forEach(function(encoding){ + it('should not add Content-Length header if Transfer-Encoding header is equal to ' + encoding, function(done){ + var app = express(); + + app.use(function(req, res){ + res.set('Transfer-Encoding', encoding).redirect('http://google.com'); + }); + + request(app) + .get('/') + .expect(utils.shouldNotHaveHeader('Content-Length')) + .expect(utils.shouldHaveHeader('Transfer-Encoding')) + .expect('Location', 'http://google.com') + .expect(302, done); + }) + }) + }) + describe('when accepting html', function(){ it('should respond with html', function(done){ var app = express();