← Learning Hub
Intermediate

A Web Server with node:http

Node can be a web server by itself, with the built-in node:http module. Every request calls your function with req (what the browser asked) and res (what you send back).

Every website you visit is answered by a server: it receives a request (method, address, headers) and sends back a response (status code, headers, body). Building one with Node's http module shows you exactly what frameworks like Express do for you.

Example
import http from "node:http";

const products = [
  { id: 1, name: "Kettle", price: 1299 },
  { id: 2, name: "Iron", price: 899 },
];

const server = http.createServer((req, res) => {
  if (req.method === "GET" && req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Welcome to the shop API");
  } else if (req.method === "GET" && req.url === "/products") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(products));
  } else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "Not found" }));
  }
});

server.listen(3000, () => console.log("Server running at http://localhost:3000"));

// Start it with: node server.mjs
// Server running at http://localhost:3000
// Then try these requests (real replies):
// GET /
//   -> 200 Welcome to the shop API
// GET /products
//   -> 200 [{"id":1,"name":"Kettle","price":1299},{"id":2,"name":"Iron","price":899}]
// GET /cart
//   -> 404 {"error":"Not found"}

Open http://localhost:3000/products in your browser, or use curl in a terminal. Stop the server with Ctrl+C.

Status codes you'll use

  • 200 OK, 201 Created
  • 400 Bad request (wrong input), 401 Not signed in, 403 Not allowed, 404 Not found
  • 500 Server error (a bug on your side)
Handling every URL and method by hand gets messy fast. That's why most people use Express - next lesson.
Key points
  • A server receives requests and sends responses.
  • Status codes tell the client what happened.
  • Frameworks like Express simplify routing.

📝 Test yourself

1. What is req in a request handler?
2. Which status code means 'not found'?
3. Fill in the method that starts the server on a port:
server.(3000);