Read request metadata and body
HTTP server request handling
Node.js · Class
http.IncomingMessage is the readable-stream object Node.js provides for an incoming HTTP request or client response. It exposes HTTP metadata and carries the message body.
IncomingMessage is the readable stream Node.js supplies for an incoming HTTP request or response. It exposes request metadata such as method, URL, headers, and socket information, while also providing response metadata when it represents a client response.
class http.IncomingMessage extends stream.ReadableAn instance supplied by Node.js to HTTP server request and client response events; it is a readable stream carrying the message payload.
import http from 'node:http';
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify({
method: request.method,
url: request.url,
body: Buffer.concat(chunks).toString()
}));
});
server.listen(3000);Creates an HTTP server that consumes the IncomingMessage request stream and returns selected request metadata and body.
HTTP server request handling
HTTP client response handling
Protocol diagnostics
IncomingMessage is created by an HTTP server or client request and passed to the request or response event. It extends stream.Readable, so request or response data is consumed as a stream.
Follow-up: How would you process a large request body? Consume the readable incrementally, avoiding accumulation of the entire body in memory.
For server requests, method and url describe the HTTP request, while headers provides the parsed request headers. For client responses, statusCode and statusMessage expose the response status information.
Follow-up: Why should header handling account for repeated fields? Node.js may represent some header values as arrays, so code should not assume every value is a string.
The complete property indicates whether the complete HTTP message has been received. The rawHeaders property preserves the headers as they were received, rather than presenting only the normalized headers object.
Follow-up: When might rawHeaders matter? It is useful when preserving original header spelling or repeated header entries during diagnostics or protocol-sensitive processing.
http.Serverhttp.ClientRequeststream.Readablehttp.ServerResponsemessage.completemessage.headersmessage.rawHeaders