LESSON 70 · ADVANCED4 min read

HTTP Servers & Routing

Build a server with node:http, read requests, send correct status codes and headers, and handle routing and failures without a framework.

ES2024 / Node.js 20+Free to readModule 16 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Create an HTTP server and end every response deliberately.
  • Parse methods, URLs, headers, and JSON request bodies.
  • Route requests, return 404s, and handle errors without leaking internals.

01Every request calls your function

node:http lets you create a server without a framework. The callback receives a request object, which describes the method, URL, headers, and body stream, and a response object, which you use to set the status and headers before ending the response. server.listen binds the process to a port and begins accepting connections.

Nothing is sent until you call response.end(). If you forget to end a response, the client waits until it times out. Every request needs exactly one exit: success, a handled error, or a deliberate 404. Returning after end prevents code from writing to a finished response.

The request object is a readable stream, and the response is a writable stream. Small JSON APIs can buffer a body in memory, but file uploads need streaming or a dedicated parser. Keep that distinction in mind before copying a JSON example into an upload endpoint.

server.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Methods, URLs, status codes, and headers

Parse request.url with new URL(request.url, "http://localhost") so pathnames and query parameters are decoded consistently. Match both the method and the path: /api/books with GET is a different operation from /api/books with POST. Return 405 when the path exists but the method does not, and 404 when no route matches at all.

Status codes belong in response.writeHead(status, headers). Set Content-Type: application/json when sending JSON, and include a Content-Length only when you know the byte length; most clients handle chunked responses fine. A 204 response must have no body, so call response.end() without writing one.

routing.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Reading a JSON body safely

Request bodies arrive as a stream of buffers, not as an object. Collect the chunks, enforce a size limit, then parse. A limit protects memory from a client that sends an enormous payload; reject oversized bodies with 413. Invalid JSON should produce 400, not an uncaught exception that crashes the process.

for await (const chunk of request) keeps the code readable and respects backpressure. Convert the collected buffers with Buffer.concat(chunks).toString("utf8") before calling JSON.parse. If the body is empty, decide whether that is valid for the endpoint instead of parsing an empty string by accident.

read-json.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04A routing table, 404s, and graceful errors

A plain object can map "METHOD /path" strings to handlers while the API is small. The server resolves the handler, awaits it, and sends the returned status and body. Unknown paths get a JSON 404; thrown errors get a logged 500 with a generic message, never a stack trace or an internal file path.

Wrap the dispatch in try/catch and check response.headersSent before writing an error, because a partially sent response cannot be corrected. Log the real error with a request id, return a stable error shape, and close the server on SIGTERM so in-flight requests can finish before the process exits.

Graceful shutdown also means finishing the current response instead of terminating mid-write. server.close stops new connections and invokes its callback when existing ones are done; a short forced-exit timer prevents a stuck connection from blocking a deployment forever.

router.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • The request handler owns the response until it calls end() and returns.
  • Match method and path, set an explicit status and content type, and read bodies with a size limit.
  • Return JSON errors, hide stack traces, and check whether headers were already sent before writing a failure.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Add a creation route

Extend the routing table with POST /api/books. Return 201, a JSON body containing the received book, and a Location header pointing at /api/books/1.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
const routes = {  "POST /api/books": async (request) => {    const book = await readJson(request);    return {      status: 201,      headers: { Location: "/api/books/1" },      body: { data: { id: 1, ...book } },    };  },};

A creation returns 201 rather than 200, and the Location header tells the client where the new resource can be read. Spreading the parsed body after the generated id keeps the server's identifier authoritative.

02

Exercise 2: Harden the body reader

Change readJson so a body larger than 10 KB rejects with status 413 and invalid JSON rejects with status 400. Return the parsed value on success and null for an empty body.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
async function readJson(request, limit = 10_240) {  let size = 0;  const chunks = [];  for await (const chunk of request) {    size += chunk.length;    if (size > limit) {      throw Object.assign(new Error("Body too large"), { status: 413 });    }    chunks.push(chunk);  }  if (chunks.length === 0) return null;  try {    return JSON.parse(Buffer.concat(chunks).toString("utf8"));  } catch {    throw Object.assign(new Error("Invalid JSON"), { status: 400 });  }}

The size check happens while chunks arrive, so an oversized body is stopped before it is fully buffered. The status values let the caller choose 413 or 400 without inspecting the message text.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01When does an HTTP client receive the response?
02A path exists but the request uses an unsupported method. Which status fits best?
03Why enforce a maximum request-body size?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Add a creation route

Extend the routing table with POST /api/books. Return 201, a JSON body containing the received book, and a Location header pointing at /api/books/1.

EXPECTED OUTPUT
[Process exited with code 0 - No output]
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.