Skip to content

"Cannot set headers after they are sent to the client" (ERR_HTTP_HEADERS_SENT) with AmazonDaxClient #4566

@rchl

Description

@rchl

Package + Version

  • @sentry/browser
  • @sentry/node
  • raven-js
  • raven-node (raven for node)
  • other:

Version:

6.17.5

Description

This affects a complicated setup that I can't provide reproduction for easily.

The setup is:

  • and express backend with express-session middleware running
  • custom session store that retrieves and stores session in a DynamoDB database and uses AmazonDaxClient for DB operations

Steps are:

  • navigate to express route that just returns some data res.json('OK')
  • The express-middleware reads the session before handling the route and tries to save it on res.end() (which express-session wraps)
  • When the saving of the session fails the dax client emits an error event:
    Screenshot 2022-02-14 at 16 08 36
  • The emitted event seems to get handled by Sentry itself in the code linked below, resulting in the next express middleware running, even though the previous one has already responded to the request:
    }
    return function sentryRequestMiddleware(
    req: http.IncomingMessage,
    res: http.ServerResponse,
    next: (error?: any) => void,
    ): void {
    if (options && options.flushTimeout && options.flushTimeout > 0) {
    // eslint-disable-next-line @typescript-eslint/unbound-method
    const _end = res.end;
    res.end = function (chunk?: any | (() => void), encoding?: string | (() => void), cb?: () => void): void {
    void flush(options.flushTimeout)
    .then(() => {
    _end.call(this, chunk, encoding, cb);
    })
    .then(null, e => {
    logger.error(e);
    });
    };
    }
    const local = domain.create();
    local.add(req);
    local.add(res);
    local.on('error', next);
  • The difference with and without Sentry is that this.domain is not defined in the code below when Sentry is not used
    Screenshot_2022-02-14_at_16 17 17

When the issue triggers then we are getting the ERR_HTTP_HEADERS_SENT error from Node because some later error middleware runs even though we've responded already.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions