Skip to content

Creating an HTTP Server

http.createServer(callback) returns a Server instance. The callback — called the request listener — is invoked once per incoming HTTP request. It receives two arguments:

  • req — an IncomingMessage object describing the request (method, URL, headers, body stream).
  • res — a ServerResponse object used to write the response.

Call server.listen(port, callback) to start accepting connections. The callback fires once the server is ready.

Every HTTP response has a status code and a set of headers. Use res.writeHead(statusCode, headersObject) to set both at once, before writing any body data.

Common status codes:

CodeMeaning
200OK
201Created
400Bad Request
404Not Found
500Internal Server Error

res.end(data) writes the final chunk of the response body and signals to Node.js that the response is complete. Every request handler must call res.end() (or res.destroy()) — if you forget, the client will wait forever and the connection will time out.

You can also use res.write(data) to send data in chunks before calling res.end().

A complete server with status codes and headers

Section titled “A complete server with status codes and headers”
Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Open in StackBlitz, then visit http://localhost:3000 in the preview tab to see the rendered HTML response with correct headers.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

What is the purpose of res.end() in a Node.js HTTP server?
Which method sets both the status code and response headers at once?
What happens if you forget to call res.end() in a request handler?