A Web Server
Handling requests.
Node's most famous job is running web servers. A server waits for requests, and sends back responses. With the built in h t t p module, a simple server takes just a few lines.

- Node runs servers
- Requests in, responses out
- The http module
Routes and JSON
Create server takes a function that runs for every request. We look at the URL, and choose what to send. The root sends a welcome message. Slash time sends JSON. Anything else is a four oh four. To test it, our script fetches three paths from itself, then closes the server. Run it.
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url === "/") return res.end("Welcome!");
if (req.url === "/time") {
res.setHeader("Content-Type", "application/json");
return res.end(JSON.stringify({ year: 2026, ok: true }));
}
res.statusCode = 404;
res.end("Not found");
});
server.listen(3002);
for (const p of ["/", "/time", "/nope"]) {
const r = await fetch("http://localhost:3002" + p);
console.log(p, r.status, await r.text());
}
server.close();/ 200 Welcome!
/time 200 {"year":2026,"ok":true}
/nope 404 Not foundFrameworks
For real apps, most people use a framework on top of the h t t p module. Express is the most popular. It makes routes, JSON, and reading request bodies much simpler. But underneath, it's exactly this: a function that gets a request, and sends a response.
| key | value |
|---|---|
| createServer(fn) | runs per request |
| req.url | the path |
| res.end(body) | send the response |
| Express | a popular framework |
Summary
The h t t p module creates a server that reads each request and sends a response. Frameworks like Express build on it. Next, two useful collections, sets and maps.
Key takeaways- http.createServer
- Check req.url
- statusCode, res.end