Node.js Server
HTTP module
Node's built-in node:http module creates an HTTP server without external dependencies. Every incoming request fires your handler with a readable stream (req) and a writable response stream (res). Always bind to process.env.PORT with a local fallback so the server works in both development and cloud containers:
import http from "node:http";
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
if (req.method === "GET" && url.pathname === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Not Found" }));
});
const port = Number(process.env.PORT) || 3000;
server.listen(port, () => console.log(`Listening on :${port}`));
Routes
Parse req.url with the standard URL constructor so query parameters and pathnames are separated cleanly. Even before adopting a framework like Express or Fastify, keeping a clear route table (matching both HTTP method and pathname) makes request flow easy to trace and test.
Response design
Every response must set its status code and headers before calling res.end(), and every code path in your handler must end the response so clients never hang waiting for a timeout:
- Intentional status codes: Return
200/201for success,400for invalid input,404for unknown routes, and500for unexpected server faults. - Explicit
Content-Type: Always declareapplication/jsonortext/plain; charset=utf-8. - Safe error payloads: Log full stack traces server-side, but return concise, non-sensitive error messages to HTTP callers.
Practice
Extend the core HTTP server above and test it with curl:
- Add a
GET /timeroute that returns the current ISO timestamp as JSON. - Return
405 Method Not Allowedwhen a client sendsPOST /health. - Extract the route-matching logic into a pure helper function so it can be unit-tested without opening a network port.