Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 133 ยท Networking and HTTP

The http Module: Servers

Build HTTP servers with the Node.js http module - createServer, request and response objects as streams, status codes, headers, reading bodies, streaming replies, timeouts and graceful shutdown.

Node.js became famous because a complete web server fits in a few lines. The built-in node:http module gives you a server that parses HTTP for you and hands each request to a function you write. Frameworks like Express, Fastify and Hono are built on exactly this module, so everything you learn here applies to all of them.

In this lesson you will create a server, read the request, send responses with the right status codes and headers, read a request body, stream a reply, and shut down cleanly. Servers in our editor must listen on 127.0.0.1 with port 0, and a client in the same program (fetch) calls them, as you saw in TCP Servers and Clients with net. HTTP itself is built on that TCP layer.

The smallest server

http.createServer(handler) returns a server. The handler is called for every request with two arguments: req, an IncomingMessage (what the client sent), and res, a ServerResponse (what you send back). You must always finish the response with res.end(), otherwise the client waits for ever.

Node.js A server and a fetch call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The handler runs inside the event loop, so while it waits for a database or a file (with await), Node serves other requests. A handler that does heavy synchronous work, like a huge loop, blocks every other request. See The Event Loop.

What is in the request

req carries everything the client sent before the body:

  • req.method: 'GET', 'POST', ... (always upper case).
  • req.url: only the path and query string, such as /search?q=node, not the host.
  • req.headers: an object whose keys are lower case, whatever the client sent.
  • req.httpVersion, req.socket (the underlying TCP socket) and more.

To pick req.url apart, build a URL object. The base is only needed so the parser accepts a relative path; it is not used for anything else.

Node.js Inspecting a request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The client sent the header as X-Demo and the server reads it as x-demo. If a header appears more than once, Node joins the values with , , except for a few like set-cookie, which stay arrays. See Headers, Cookies and Caching.

Status codes and headers

The status code tells the client what happened: 2xx success, 3xx redirect, 4xx the client made a mistake, 5xx the server failed. Set it with res.statusCode, or together with headers using res.writeHead(status, headers). Headers can be changed with res.setHeader() only until the first byte of the body is sent.

Node.js Several responses with the right codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

We asked fetch not to follow redirects (redirect: 'manual') so that the 301 is visible; the client side is explained in HTTP Clients. Choose codes deliberately: 200 for success, 201 for "created", 204 for "success, nothing to return", 400 for a bad request, 401 and 403 for authentication and permission problems, 404 for a missing resource, 500 for your own bugs. Designing REST APIs goes deeper.

Headers cannot be changed after the body starts

HTTP sends the status line and headers first. The first res.write() or res.end(data) flushes them to the client, and after that they are fixed. Trying to set one afterwards is a bug that Node reports with an error. Here is how it looks, caught so the program continues.

Node.js Changing headers after the body has started

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

ERR_HTTP_HEADERS_SENT is among the most common server errors in Node. It usually means a code path replied twice, for example an if branch that sends a reply but forgets to return. Check res.headersSent when you need to know.

Reading a request body

The body is not read for you. req is a readable stream, so you consume it with events or, nicer, with for await. Collect the chunks, join them, and then parse. Here the server accepts JSON and answers 400 when the JSON is broken.

Node.js Reading and parsing a JSON body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real servers also cap the body size (stop reading and answer 413 when the total passes a limit), check Content-Type, and handle forms. That is the subject of Request Bodies, JSON and Forms. Note the async handler: if it throws and nothing catches the error, you get an unhandled rejection, so wrap the body in try/catch as above.

Routing by hand

A real application answers different paths and methods differently. The simplest router is a switch or if chain on req.method and the path. This small API keeps a list of notes in memory.

Node.js A tiny notes API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This works but grows unwieldy fast. Real code separates routes into a table or a router object; you will write one in Building a Router from Scratch, and the pattern generalises into middleware.

Streaming responses

res is a writable stream. You do not have to build a whole response in memory: write parts as they become ready, or pipe a readable into it. When you do not set Content-Length, Node automatically uses Transfer-Encoding: chunked, so the client can start reading before you finish.

Node.js Piping a readable into the response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Use pipeline rather than .pipe() so that errors and a client that disconnects mid-download clean up the source properly (see pipeline and Backpressure). The number and boundaries of chunks the client sees can vary between runs, as with TCP; only the combined text is guaranteed. Streaming also underlies Server-Sent Events.

Timeouts and limits

A public server must defend itself against slow or malicious clients. http.Server has timeout properties with defaults you should know. You can print them, and change them to fit your traffic.

Node.js Server timeout defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

headersTimeout is how long a client has to send its headers; requestTimeout is how long it has to send the whole request; keepAliveTimeout is how long an idle connection stays open between requests. Putting a reverse proxy such as nginx or a load balancer in front is common and adds its own limits. The default http.maxHeaderSize of 16 KiB makes Node answer 431 to absurdly large headers. For TCP-level protection see the idle-timeout section in TCP Servers and Clients with net.

Shutting down gracefully

Calling server.close() stops accepting new connections and waits for current ones to finish. Since Node 19 it also closes connections that are idle at that moment (a keep-alive connection waiting for the next request). A request that is still in flight is allowed to finish, and the connection it used then stays open, idle, until keepAliveTimeout passes; server.closeIdleConnections() closes such connections right away. server.closeAllConnections() forcibly drops everything, which is the last resort after a deadline.

Node.js Closing the server while a request is in flight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The slow request is not cut off, and new requests are refused with ECONNREFUSED. Try deleting the closeIdleConnections() line: the program then takes several seconds to finish, because the server politely waits for the idle connection to expire. A production server also listens for SIGTERM, calls close(), sets a deadline, and exits; Graceful Shutdown and Health Checks covers the full recipe.

Reference corner: trailers, raw headers, agent pools and request events

The http module has a handful of features that most tutorials skip, but that show up in debugging sessions, proxies and performance work.

Trailers: headers after the body

A chunked response can send headers after the body, called trailers. The use case is a value you only know once you have streamed everything, such as a checksum or a final status. The server announces the names in a Trailer header, writes the body, then calls res.addTrailers() before res.end(). The client reads them from res.trailers once the body has ended. Trailers need chunked encoding (they are not possible with a Content-Length response), and many browsers and proxies ignore them, so they are mainly useful between services you control. gRPC, for example, sends its final status as a trailer.

Raw headers

req.headers and res.headers are convenient but lossy: names are lowercased and duplicate headers are merged. When you need the exact bytes (debugging a proxy, checking header case, counting duplicates), use rawHeaders, a flat array [name1, value1, name2, value2, ...] in the order received. Only set-cookie is kept as an array in the parsed version, because it must not be joined with commas.

Node.js Trailers, set-cookie arrays and rawHeaders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

http.STATUS_CODES maps numbers to the standard reason phrases and http.METHODS lists every method the parser knows, both handy when you build error pages or validate input.

Agent pools: limiting concurrent connections

An http.Agent decides how outgoing requests share connections (the basics are in HTTP Clients). The setting that matters for load is maxSockets: how many connections the agent opens at once per host. Requests beyond the limit wait in a queue inside the agent. The default is Infinity, which means a loop of a thousand requests opens a thousand connections, so use a limit when you call a fragile service. Related options: maxFreeSockets (idle connections kept for reuse), timeout (socket idle timeout) and scheduling ('lifo', the default, reuses the most recently used connection, or 'fifo').

The experiment sends six requests that each take 30 ms on the server, once through an agent limited to two sockets and once through an unlimited one. The server counts how many requests it saw at the same time.

Node.js maxSockets and the lifecycle events of a request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With maxSockets: 2 the server never sees more than two simultaneous requests, because the other four requests waited in the agent's queue and went out in later waves; the unlimited agent sends all six at once. That is exactly the back-pressure you want when calling a rate-limited API.

ClientRequest events

The object returned by http.request() and http.get() is an event emitter with a predictable order: 'socket' (a connection was assigned, possibly after queueing), 'finish' (the request body was fully sent), 'response' (the status line and headers arrived, and the body is now a stream you must consume or call resume() on), and 'close'. Two more matter for robustness: 'timeout' fires when the socket is idle for the time set with req.setTimeout(ms) (it does not abort the request by itself, so call req.destroy() in the handler), and 'error' reports connection failures such as ECONNREFUSED or ECONNRESET. Always attach an 'error' listener: an unhandled one crashes the process. The newer AbortSignal.timeout() option in fetch and http.request is the simpler route for deadlines; see AbortController and Cancellation.

Pitfalls and good habits

  • Always end the response, exactly once. Every code path needs res.end(); and after sending, return.
  • Never trust req.url or headers. Validate and decode input; do not build file paths from it (see Web Application Security).
  • Do not block the event loop. Heavy CPU work in a handler stalls every request; use worker threads.
  • Handle errors in async handlers. An exception in an async handler becomes an unhandled rejection that can crash the process.
  • Set sensible Content-Type and charset headers, and Cache-Control where it matters.
  • Do not reinvent everything. node:http is perfect for learning, small services and internal tools. For larger apps use a framework or a router built on it (see Express and Minimal Frameworks) so you get parsing, validation and error handling without writing them yourself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does req.url contain for a request to http://example.com/search?q=node?

    req.url holds the path and query string as sent on the request line. Use new URL(req.url, base) to take it apart.
  2. 2. Why does the handler need to read the request body with for await (const chunk of req)?

    IncomingMessage is a stream. You consume its chunks and combine them; no body parsing happens for you.
  3. 3. When can you still call res.setHeader()?

    Headers are sent with the first write. Afterwards setHeader throws ERR_HTTP_HEADERS_SENT.
  4. 4. What does server.close() do to a request that is already being handled?

    close() stops accepting new connections and waits for in-flight work; use closeAllConnections() after a deadline to force it.
  5. 5. Which status code fits a successful DELETE that returns no body?

    204 No Content means success without a response body.

Summary

  • http.createServer((req, res) => ...) runs your handler for every request; always call res.end() once.
  • req.method, req.url (path plus query) and lower-case req.headers describe the request; new URL(req.url, base) parses the URL.
  • Set status codes and headers with writeHead/setHeader before the body starts; afterwards you get ERR_HTTP_HEADERS_SENT.
  • Request bodies are streams: collect chunks with for await, validate, and limit the size.
  • Responses are streams too: pipeline(source, res) streams data with chunked encoding.
  • Know the server timeouts, handle errors in async handlers, and shut down with server.close().

Next: HTTP Clients: fetch and http.request