Code Reference

HTTP Server (node:http)

Node.js · Reference cheat sheet

HTTP Server (node:http)

Node.js · Reference cheat sheet


📋 Overview

node:http (and node:https) provide low-level servers and clients. Frameworks like Express/Fastify wrap these primitives.

🔧 Core concepts

APIRole
http.createServerCreate server
IncomingMessage (req)Request stream + headers
ServerResponse (res)Writable response
server.listenBind port/host
http.request / fetchOutbound HTTP
Header tipDetail
Set before bodyCall writeHead or setHeader early
Content-TypeRequired for correct client parsing
Keep-aliveDefault in modern Node

💡 Examples

Plain text server:

import http from "node:http";

http
  .createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ path: req.url }));
  })
  .listen(9000, "0.0.0.0");

Read POST body:

async function readBody(req) {
  const chunks = [];
  for await (const c of req) chunks.push(c);
  return Buffer.concat(chunks).toString("utf8");
}

Global fetch (Node 18+):

const res = await fetch("https://example.com");
const text = await res.text();

⚠️ Pitfalls

  • Forgetting to end() the response leaves the client hanging.
  • Unbounded body reads enable memory DoS — enforce size limits.
  • req.url includes query string; parse with URL + host header carefully.

On this page