Explain it simply
Explain it simply
Picture a web server as a shop assistant at a counter. A customer (the browser) hands over a slip saying "GET /about, please", and the assistant reads it and hands back a reply. The reply starts with a status such as "200 OK" or "404 Not Found" and labels (headers) such as "this is HTML", followed by the actual content (the body).
Node's http module gives you that counter. All you write is one function that says what to do each time a slip arrives. Frameworks such as Express use this same module underneath, so everything you understand here carries straight into the next lessons.
Problem → Why → Solution
The problem: the browser just keeps spinning
On a first server it is common to see the browser spinner turn forever on some URLs, or to watch the server crash with ERR_HTTP_HEADERS_SENT. In the code below, the /about branch never calls res.end(), so that response never finishes, and URLs that match no if get no answer at all. Requesting / finishes the response and then tries to set a header afterwards, which throws.
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/') {
res.end('Home');
}
if (req.url === '/about') {
res.write('About'); // no res.end(): the browser waits forever
}
// no fallback: /anything-else also hangs instead of returning 404
res.setHeader('X-App', 'demo'); // after '/' ended: ERR_HTTP_HEADERS_SENT
}).listen(3000);Why does this happen?
The http module treats a response as a stream. Headers go out first, the body follows, and only res.end() tells the client "that's everything". So every request must reach res.end() exactly once, and headers must be set before any body is sent. Writing the routes as one if / else if / else chain gives every path exactly one answer.
Core concept: one request, one handler call
http.createServer(handler) creates a server object and calls handler(req, res) every time a request arrives. A server can be handling hundreds of requests at once, so the handler runs many times, and each request gets its own fresh req and res pair. The server only starts listening when you call server.listen(port), and server.close() stops it accepting new requests.
req (an IncomingMessage) describes what the client sent. req.method is an uppercase string such as 'GET' or 'POST', and req.url holds only the path plus query string, without the host: for example '/search?q=node'. To read the query, build new URL(req.url, 'http://localhost') and call searchParams.get('q'). req.headers is an object whose keys are the lowercase header names.
res (a ServerResponse) is the reply you are building. res.writeHead(status, headers) sets the status code and headers in one call, and res.end(body) sends the body and closes the response. You can also set res.statusCode = 404 and call res.setHeader() separately. Content-Type tells the browser how to interpret the body, so send 'text/html; charset=utf-8' for HTML and 'application/json' for JSON; without the charset, UTF-8 text such as Myanmar script can show up garbled.
| Status | When to use it |
|---|---|
| 200 OK | The request worked and there is a body |
| 201 Created | A POST created something new |
| 400 Bad Request | The client sent invalid data |
| 404 Not Found | Nothing lives at this URL |
| 405 Method Not Allowed | The URL exists but not for this method |
| 500 Internal Server Error | Something broke on the server side |
Passing 0 as the port asks the operating system to pick any free port, which you then read back from server.address().port. Tests, and the examples in this lesson, use this trick to avoid an EADDRINUSE error when some other program already holds port 3000.
- Client sends a method and a URL
- Handler checks req.method / req.url
- writeHead() sets status and headers
- end() sends the body and finishes
Every path must reach res.end() exactly once: never and the client waits forever, twice and Node throws.
General pattern
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'METHOD' && req.url === '/path') {
res.writeHead(STATUS, { 'Content-Type': 'type' });
res.end(body);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});
server.listen(PORT, () => { /* ready */ });One handler checks the method and path, and every branch calls writeHead() and end() once. The final else answers anything that matched no route with a 404.
Example: a three-route server tested with fetch
The server offers an HTML home page, a JSON status endpoint and a 404 fallback. So you do not need a browser, the listen callback sends three requests with Node 22's built-in fetch(), prints the status, Content-Type and body of each, then closes the server. Once the server is closed, the process exits on its own.
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('<h1>Home Page</h1>');
} else if (req.method === 'GET' && req.url === '/api/status') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, uptime: 'fine' }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Not found: ${req.method} ${req.url}`);
}
});
// Port 0 = "any free port"; then talk to the server with fetch
server.listen(0, async () => {
const { port } = server.address();
for (const path of ['/', '/api/status', '/missing']) {
const res = await fetch(`http://localhost:${port}${path}`);
const type = res.headers.get('content-type');
console.log(`${path} -> ${res.status} [${type}] ${await res.text()}`);
}
server.close(() => console.log('server closed'));
});Code breakdown
- The handler
const server = http.createServer((req, res) => {This arrow function runs once per incoming request; the example sends three requests, so it runs three times.
- Routing
} else if (req.method === 'GET' && req.url === '/api/status') {It checks both the method and the URL, so a POST /api/status would fall through to the 404 branch.
- Status + headers
res.writeHead(200, { 'Content-Type': 'application/json' });Status and headers are set in one go, before the body. The body must be a string or Buffer, hence JSON.stringify() on the next line.
- Fallback
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });Because of the else branch, every URL gets an answer and no client is left waiting.
- Port 0 and fetch
const { port } = server.address();It reads the port the OS picked to build the fetch URLs. The number changes between runs, so it is never printed, which keeps the output identical every time.
- Shutting down
server.close(() => console.log('server closed'));Stops accepting new requests and calls back once open connections are closed, which lets the Node process exit by itself.
/ -> 200 [text/html; charset=utf-8] <h1>Home Page</h1>
/api/status -> 200 [application/json] {"ok":true,"uptime":"fine"}
/missing -> 404 [text/plain; charset=utf-8] Not found: GET /missing
server closedReading a request body
When a POST sends data such as JSON, there is no req.body: req itself is a readable stream and the data arrives in chunks. You collect the chunks with for await, join them and call JSON.parse(). The helper below is tested with a fake stream from Readable.from(), so it runs without a server. In a real server, wrap the parse in try/catch and answer 400 when the JSON is invalid. Express's express.json() does exactly this work for you.
import { Readable } from 'node:stream';
async function readJson(req) {
const chunks = [];
for await (const chunk of req) chunks.push(Buffer.from(chunk));
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}
// A stand-in for req: the body arrives in two chunks
const fakeReq = Readable.from(['{"name":"Ay', 'e","age":21}']);
console.log(await readJson(fakeReq));In real projects
Where this shows up in real projects
Most production apps do not write raw http handlers; they use a framework such as Express or Fastify. Every one of those still calls http.createServer() underneath and extends req and res. When you debug a "headers already sent" error, a request that times out or a wrong Content-Type, understanding this layer is what lets you find the cause quickly.
Some code does use raw http directly: a worker process that only needs a /healthz endpoint for Kubernetes, a small script that receives GitHub webhooks, or a CLI's local preview server that should not pull in dependencies. Integration tests follow the same recipe as this lesson: start the server on port 0, call it with fetch, then close() it.
Common mistakes
Common mistakes
1. Forgetting res.end() in one branch
res.write() sends part of the body but does not finish the response. Without end(), the browser keeps loading and the server prints no error at all. Check that every branch of your if/else chain ends with end().
2. Setting a header after the body
As soon as res.end() or the first res.write() runs, the headers are already on the wire, so a later setHeader() throws "ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client". Set headers and status early in the handler.
3. Comparing a URL that has a query string
A request for /search?q=node makes req.url === '/search' false, so it gets a 404. Compare new URL(req.url, 'http://localhost').pathname instead and read the query from searchParams.
Best practices
Best practices
- Put JSON responses behind one helper such as sendJson(), so nobody forgets the Content-Type or the stringify.
- Answer unknown routes with 404 and wrong methods with 405 plus an Allow header; clients can debug that.
- Never do slow synchronous work (huge loops, readFileSync) in a handler; every other request waits behind it.
Mini challenge
Mini challenge: a JSON greeting API
Using only the http module, write a tiny JSON API with a /api/greet endpoint and test it by sending four requests with fetch.
- A sendJson(res, status, data) helper sends the status, Content-Type: application/json and the body
- GET /api/greet?name=Aye returns 200 and {"message":"Hello, Aye!"}; without a name it uses "stranger"
- POST /api/greet returns 405 with an Allow: GET header
- Any other URL gets a JSON 404, and the server is closed after the tests
import http from 'node:http';
function sendJson(res, status, data, extraHeaders = {}) {
// TODO: writeHead with Content-Type application/json + extraHeaders
// TODO: end with the JSON string
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
// TODO: /api/greet + GET -> 200 { message: 'Hello, <name>!' }
// TODO: /api/greet + other method -> 405 with an Allow header
// TODO: anything else -> 404 { error: 'Not found' }
});
server.listen(0, async () => {
// TODO: fetch the four cases, print "<status> <body>", then close
});Expected: Expected output: 200 {"message":"Hello, Aye!"} 200 {"message":"Hello, stranger!"} 405 {"error":"Use GET"} allow=GET 404 {"error":"Not found"}
Show hint
Use url.pathname for routing and url.searchParams.get('name') ?? 'stranger' for the name. Passing method: 'POST' to fetch sends a POST, and res.headers.get('allow') reads the Allow header.
Show solution
import http from 'node:http';
function sendJson(res, status, data, extraHeaders = {}) {
res.writeHead(status, { 'Content-Type': 'application/json', ...extraHeaders });
res.end(JSON.stringify(data));
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/api/greet') {
if (req.method !== 'GET') {
return sendJson(res, 405, { error: 'Use GET' }, { Allow: 'GET' });
}
const name = url.searchParams.get('name') ?? 'stranger';
return sendJson(res, 200, { message: `Hello, ${name}!` });
}
sendJson(res, 404, { error: 'Not found' });
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const cases = [
['GET', '/api/greet?name=Aye'],
['GET', '/api/greet'],
['POST', '/api/greet'],
['GET', '/nope'],
];
for (const [method, path] of cases) {
const res = await fetch(base + path, { method });
const allow = res.headers.get('allow');
console.log(res.status, await res.text(), allow ? `allow=${allow}` : '');
}
server.close();
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- http.createServer(handler) calls handler(req, res) once per request.
- Route on req.method and req.url (path plus query) and fall back to a 404.
- Set the status and Content-Type with writeHead() first, then call end() exactly once on every path.
- Listen on port 0, test with fetch, stop with server.close(): the standard recipe for tests.
HTTP — Node.js