Search code examples
javascriptnode.jshttpserverenumerable

Why is the headers property of an http.IncomingMessage non-enumerable?


Say I create a node server with the following:

const server = http.createServer((req, res) => {
  // req is an IncomingMessage
}

I believe the first param, req, is an instance of IncomingMessage

I know this instance has a headers property.

If I do Object.keys(req), however, I do not see the headers key. I assume this is because this the headers property is non-enumerable.

Question is - why? Why is headers not enumerable whereas rawHeaders is? Is this just how it is, or is there a specific reason / benefit to this?

Thanks!


Solution

  • Previously, in Node.js versions before 15.1.0, the req.headers property was an own property of the IncomingMessage object. It was readily available and enumerable, meaning you could directly access it and iterate over it using Object.keys() or a for…in loop. However, starting from version 15.1.0, this behavior was altered.

    The req.headers property is no longer an own property of the IncomingMessage object. Instead, it is lazily computed using an accessor property on the prototype. This means that when you access req.headers, it is now computed on-the-fly and not stored as a direct property on the req object.

    for more details you can go here : https://medium.com/@apoorva.gcet/understanding-the-change-in-req-headers-in-node-js-version-15-1-0-and-above-dbcb3ea812a0