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.
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");
});{"type":"module"}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 runningHTTP/1.1 200 OK
Content-Type: application/json
{"AE":5,"SA":15,"OM":5,"BH":10}{"amount":200,"country":"SA","rate":15,"total":230}HTTP/1.1 400 Bad Request
Content-Type: application/json
{"error":"Send ?amount=number&country=AE|SA|OM|BH"}HTTP/1.1 404 Not Found
Content-Type: application/json
{"error":"Not found"}Listening on http://localhost:3000
GET /
GET /api/rates
GET /api/vat
GET /api/vat
GET /api/ordersRun 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
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.
- Node.js docs: HTTP
- Node.js docs: URL
- Node.js learn: Don’t block the event loop
- MDN: HTTP response status codes
Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.