A minimal Node HTTP server
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Create a server with the built-in http module and route on method and URL.
- Read a JSON request body from a stream without unbounded buffering.
- Send a JSON response with the correct status and content type.
Overview
#Node ships an http module that turns a callback into a server. You own routing, parsing and response writing; frameworks add convenience on top of the same primitives.
A server with two routes
const http = require('http');
function readJson(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > 1e6) {
req.destroy(new Error('payload too large'));
return;
}
chunks.push(chunk);
});
req.on('end', () => {
try {
const raw = Buffer.concat(chunks).toString('utf8');
resolve(raw ? JSON.parse(raw) : {});
} catch (err) { reject(err); }
});
req.on('error', reject);
});
}
const server = http.createServer(async (req, res) => {
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ ok: true }));
}
if (req.method === 'POST' && req.url === '/echo') {
try {
const body = await readJson(req);
res.writeHead(201, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(body));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'invalid json' }));
}
}
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'not found' }));
});
server.listen(3000);
Why stream the body
req is a readable stream. Accumulating it with a size cap prevents a client from exhausting memory. Never call JSON.parse before the stream ends.
Common pitfalls
- Forgetting
res.end()and leaving the socket open. - Parsing the body on
GETwhere there is none. - Trusting
req.urlfor routing when it contains a query string; parse it withnew URL(req.url, 'http://localhost').
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Add a GET /time route that responds 200 with JSON { now: <ISO string> }.
starter.javascriptif (req.method === 'GET' && req.url === '/time') { // respond with { now: new Date().toISOString() } }Reveal the reference answer
reference.javascriptif (req.method === 'GET' && req.url === '/time') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ now: new Date().toISOString() })); }Authored expected output: 200 with body {"now":"<ISO timestamp>"}
Set the status and content type, serialize the object, and end the response. Returning after end prevents the 404 branch from running.
Exercise 2Debug
This handler hangs every request. Find the bug.
starter.javascriptconst server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.write(JSON.stringify({ ok: true })); });Reveal the reference answer
reference.javascriptconst server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true })); });Authored expected output: Requests complete instead of hanging; the response is sent and the socket closes.
res.write sends bytes but does not finish the response. Without res.end the client waits forever for the end of the message.
Common misconceptions
#- The framework is required to handle requests: the built-in http module is the same layer frameworks wrap.
- req.body exists on a raw Node request: body parsing is something you or a framework adds.
Follow-up practice
#- backend-databases-rest-design
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.