On this page

class http.IncomingMessage extends stream.Readable

An IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers, and data.

Different from its socket value which is a subclass of stream.Duplex, the IncomingMessage itself extends stream.Readable and is created separately to parse and emit the incoming HTTP headers and payload, as the underlying socket may be reused multiple times in case of keep-alive.

E

aborted

History
Stability: 0Deprecated. Listen for 'close' event instead.

Emitted when the request has been aborted.

Emitted when the request has been completed.

P

message.aborted

History
Stability: 0Deprecated. Check message.destroyed from stream.Readable.
Type:boolean

The message.aborted property will be true if the request has been aborted.

P

message.complete

History
Type:boolean

The message.complete property will be true if a complete HTTP message has been received and successfully parsed.

This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:

const req = http.request({
  host: '127.0.0.1',
  port: 8080,
  method: 'POST',
}, (res) => {
  res.resume();
  res.on('end', () => {
    if (!res.complete)
      console.error(
        'The connection was terminated while the message was still being sent');
  });
});
P

message.connection

History
Stability: 0Deprecated. Use message.socket.

Alias for message.socket.

message.destroy(error?): this
Attributes
error:Error
Returns:this

Calls destroy() on the socket that received the IncomingMessage. If error is provided, an 'error' event is emitted on the socket and error is passed as an argument to any listeners on the event.

Type:Object

The request/response headers object.

Key-value pairs of header names and values. Header names are lower-cased.

// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
//   host: '127.0.0.1:8000',
//   accept: '*/*' }
console.log(request.headers);

Duplicates in raw headers are handled in the following ways, depending on the header name:

  • Duplicates of age, authorization, content-length, content-type, etag, expires, from, host, if-modified-since, if-unmodified-since, last-modified, location, max-forwards, proxy-authorization, referer, retry-after, server, or user-agent are discarded. To allow duplicate values of the headers listed above to be joined, use the option joinDuplicateHeaders in http.request() and http.createServer(). See RFC 9110 Section 5.3 for more information.
  • set-cookie is always an array. Duplicates are added to the array.
  • For duplicate cookie headers, the values are joined together with ; .
  • For all other headers, the values are joined together with , .
P

message.headersDistinct

History
Type:Object

Similar to message.headers, but there is no join logic and the values are always arrays of strings, even for headers received just once.

// Prints something like:
//
// { 'user-agent': ['curl/7.22.0'],
//   host: ['127.0.0.1:8000'],
//   accept: ['*/*'] }
console.log(request.headersDistinct);
P

message.httpVersion

History
Type:string

In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either '1.1' or '1.0'.

Also message.httpVersionMajor is the first integer and message.httpVersionMinor is the second.

P

message.method

History
Type:string

Only valid for request obtained from http.Server.

The request method as a string. Read only. Examples: 'GET', 'DELETE'.

P

message.rawHeaders

History
Type:string[]

The raw request/response headers list exactly as they were received.

The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.

Header names are not lowercased, and duplicates are not merged.

// Prints something like:
//
// [ 'user-agent',
//   'this is invalid because there can be only one',
//   'User-Agent',
//   'curl/7.22.0',
//   'Host',
//   '127.0.0.1:8000',
//   'ACCEPT',
//   '*/*' ]
console.log(request.rawHeaders);
P

message.rawTrailers

History
Type:string[]

The raw request/response trailer keys and values exactly as they were received. Only populated at the 'end' event.

M

message.setTimeout

History
message.setTimeout(msecs, callback?): http.IncomingMessage
Attributes
msecs:number
callback:Function

Calls message.socket.setTimeout(msecs, callback).

An AbortSignal that is aborted when the message is destroyed before completion or when its underlying socket closes before request handling or response reading completes. The signal is created lazily on first access — no AbortController is allocated for requests that never use this property.

This is useful for cancelling downstream asynchronous work such as database queries or fetch calls when a client disconnects mid-request.

import http from 'node:http';

http.createServer(async (req, res) => {
  try {
    const data = await fetch('https://example.com/api', { signal: req.signal });
    res.end(JSON.stringify(await data.json()));
  } catch (err) {
    if (err.name === 'AbortError') return;
    res.statusCode = 500;
    res.end('Internal Server Error');
  }
}).listen(3000);
const http = require('node:http');

http.createServer(async (req, res) => {
  try {
    const data = await fetch('https://example.com/api', { signal: req.signal });
    res.end(JSON.stringify(await data.json()));
  } catch (err) {
    if (err.name === 'AbortError') return;
    res.statusCode = 500;
    res.end('Internal Server Error');
  }
}).listen(3000);
P

message.socket

History

The net.Socket object associated with the connection.

With HTTPS support, use request.socket.getPeerCertificate() to obtain the client's authentication details.

This property is guaranteed to be an instance of the net.Socket class, a subclass of stream.Duplex, unless the user specified a socket type other than net.Socket or internally nulled.

P

message.statusCode

History
Type:number

Only valid for response obtained from http.ClientRequest.

The 3-digit HTTP response status code. E.G. 404.

P

message.statusMessage

History
Type:string

Only valid for response obtained from http.ClientRequest.

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

P

message.trailers

History
Type:Object

The request/response trailers object. Only populated at the 'end' event.

P

message.trailersDistinct

History
Type:Object

Similar to message.trailers, but there is no join logic and the values are always arrays of strings, even for headers received just once. Only populated at the 'end' event.

P

message.url

History
Type:string

Only valid for request obtained from http.Server.

Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:

GET /status?name=ryan HTTP/1.1
Accept: text/plain

To parse the URL into its parts:

When request.url is '/status?name=ryan' and process.env.HOST is undefined:

$ node
> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
URL {
  href: 'http://localhost/status?name=ryan',
  origin: 'http://localhost',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost',
  hostname: 'localhost',
  port: '',
  pathname: '/status',
  search: '?name=ryan',
  searchParams: URLSearchParams { 'name' => 'ryan' },
  hash: ''
}

Ensure that you set process.env.HOST to the server's host name, or consider replacing this part entirely. If using req.headers.host, ensure proper validation is used, as clients may specify a custom Host header.