Skip to content

[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client #3994

@screendriver

Description

@screendriver

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the regression has not already been reported

Last working version

3.29.0

Stopped working in version

4.0.0

Node.js version

18.2.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Node.js running in Docker in an continuous integration environment

💥 Regression Report

Since the update to fastify v4.0.0 we receive randomly:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at onSendEnd (/builds/my/project/node_modules/fastify/lib/reply.js:493:7)
    at onSendHook (/builds/my/project/node_modules/fastify/lib/reply.js:427:5)
    at fallbackErrorHandler (/builds/my/project/node_modules/fastify/lib/error-handler.js:124:3)
    at handleError (/builds/my/project/node_modules/fastify/lib/error-handler.js:54:5)
    at onErrorHook (/builds/my/project/node_modules/fastify/lib/reply.js:594:5)
    at _Reply.Reply.send (/builds/my/project/node_modules/fastify/lib/reply.js:119:5)
    at defaultErrorHandler (/builds/my/project/node_modules/fastify/lib/error-handler.js:85:9)
    at handleError (/builds/my/project/node_modules/fastify/lib/error-handler.js:58:18)
    at onErrorHook (/builds/my/project/node_modules/fastify/lib/reply.js:594:5)
    at _Reply.Reply.send (/builds/my/project/node_modules/fastify/lib/reply.js:119:5)
    at /builds/my/project/node_modules/fastify/lib/wrapThenable.js:23:15

Sometimes it works sometimes most of the time not so I guess this is some kind of timing issue or race condition. All of our route handlers looks like this

{
    async handler(_request, reply) {
        return reply.type('application/json').send({
                foo: 'bar',
        });
    },
    method: 'GET'
};

or

{
    async handler(request, reply) {
        await delay(3000); // simulate slow responses

        return reply.type('application/json').headers({ my: 'header' }).send({ foo: 'bar' });
    },
    method: 'GET'
}

Steps to Reproduce

Unfortunately I don't have any steps or repository to reproduce the issue. Our CI jobs are failing mostly all the time because of this. Locally I cannot reproduce the issue (I guess because my machine has more power and is faster)

Expected Behavior

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions