HTTP Server Basics
Node.js was built for network servers, and you need nothing but the built-in node:http module to write one. In this lesson you'll create a server, read the incoming request, and send back status codes, headers and a body. Every framework (Express, Fastify, Koa…) is built on these same objects.
The smallest server
// server.mjs
import http from 'node:http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Hello from Node!\n');
});
server.listen(3000, () => console.log('Listening on http://localhost:3000'));node server.mjs &
curl -i http://localhost:3000Listening on http://localhost:3000
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Fri, 16 Oct 2026 09:00:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 17
Hello from Node!
The callback runs once for every request. A server keeps running until you stop it (Ctrl+C).
Testing a server from the same script
In the playgrounds below, the server listens on port 0, which lets the operating system pick any free port. The script then calls itself with fetch, prints the response and closes the server so the program can exit:
const http = require('node:http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`You asked for ${req.method} ${req.url}`);
});
server.listen(0, async () => {
const { port } = server.address();
const res = await fetch(`http://localhost:${port}/hello?x=1`);
console.log(res.status, res.statusText);
console.log(res.headers.get('content-type'));
console.log(await res.text());
server.close();
});200 OK
text/plain
You asked for GET /hello?x=1
The request object (req)
req is an http.IncomingMessage, a readable stream with metadata:
| Property | Example |
|---|---|
req.method |
'GET', 'POST', 'DELETE' |
req.url |
'/users/7?sort=name' (path + query, no host) |
req.headers |
object with lower-case names: req.headers['user-agent'] |
req.httpVersion |
'1.1' |
| the stream itself | the request body, read in chunks |
To get a full URL object with parsed query parameters, combine it with the Host header:
const url = new URL(req.url, `http://${req.headers.host}`);
url.pathname; // '/users/7'
url.searchParams.get('sort'); // 'name'The response object (res)
| Method | Purpose |
|---|---|
res.statusCode = 404 |
set the status (default 200) |
res.setHeader(name, value) |
set one header |
res.writeHead(status, headers) |
status + headers in one call |
res.write(chunk) |
send part of the body |
res.end([chunk]) |
finish the response — always call it |
Note: Forgetting
res.end()leaves the client waiting until it times out. Every code path in your handler must end the response.
Reading a request body
A POST body arrives as a stream of chunks. The easiest modern way to collect it is for await over req:
const http = require('node:http');
const server = http.createServer(async (req, res) => {
if (req.method !== 'POST') {
res.statusCode = 405;
res.setHeader('Allow', 'POST');
return res.end('Only POST, please\n');
}
let body = '';
for await (const chunk of req) body += chunk;
res.setHeader('Content-Type', 'text/plain');
res.end(`Received ${body.length} characters: ${body.toUpperCase()}`);
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const r1 = await fetch(base);
console.log(r1.status, r1.headers.get('allow'), (await r1.text()).trim());
const r2 = await fetch(base, { method: 'POST', body: 'hello server' });
console.log(r2.status, await r2.text());
server.close();
});405 POST Only POST, please
200 Received 12 characters: HELLO SERVER
Common status codes
| Code | Meaning | Typical use |
|---|---|---|
| 200 | OK | successful GET |
| 201 | Created | a POST created a resource |
| 204 | No Content | successful DELETE |
| 301 / 302 | Redirect | send a Location header |
| 400 | Bad Request | invalid input |
| 404 | Not Found | unknown route |
| 405 | Method Not Allowed | e.g. PUT on a read-only URL |
| 500 | Internal Server Error | an exception in your code |
Sending HTML and redirects
const http = require('node:http');
const server = http.createServer((req, res) => {
if (req.url === '/old-page') {
res.writeHead(301, { Location: '/new-page' });
return res.end();
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`<h1>You are on ${req.url}</h1>`);
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const noFollow = await fetch(`${base}/old-page`, { redirect: 'manual' });
console.log(noFollow.status, noFollow.headers.get('location'));
const followed = await fetch(`${base}/old-page`);
console.log(followed.status, followed.redirected, await followed.text());
server.close();
});301 /new-page
200 true <h1>You are on /new-page</h1>
Tip: Run your server with
node --watch server.mjsduring development: Node restarts it automatically whenever you save a file.
Test yourself
How often is the callback passed to http.createServer() called?
- Once, at start-up
- Once per incoming request
- Once per second
- Only for POST requests
What happens if a handler never calls res.end()?
- Node calls it automatically
- The client keeps waiting for the response
- The server crashes
- A 404 is sent
What does server.listen(0) do?
- Listens on port 80
- Lets the operating system choose a free port
- Disables the server
- Listens on all ports