Node.js theorytheory 0/50 · 0%
Networking · easy

16. Creating an HTTP server

The built-in http module, no framework required.

Node ships a full HTTP server in `node:http`. A request handler receives `(req, res)`: `req` is a readable stream describing the incoming request, `res` is a writable stream you use to send a response.

js
import { createServer } from "node:http";

const server = createServer((req, res) => {
  if (req.url === "/health") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ ok: true }));
    return;
  }
  res.writeHead(404);
  res.end("not found");
});

server.listen(3000, () => console.log("listening on :3000"));

Frameworks like Express build convenience on top of this same primitive (routing, middleware, body parsing) — understanding the raw `http` module makes those abstractions much less mysterious.

Check your understanding

  1. 1. What two objects does an http request handler receive?

  2. 2. What must you call to actually send the response body and finish?

  3. 3. What do frameworks like Express add on top of node:http?