Node.js: a web server with the http module

A server with nothing but the built-in `node:http`: `createServer`, the request and response objects, routing by method and URL, reading a JSON body from the stream, status codes and headers, serving static files safely (path traversal) and why frameworks exist.

  • Advanced
  • 25 min
  • 12 questions
  • Lesson 36 of 39

In this lesson you will learn

  • Create a server with http.createServer, use the req and res objects and test it with fetch
  • Route requests by method and path and return the right status code (200, 201, 204, 400, 404, 405, 413, 415)
  • Read a JSON body from the stream with a size limit and protect static files from path traversal

When a browser or fetch calls http://localhost:3000/api/notes, some program has to listen on port 3000, read the request and write an answer. In «Node.js basics» we saw a five-line server that gives the same answer to everything. In this lesson we build a real one with nothing but the built-in node:http module: routes by method and URL, reading a JSON body, correct status codes and headers, safe static files and a small notes API. At the end you will see why frameworks such as Express exist.

createServer: request and response

http.createServer(handler) creates a server; the handler runs for every request and receives two objects. req is a readable stream with req.method, req.url (the path together with the query string, e.g. /hello?name=Aysel) and req.headers (header names in lower case). res is a writable stream: res.statusCode and res.setHeader() prepare the head of the answer, res.write() sends a piece of the body and res.end() finishes the answer. server.listen(3000) starts listening on port 3000.

JavaScript
// hello-server.mjs
import http from 'node:http';

const server = http.createServer((req, res) => {
  console.log(req.method, req.url, req.headers['user-agent']);

  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.setHeader('X-Lesson', 'node-http');
  res.end(`Salam! You asked for ${req.url}\n`);
});

server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

Expected output

Listening on http://localhost:3000
GET /hello?name=Aysel node
The server prints one line for every request and keeps running until you press Ctrl+C.
JavaScript
// hello-client.mjs
const res = await fetch('http://localhost:3000/hello?name=Aysel');

console.log(res.status, res.statusText, res.ok);
console.log(res.headers.get('content-type'));
console.log(res.headers.get('x-lesson'));
console.log(await res.text());

Expected output

200 OK true
text/plain; charset=utf-8
node-http
Salam! You asked for /hello?name=Aysel
Run it in a second terminal while the server is working. fetch in Node.js sends node as its User-Agent. Header names are case-insensitive: res.headers.get('x-lesson') finds X-Lesson.

Sign up free to keep reading

The rest of the lesson, the quiz and your notes open with an Educora account. Signing up takes a minute, and your progress is saved on all your devices.

Routing: method + path

A server usually does different work for GET /api/time and POST /api/notes. The URL arrives as a string, so parse it with new URL(req.url, 'http://localhost'): you get pathname without the query string and searchParams for ?name=Leyla. A simple router is an object whose keys are 'METHOD /path'. If the path exists but the method does not fit, the correct answer is 405 Method Not Allowed with an Allow header; if the path does not exist at all, 404 Not Found.

JavaScript
// router-server.mjs
import http from 'node:http';

function send(res, status, data) {
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
  res.end(JSON.stringify(data));
}

const routes = {
  'GET /api/greet': (req, res, url) =>
    send(res, 200, { text: `Salam, ${url.searchParams.get('name') ?? 'friend'}!` }),
  'GET /api/time': (req, res) => send(res, 200, { city: 'Baku', utcOffset: '+04:00' }),
};

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const handler = routes[`${req.method} ${url.pathname}`];
  if (handler) return handler(req, res, url);

  const allowed = Object.keys(routes)
    .filter((key) => key.endsWith(` ${url.pathname}`))
    .map((key) => key.split(' ')[0]);
  if (allowed.length) {
    res.setHeader('Allow', allowed.join(', '));
    return send(res, 405, { error: `${req.method} is not allowed here` });
  }
  send(res, 404, { error: `Nothing at ${url.pathname}` });
});

server.listen(3000, () => console.log('Listening on http://localhost:3000'));
JavaScript
// router-client.mjs
const base = 'http://localhost:3000';
const requests = [
  ['GET', '/api/greet?name=Leyla'],
  ['GET', '/api/greet'],
  ['GET', '/api/time'],
  ['DELETE', '/api/time'],
  ['GET', '/api/weather'],
];

for (const [method, path] of requests) {
  const res = await fetch(base + path, { method });
  const allow = res.headers.get('allow');
  const body = await res.text();
  console.log(`${method} ${path} → ${res.status} ${body}${allow ? ` (Allow: ${allow})` : ''}`);
}

Expected output

GET /api/greet?name=Leyla → 200 {"text":"Salam, Leyla!"}
GET /api/greet → 200 {"text":"Salam, friend!"}
GET /api/time → 200 {"city":"Baku","utcOffset":"+04:00"}
DELETE /api/time → 405 {"error":"DELETE is not allowed here"} (Allow: GET)
GET /api/weather → 404 {"error":"Nothing at /api/weather"}
url.searchParams.get('name') returns null when the parameter is missing, and ?? replaces it with 'friend'. DELETE on /api/time got 405 because the path exists, while /api/weather got 404 because it does not.
CodeWhenNote
200 OKa successful read or change
201 CreatedPOST created a new resourcethe Location header gives the new address
204 No Contentsuccess without a body (e.g. DELETE)
400 Bad Requestbroken JSON or invalid data
404 Not Foundno such path or resource
405 Method Not Allowedthe path exists, the method does nota header such as Allow: GET
413 Payload Too Largethe body is over the limit
415 Unsupported Media Typethe Content-Type is not the expected one
500 Internal Server Errora bug on the serverdo not show the details to the client

Reading a JSON body

The body of a POST request is not in req.url — it is the req stream itself, and it may arrive in several chunks. So collect the chunks with for await, join them with Buffer.concat (joining Buffers rather than strings keeps multi-byte letters whole) and only then call JSON.parse. Three checks protect the server: the Content-Type must be JSON (415), the body must stay under a limit — otherwise anyone can send gigabytes (413) — and broken JSON must give 400 instead of crashing the server.

JavaScript
// http-utils.mjs
export class HttpError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

export function send(res, status, data) {
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
  res.end(JSON.stringify(data));
}

export async function readJson(req, limit = 10_000) {
  if (!req.headers['content-type']?.startsWith('application/json')) {
    throw new HttpError(415, 'Expected Content-Type: application/json');
  }
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > limit) throw new HttpError(413, `Body is larger than ${limit} bytes`);
    chunks.push(chunk);
  }
  try {
    return JSON.parse(Buffer.concat(chunks).toString('utf8'));
  } catch {
    throw new HttpError(400, 'Body is not valid JSON');
  }
}
HttpError carries a status code: a handler simply writes throw new HttpError(404, …), and one central place turns it into a response. The limit is 10 000 bytes for the demo.

Static files and path traversal

Websites also need files: HTML, CSS, pictures. The naive way is to join the folder and the URL. But a URL can contain ... Browsers and fetch clean /../ out of the address — attackers do not: curl --path-as-is sends it untouched, and %2f is an encoded / that the server decodes itself. The result is a path traversal attack: the server reads files outside the public folder — configuration, passwords, source code.

Dangerous

const file = path.join(ROOT, decodeURIComponent(req.url));
const info = await stat(file).catch(() => null);

Safe

const file = resolveSafe(req.url.split('?')[0]);
const info = file && (await stat(file).catch(() => null));
The left version was tested: curl --path-as-is http://localhost:3000/../secret.txt and curl http://localhost:3000/..%2fsecret.txt both returned the contents of secret.txt, which lies outside public. The right version decodes, joins and then checks that the result is still inside ROOT.
JavaScript
// static-server.mjs
import http from 'node:http';
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import { pipeline } from 'node:stream/promises';
import path from 'node:path';

const ROOT = path.join(import.meta.dirname, 'public');
const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript' };

function resolveSafe(urlPath) {
  let decoded;
  try {
    decoded = decodeURIComponent(urlPath);
  } catch {
    return null;
  }
  const file = path.join(ROOT, decoded === '/' ? 'index.html' : decoded);
  return file.startsWith(ROOT + path.sep) ? file : null;
}

http.createServer(async (req, res) => {
  const file = resolveSafe(req.url.split('?')[0]);
  const info = file && (await stat(file).catch(() => null));
  if (!info?.isFile()) return res.writeHead(404, { 'Content-Type': 'text/plain' }).end('Not found\n');

  const type = TYPES[path.extname(file)] ?? 'application/octet-stream';
  res.writeHead(200, { 'Content-Type': type, 'Content-Length': info.size });
  await pipeline(createReadStream(file), res).catch((error) => console.error('send failed:', error.code));
}).listen(3000, () => console.log('Static files on http://localhost:3000'));
Checking with ROOT + path.sep matters: with just startsWith(ROOT), a folder called public-old would also count as «inside». The file is sent as a stream with pipeline and never loaded into memory as a whole.
Terminal
$ curl http://localhost:3000/
<h1>Salam!</h1>
$ curl http://localhost:3000/css/site.css
h1 { color: teal; }
$ curl --path-as-is http://localhost:3000/../secret.txt
Not found
$ curl http://localhost:3000/..%2fsecret.txt
Not found
$ curl http://localhost:3000/%E0%A4%A
Not found
$ curl -o /dev/null -w "%{http_code} %{content_type}\n" http://localhost:3000/index.html
200 text/html; charset=utf-8
The same attacks now get Not found. Broken percent-encoding (%E0%A4%A) makes decodeURIComponent throw — that is caught too. The Content-Type comes from the file extension; unknown types get application/octet-stream.

Mini project: a notes API on plain http

Now let us put it all together: a list (GET /api/notes), creating (POST), reading one note (GET /api/notes/2) and deleting (DELETE). The notes live in an array in memory for now — they are lost when the server restarts; the database comes in «Express with a database». All errors are thrown from the handle function, and one .catch() turns them into JSON responses; unexpected errors (without a status) are logged, while the client sees only Internal error.

JavaScript
// notes-server.mjs
import http from 'node:http';
import { HttpError, send, readJson } from './http-utils.mjs';

const notes = [{ id: 1, text: 'Buy bread' }];
let nextId = 2;

async function handle(req, res) {
  const { pathname } = new URL(req.url, 'http://localhost');
  if (pathname === '/api/notes' && req.method === 'GET') return send(res, 200, notes);
  if (pathname === '/api/notes' && req.method === 'POST') {
    const { text } = await readJson(req);
    if (typeof text !== 'string' || !text.trim()) throw new HttpError(400, 'text is required');
    const note = { id: nextId++, text: text.trim() };
    notes.push(note);
    res.setHeader('Location', `/api/notes/${note.id}`);
    return send(res, 201, note);
  }
  const id = Number(pathname.match(/^\/api\/notes\/(\d+)$/)?.[1]);
  if (!id) throw new HttpError(404, `Nothing at ${pathname}`);
  const index = notes.findIndex((n) => n.id === id);
  if (index === -1) throw new HttpError(404, 'Note not found');
  if (req.method === 'GET') return send(res, 200, notes[index]);
  if (req.method !== 'DELETE') throw new HttpError(405, 'Method not allowed');
  notes.splice(index, 1);
  res.writeHead(204).end();
}

http.createServer((req, res) => handle(req, res).catch((error) => {
  if (!error.status) console.error(error);
  send(res, error.status ?? 500, { error: error.status ? error.message : 'Internal error' });
})).listen(3000, () => console.log('Notes API on http://localhost:3000'));
pathname.match(...)?.[1] gives undefined if the path is not /api/notes/<digits>, and Number(undefined) is NaN — a falsy value, hence 404. res.writeHead(204).end() sends an answer without a body.
JavaScript
// notes-client.mjs
const base = 'http://localhost:3000/api/notes';

async function call(method, url, body, type = 'application/json') {
  const headers = body === undefined ? {} : { 'Content-Type': type };
  const res = await fetch(url, { method, headers, body });
  const text = await res.text();
  console.log(`${method} ${url.slice(21)} → ${res.status}${text ? ` ${text}` : ''}`);
}

await call('POST', base, JSON.stringify({ text: 'Call Leyla' }));
await call('POST', base, '{"text": "oops"');
await call('POST', base, 'text=hi', 'text/plain');
await call('POST', base, JSON.stringify({ text: 'x'.repeat(20_000) }));
await call('POST', base, JSON.stringify({ title: 'no text' }));
await call('GET', `${base}/2`);
await call('DELETE', `${base}/1`);
await call('DELETE', `${base}/1`);
await call('PUT', `${base}/2`);
await call('GET', base);
await call('GET', 'http://localhost:3000/api/users');

Expected output

POST /api/notes → 201 {"id":2,"text":"Call Leyla"}
POST /api/notes → 400 {"error":"Body is not valid JSON"}
POST /api/notes → 415 {"error":"Expected Content-Type: application/json"}
POST /api/notes → 413 {"error":"Body is larger than 10000 bytes"}
POST /api/notes → 400 {"error":"text is required"}
GET /api/notes/2 → 200 {"id":2,"text":"Call Leyla"}
DELETE /api/notes/1 → 204
DELETE /api/notes/1 → 404 {"error":"Note not found"}
PUT /api/notes/2 → 405 {"error":"Method not allowed"}
GET /api/notes → 200 [{"id":2,"text":"Call Leyla"}]
GET /api/users → 404 {"error":"Nothing at /api/users"}
Each line is one request: 201 created, 400 broken JSON, 415 wrong type, 413 large body (20 000 bytes > 10 000), 400 no text, 204 deleted, deleting the same note again — 404, PUT — 405.

Now look at what we wrote by hand: parsing the URL, matching paths with regular expressions, collecting the body, checking type and size, turning errors into statuses, safe static files. Every project needs the same code, and every hand-made copy can have its own bug. Frameworks turn these pieces into tested building blocks:

By hand (node:http)Express
new URL(req.url, …) + if / regexapp.get('/api/notes/:id', …), req.params.id
readJson(req)app.use(express.json()), req.body
resolveSafe + pipelineapp.use(express.static('public'))
HttpError + .catch()error-handling middleware
res.writeHead(201, …).end(JSON.stringify(x))res.status(201).json(x)

Exercise

Write the heart of a router: matchRoute(pattern, pathname) compares a pattern such as /api/notes/:id with a path. On a match it returns the params object ({ id: '7' }, values decoded with decodeURIComponent), otherwise null. A different number of segments means null.

Exercise · JavaScript
function matchRoute(pattern, pathname) {
  const want = pattern.split('/').filter(Boolean);
  const got = pathname.split('/').filter(Boolean);
  // compare segment by segment; ':name' segments go into params
}

console.log(matchRoute('/api/notes/:id', '/api/notes/7'));
console.log(matchRoute('/api/users/:userId/notes/:noteId', '/api/users/3/notes/15'));
console.log(matchRoute('/api/notes/:id', '/api/notes'));
console.log(matchRoute('/api/notes', '/api/notes/'));
console.log(matchRoute('/api/tags/:name', '/api/tags/G%C9%99nc%C9%99'));
Expected output
{ id: '7' }
{ userId: '3', noteId: '15' }
null
{}
{ name: 'Gəncə' }

Exercise

Write the path traversal defence without node:path: resolveInside(urlPath) decodes the path (decodeURIComponent; broken encoding gives null), splits it on / and \, drops . and empty parts and goes one step back on ... An attempt to climb above the root gives null. The result is the relative path joined with /, and an empty path becomes index.html.

Exercise · JavaScript
function resolveInside(urlPath) {
  // 1) decode (try/catch → null)
  // 2) split on / and \, walk the parts with a stack
  // 3) '..' on an empty stack → null
}

const tests = ['/', '/css/./site.css', '/img/../css/site.css', '/../secret.txt',
  '/css/..%2f..%2fsecret.txt', '/..%5csecret.txt', '/%E0%A4%A', '/docs/My%20CV.pdf'];
for (const t of tests) console.log(`${t} -> ${resolveInside(t)}`);
Expected output
/ -> index.html
/css/./site.css -> css/site.css
/img/../css/site.css -> css/site.css
/../secret.txt -> null
/css/..%2f..%2fsecret.txt -> null
/..%5csecret.txt -> null
/%E0%A4%A -> null
/docs/My%20CV.pdf -> docs/My CV.pdf

Remember

  • http.createServer((req, res) => …): req gives the method, URL, headers and the body stream; res takes the status, headers and a body finished with end().
  • Parse the URL with new URL(req.url, 'http://localhost'); a route = method + pathname; path exists but method does not — 405 with Allow.
  • JSON body: check the Content-Type (415), a size limit (413), Buffer.concat + JSON.parse, and 400 for broken JSON.
  • Static files: decode, join, then check that the result starts with ROOT + path.sep — otherwise path traversal leaks files.
  • Turn errors into statuses in one place and show no details on a 500; this repeated work is why frameworks exist.
Spotted a mistake or something inaccurate in this lesson?

Check yourself

12 questions. Every correct answer earns XP.

Question 1 / 12

Question 1 / 12. A client sends GET /search?q=tea. What is req.url?