From b9c12c21843f4f5a7e49a5126bec7f80ead63be2 Mon Sep 17 00:00:00 2001 From: vaibhavmashal Date: Tue, 8 Sep 2026 22:15:26 +0530 Subject: [PATCH] fix: prevent ERR_HTTP_HEADERS_SENT when response headers sent during request wait (#162) --- index.js | 4 ++++ test/test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/index.js b/index.js index bf15e48..3ac07a0 100644 --- a/index.js +++ b/index.js @@ -243,6 +243,10 @@ function getResponseStatusCode (res) { function send (req, res, status, headers, message) { function write () { + if (res.headersSent) { + return + } + // response body var body = createHtmlDocument(message) diff --git a/test/test.js b/test/test.js index 516e088..76f4294 100644 --- a/test/test.js +++ b/test/test.js @@ -393,6 +393,34 @@ var topDescribe = function (type, createServer) { test.write(buf) test.expect(500, done) }) + + it('should not throw if headers are sent while waiting for request', function (done) { + var buf = Buffer.alloc(1024 * 16, '.') + var server = createServer(function (req, res, next) { + next() + res.setHeader('Content-Type', 'text/plain') + res.end('ok') + }) + var test = wrapper(request(server).post('/foo')) + test.write(buf) + test.write(buf) + test.write(buf) + test.expect(200, 'ok', done) + }) + + it('should not throw if headers are sent while waiting for request on error', function (done) { + var buf = Buffer.alloc(1024 * 16, '.') + var server = createServer(function (req, res, next) { + next(new Error('boom!')) + res.setHeader('Content-Type', 'text/plain') + res.end('error response') + }) + var test = wrapper(request(server).post('/foo')) + test.write(buf) + test.write(buf) + test.write(buf) + test.expect(200, 'error response', done) + }) }) describe('when res.statusCode set', function () {