BuildBot

Node Essentials

An HTTP server

Lesson 5 of 5

What you'll learn

  • Create an HTTP server with http.createServer
  • Route by method and path to the right handler
  • Return JSON with the correct status and headers

An HTTP server is, conceptually, a single function: a request comes in, you produce a response. Node's http module hands you that request/response pair on every connection.

import { createServer } from "node:http";

const server = createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ hello: "world" }));
});

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

Routing is a lookup

Real apps serve many endpoints, so you route: combine the method and path into a key, look up a handler, and run it. A missing key is a 404.

const routes = {
  "GET /users": (req) => ({ status: 200, body: { users: [] } }),
  "POST /users": (req) => ({ status: 201, body: { created: true } }),
};

function handle(method, path) {
  const handler = routes[method + " " + path];
  if (!handler) return { status: 404, body: { error: "Not Found" } };
  return handler();
}

Always set the status and type

Forgetting Content-Type: application/json makes clients guess at your payload, and a silent default 200 hides real failures. Set both explicitly on every response.

The challenge builds that router as a pure function — method plus path in, a response object out, with a 404 fallback.

A request router

Run it. The router maps method+path to a handler and returns a response object, falling back to 404 for unknown routes.

Loading editor…

That is the core of every Node backend: route a request to a handler, return a response.

Sign in to save your progress across devices.