Node.js Server

A Node server turns runtime skills into a real service. Start with the core HTTP module before adding a framework.

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/201 for success, 400 for invalid input, 404 for unknown routes, and 500 for unexpected server faults.
  • Explicit Content-Type: Always declare application/json or text/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:

  1. Add a GET /time route that returns the current ISO timestamp as JSON.
  2. Return 405 Method Not Allowed when a client sends POST /health.
  3. Extract the route-matching logic into a pure helper function so it can be unit-tested without opening a network port.