AI Hints
Home›JavaScript Tutorial›Node and npm
JavaScript · Lesson 108 of 138

A Web Server

Handling requests.

⏱ 2 min read▶ Video at 2:09:49🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

A Web Server
From the video: A Web Server
  • 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.

app.mjsjavascript
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();
Output
/ 200 Welcome!
/time 200 {"year":2026,"ok":true}
/nope 404 Not found

Frameworks

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.

keyvalue
createServer(fn)runs per request
req.urlthe path
res.end(body)send the response
Expressa 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
Next up: Sets and Maps — better collections