Skip to content

Build a Web Server with node:http: Routes, JSON, Status Codes and Request Bodies

NeedMyTools Academy

Sign in free to read the full lesson

Sign in or create a free account

Free forever. No card, no paywall.

Every web framework for Node.js, Express included, sits on top of one built in module: node:http. Writing a small server with it once shows you what a framework does for you, and what it cannot hide. In this lesson you build a VAT API for Gulf prices with no packages at all. It answers GET requests with text and JSON, reads numbers from the query string, accepts new orders as a JSON body with POST, and returns honest status codes such as 201, 400 and 404. You will also see the crash Node.js printed when the port was already in use, and a timing test that shows how one slow request froze a fast one. Recorded with Node.js 22.23.4 and curl.

Quick answer

Import createServer from "node:http" and pass it a function that receives req and res. Read req.method and req.url (parse it with new URL(req.url, "http://localhost") to get the path and query), then answer with res.writeHead(status, headers) and res.end(body). Call server.listen(3000) to start. For JSON, send JSON.stringify(data) with Content-Type: application/json. A request body arrives in chunks, so collect it with for await (const chunk of req) before parsing.

40 min read and practice · Content checked on 28 November 2026

In this lesson you will

  • Start an HTTP server and answer different paths and methods
  • Return JSON with the right Content-Type and status code
  • Read query strings and JSON request bodies safely
  • Explain why blocking code slows every visitor, not just one

Requests in, responses out

An HTTP server is a program that waits on a port for requests. Each request has a method such as GET or POST, a path such as /api/rates, headers and sometimes a body. Your job is to send back exactly one response: a status code, headers and a body. createServer calls your function once per request with two objects. req describes what arrived, and res is how you answer. Nothing is sent until you call res.end(), and if you never call it the browser or curl waits until it gives up.

req.url is only the path and query, such as /api/vat?amount=200&country=SA, so the server builds a full URL object with a dummy origin to read pathname and searchParams. Routing is then plain if checks on method and path. Every branch ends with return after res.end(), so a request never falls through to the 404 at the bottom. The curl -i flag prints the status line and headers, which is how you check that the JSON really went out as application/json and not as text.

Status codes are part of the answer, not decoration. 200 means it worked, 400 means the client sent something wrong, and 404 means there is nothing at that path. Look at the amount=abc request: Number("abc") is NaN, so the server refused with 400 and a message that says what to send, instead of answering with a total of null. A client, or another developer reading your logs, can act on that without guessing.

Example: A VAT API with three routes
server.js
import { createServer } from "node:http";

const RATES = { AE: 5, SA: 15, OM: 5, BH: 10 };

const server = createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  console.log(req.method, url.pathname);

  if (req.method === "GET" && url.pathname === "/") {
    res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
    res.end("Souq API is running\n");
    return;
  }

  if (req.method === "GET" && url.pathname === "/api/rates") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(RATES));
    return;
  }

  if (req.method === "GET" && url.pathname === "/api/vat") {
    const amount = Number(url.searchParams.get("amount"));
    const country = url.searchParams.get("country") ?? "AE";
    const rate = RATES[country];
    if (Number.isNaN(amount) || rate === undefined) {
      res.writeHead(400, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "Send ?amount=number&country=AE|SA|OM|BH" }));
      return;
    }
    const total = Math.round(amount * (100 + rate)) / 100;
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ amount, country, rate, total }));
    return;
  }

  res.writeHead(404, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ error: "Not found" }));
});

server.listen(3000, () => {
  console.log("Listening on http://localhost:3000");
});
package.json
{"type":"module"}
Real output: terminal 2, curl -i http://localhost:3000/
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Sat, 28 Nov 2026 05:32:12 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

Souq API is running
Real output: terminal 2, curl -i http://localhost:3000/api/rates (Date and connection headers removed)
HTTP/1.1 200 OK
Content-Type: application/json

{"AE":5,"SA":15,"OM":5,"BH":10}
Real output: terminal 2, curl "http://localhost:3000/api/vat?amount=200&country=SA"
{"amount":200,"country":"SA","rate":15,"total":230}
Real output: terminal 2, curl -i "http://localhost:3000/api/vat?amount=abc" (Date and connection headers removed)
HTTP/1.1 400 Bad Request
Content-Type: application/json

{"error":"Send ?amount=number&country=AE|SA|OM|BH"}
Real output: terminal 2, curl -i http://localhost:3000/api/orders (headers trimmed)
HTTP/1.1 404 Not Found
Content-Type: application/json

{"error":"Not found"}
Real output: terminal 1, where node server.js runs
Listening on http://localhost:3000
GET /
GET /api/rates
GET /api/vat
GET /api/vat
GET /api/orders

Run the server in one terminal and curl in a second one. The server keeps running until you press Ctrl+C. Notice that the log shows only the path: the query string is in url.search, not in pathname.

Sign in free to read the full lesson

You are reading the free preview. Create a free account (it takes one minute, no password) to unlock the rest of this lesson and track your progress.

Unlocks after sign-in:

  • 3 more sections with live code examples
  • Common mistakes to avoid
  • Hands-on coding exercise with automatic checks
  • Practice quiz and the graded lesson test
Sign in or create a free account

Free forever. No card, no paywall.

Questions people ask

Do I need Express to build a Node.js API?

No. node:http is enough for small services, health checks and learning, as this lesson shows. Express and similar frameworks save time once you have many routes, middleware and error handling, which is the next lesson.

How do I stop a Node.js server?

Press Ctrl+C in the terminal where it runs. In code, server.close() stops accepting new connections and lets open requests finish, which is what you do before a planned restart.

Why does my server restart need Ctrl+C every time I edit?

Node.js loads your code once at start. Run node --watch server.js and it restarts by itself whenever a file it loaded changes, which has been stable since Node.js 22.

Can a Node.js server serve HTML pages too?

Yes. Send the HTML string with Content-Type: text/html; charset=utf-8. For many pages and static files, a framework or a static host is easier than writing the file serving yourself, which has security traps such as paths with .. in them.

What is the difference between 401, 403 and 404?

401 means the request has no valid credentials, 403 means the credentials are known but not allowed to do this, and 404 means nothing exists at that path. Some APIs answer 404 instead of 403 to avoid revealing that a private item exists.

Sources

Facts in this lesson were checked against these official pages on 28 November 2026.

Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.