Node.js can create a web server with the built-in http module — no extra software needed.
createServer
http.createServer((req, res) => { ... }) runs your function for every request.
req.method— GET, POST, ...req.url— the path and query, e.g./users?page=2req.headers— request headers
Sending a response
res.statusCode = 200orres.writeHead(200, { 'Content-Type': 'text/html' })res.setHeader(name, value)res.end(body)— send and finish. Always end the response, or the browser keeps waiting.
Parsing the URL
new URL(req.url, 'http://localhost') gives pathname and searchParams.get('page').
Reading a POST body
The body arrives in chunks: collect them with for await (const chunk of req), then JSON.parse.
Start listening
server.listen(3000) → open http://localhost:3000.
Writing routing by hand gets long quickly — that is why most apps use Express, covered later.
Example
import http from 'node:http';
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && url.pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end('<h1>Home page</h1>');
}
if (req.method === 'GET' && url.pathname === '/api/hello') {
const name = url.searchParams.get('name') ?? 'Guest';
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ message: `Hello, ${name}` }));
}
if (req.method === 'POST' && url.pathname === '/api/echo') {
let body = '';
for await (const chunk of req) body += chunk;
res.writeHead(201, { 'Content-Type': 'application/json' });
return res.end(body);
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
});
server.listen(3000, () => console.log('Server running at http://localhost:3000'));
/ shows a heading, /api/hello?name=Asha returns {"message":"Hello, Asha"}, POST /api/echo returns the body you sent, and any other URL returns 404 Not found.