TExcelTAD
Home › Node.js › Node.js HTTP Module

Node.js HTTP Module

The web runs on HTTP: a client sends a request (a method, a URL, headers and maybe a body), and a server answers with a response (a status code, headers and a body). The built-in node:http module lets Node.js play both roles. Frameworks like Express and Fastify are built on top of it, so understanding it makes every framework easier to learn.

This lesson gives an overview of the module. The Node.js Web section later builds real servers, routing and REST APIs step by step.

A minimal server

http.createServer() takes a request listener — a function that Node calls once for every incoming request with two objects:

Object Class You use it to…
req http.IncomingMessage read the method, URL, headers and body
res http.ServerResponse set the status and headers, then write the body
node
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Hello from Node.js!\n');
});

server.listen(3000, () => console.log('Listening on http://localhost:3000'));

Save it as server.js, run it, and open the address in a browser — or use curl:

bash · try it yourself
node server.js &
curl -i http://localhost:3000
Listening on http://localhost:3000
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Fri, 16 Oct 2026 09:00:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 20

Hello from Node.js!

(Simulated session.) The server keeps running until you press Ctrl+C — it's waiting for more requests.

Server and client in one script

The playground below starts a server on port 0, which tells the operating system to pick any free port. It then sends a request to itself with the global fetch() function, prints the answer and closes the server so the program can end.

node · try it yourself
const http = require('node:http');

const server = http.createServer((req, res) => {
  console.log('server got:', req.method, req.url);
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('X-Powered-By', 'ExcelTAD');
  res.end('Hi, client!');
});

server.listen(0, async () => {
  const { port } = server.address();
  const response = await fetch(`http://localhost:${port}/hello?name=ana`);

  console.log('status:', response.status, response.statusText);
  console.log('type:', response.headers.get('content-type'));
  console.log('custom:', response.headers.get('x-powered-by'));
  console.log('body:', await response.text());

  server.close();
});
server got: GET /hello?name=ana
status: 200 OK
type: text/plain
custom: ExcelTAD
body: Hi, client!

Reading the request

req.method and req.url tell you what the client wants; req.headers is an object whose keys are always lower-case. The body arrives as a stream of chunks — with modern Node you can collect it with for await:

node · try it yourself
const http = require('node:http');

const server = http.createServer(async (req, res) => {
  let body = '';
  for await (const chunk of req) body += chunk;

  const info = {
    method: req.method,
    path: new URL(req.url, 'http://localhost').pathname,
    contentType: req.headers['content-type'],
    body: JSON.parse(body),
  };
  res.writeHead(201, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(info));
});

server.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/orders`;
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ item: 'coffee', qty: 2 }),
  });
  console.log(response.status);
  console.log(await response.json());
  server.close();
});
201
{
  method: 'POST',
  path: '/orders',
  contentType: 'application/json',
  body: { item: 'coffee', qty: 2 }
}

Writing the response

Method Purpose
res.statusCode = 404 set the status code
res.setHeader(name, value) set one header
res.writeHead(status, headers) set status and headers at once
res.write(chunk) send part of the body
res.end([chunk]) finish the response (always call it)

Note: If you forget res.end(), the client waits until it times out. Headers must be set before the first write() — afterwards they have already been sent.

Status codes

http.STATUS_CODES maps every code to its standard phrase, and http.METHODS lists the methods Node understands:

node · try it yourself
const http = require('node:http');

for (const code of [200, 201, 204, 301, 400, 401, 404, 500]) {
  console.log(code, http.STATUS_CODES[code]);
}
console.log(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].every((m) => http.METHODS.includes(m)));
200 OK
201 Created
204 No Content
301 Moved Permanently
400 Bad Request
401 Unauthorized
404 Not Found
500 Internal Server Error
true

The client side

Node's HTTP client used to be http.request() / http.get(), which are callback- and stream-based. Since Node 18, the global fetch() (the same API as in browsers) is the simplest choice for most requests and is covered in its own lesson. node:https works like node:http but for TLS-encrypted servers.

Test yourself

What does server.listen(0) do?

  1. Listens on port 0, which browsers block
  2. Asks the operating system for any free port
  3. Starts the server without a port
  4. Throws an error

How do you read the Content-Type request header?

  1. req.headers['Content-Type']
  2. req.headers['content-type']
  3. req.contentType
  4. req.getHeader('Content-Type') only

What happens if a request handler never calls res.end()?

  1. Node calls it automatically
  2. The client keeps waiting for the response
  3. The server crashes
  4. A 500 error is sent