From 2f36fd90ffcafca8dec0b71f5d902fdfebf4fdfb Mon Sep 17 00:00:00 2001 From: Mahmoud Hamdi Date: Sun, 29 Mar 2026 04:31:24 +0200 Subject: [PATCH] fix: handle undefined statusText in writeHead arguments When writeHead is called with three arguments where the second argument (statusText) is undefined or null, the headers object at the third argument position was being ignored. This is because the argument parsing only checked if the second argument was a string to determine the header index, without considering that three arguments always means the third is headers. This caused headers set via writeHead(status, undefined, headers) to be silently dropped, which affected downstream packages like compression middleware (expressjs/compression#254). The fix checks if there are more than two arguments, and if so, always reads headers from the third position, matching Node.js native writeHead behavior. --- index.js | 4 +++- test/test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index d691cc7..15ad55a 100644 --- a/index.js +++ b/index.js @@ -120,7 +120,9 @@ function setWriteHeadHeaders (statusCode) { var length = arguments.length var headerIndex = length > 1 && typeof arguments[1] === 'string' ? 2 - : 1 + : length > 2 + ? 2 + : 1 var headers = length >= headerIndex + 1 ? arguments[headerIndex] diff --git a/test/test.js b/test/test.js index 2efcf30..bb69742 100644 --- a/test/test.js +++ b/test/test.js @@ -221,6 +221,34 @@ describe('onHeaders(res, listener)', function () { }) }) + describe('writeHead(status, undefined, obj)', function () { + it('should set headers when statusText is undefined', function (done) { + var server = createServer(echoListener, handler) + + function handler (req, res) { + res.writeHead(200, undefined, { 'X-Outgoing': 'test' }) + } + + request(server) + .get('/') + .expect('X-Outgoing-Echo', 'test') + .expect(200, done) + }) + + it('should set headers when statusText is null', function (done) { + var server = createServer(echoListener, handler) + + function handler (req, res) { + res.writeHead(200, null, { 'X-Outgoing': 'test' }) + } + + request(server) + .get('/') + .expect('X-Outgoing-Echo', 'test') + .expect(200, done) + }) + }) + describe('writeHead(status, obj)', function () { it('should be available in listener', function (done) { var server = createServer(listener, handler)