Native HTTP server
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Return a small catalog
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});await withServer((req,res)=>{ res.setHeader('content-type','application/json'); res.end(JSON.stringify([{id:1,title:'Notebook'}]));},async base=>{const r=await localFetch(base+'/catalog'); console.log(r.status,(await r.json())[0].title);});Run:
node main.mjsExpected stdout:
200 NotebookExit status: 0. Expected stderr: empty.
How it works
The fixture helper starts a server on the loopback address and lets the OS allocate a free port. It waits for readiness, runs a finite client scenario and closes connections in finally. The request exposes method and url; the response supplies statusCode, setHeader and end. The first example returns a JSON catalog. The second distinguishes missing paths from a disallowed method on an existing path and includes Allow. These are isolated demos, not hardened Internet services.
Handle missing routes and methods
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});await withServer((req,res)=>{ if(req.url!=='/catalog'){res.statusCode=404;res.end();return;} if(req.method!=='GET'){res.statusCode=405;res.setHeader('allow','GET');res.end();return;} res.end('catalog');},async base=>{ const missing=await localFetch(base+'/missing'); await missing.text(); console.log(missing.status); const denied=await localFetch(base+'/catalog',{method:'POST'});await denied.text();console.log(denied.status,denied.headers.get('allow'));});Run:
node main.mjsExpected stdout:
404405 GETExit status: 0. Expected stderr: empty.
Common mistake
Call end once for every handled request. Do not bind a teaching service to all interfaces. Do not send a second response after headers or content were already sent.
Practice
Add a GET /health route that returns 200 with a small JSON object. Add a check for an unknown path.
Further reading: Authoritative source 1 · Authoritative source 2. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Native HTTP server — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What does createServer pass to the request handler?
Why listen on port 0 in a local fixture?
What header accompanies a 405 response?