97

I am writing a library which may set headers. I want to give a custom error message if headers have already been sent, instead of just letting it fail with the "Can't set headers after they are sent" message given by Node.js. So how to check if headers have already been sent?

Yogesh Umesh Vaity
  • 41,009
  • 21
  • 145
  • 105
powerboy
  • 10,523
  • 20
  • 63
  • 93
  • 2
    powerboy would you be able to accept the other answer, because the currently accepted answer doesn't work anymore? See @fiatjaf 's comment. – Willem Mulder Oct 31 '15 at 20:54

3 Answers3

218

Node supports the res.headersSent these days, so you could/should use that. It is a read-only boolean indicating whether the headers have already been sent.

if(res.headersSent) { ... }

See http://nodejs.org/api/http.html#http_response_headerssent

Note: this is the preferred way of doing it, compared to the older Connect 'headerSent' property that Niko mentions.

Willem Mulder
  • 12,974
  • 3
  • 37
  • 62
75

EDIT: as of express 4.x, you need to use res.headersSent. Note also that you may want to use setTimeout before checking, as it isn't set to true immediately following a call to res.send(). Source

Simple: Connect's Response class provides a public property "headerSent".

res.headerSent is a boolean value that indicates whether the headers have already been sent to the client.

From the source code:

/**
   * Provide a public "header sent" flag
   * until node does.
   *
   * @return {Boolean}
   * @api public
   */

  res.__defineGetter__('headerSent', function(){
    return this._header;
  });

https://github.com/senchalabs/connect/blob/master/lib/patch.js#L22

MalcolmOcean
  • 2,807
  • 2
  • 29
  • 38
Niko
  • 26,516
  • 9
  • 93
  • 110
16

Others answers point to Node.js or Github websites.

Below is from Expressjs website: https://expressjs.com/en/api.html#res.headersSent

app.get('/', function (req, res) {
  console.log(res.headersSent); // false
  res.send('OK');
  console.log(res.headersSent); // true
});
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140