A Web Server with Node's http Module

Node's own http module starts a web server that keeps running and calls your function once for every request, which reads req.method and req.url and answers with res.writeHead and res.end.

Apprentice · Node.js · Web Development · Updated

By

After this lesson you can

  • Start a web server with http.createServer and listen, read req.method and req.url, and stop it with Ctrl+C
  • Answer a request with res.writeHead and res.end, sending JSON with Content-Type application/json
  • Fix a server that won't start because its port is already in use (EADDRINUSE)

Key takeaways

  • http.createServer takes a function that Node calls once for every request, and server.listen(3100) starts waiting for requests at port 3100.
  • A server keeps running until you stop it with Ctrl+C, and it runs your code as it was when it started, so restart it, or use node --watch, after every change.
  • req.method is the request's method, and req.url is its path and query string, such as /plots?free=true.
  • res.writeHead sets the status code and headers, and res.end sends the body as text and finishes the response. JSON.stringify turns data into that text.
  • EADDRINUSE means another program is already listening at that port. Stop it, or pick another port.

Every Node web framework you'll meet, Express included, is built on the module in this lesson. Knowing it pays off on the job when a server won't start, when a request hangs forever, or when you're reading the code underneath a framework to see what it really does.

Greenleaf Community Garden wants neighbors to check the plots from their phones. That needs a program that's always there to answer. A script you've written so far runs from top to bottom and ends; a server has to stay running and wait for requests that could come at any moment.

A program that waits

Think of a shop with a bell on its door. The shopkeeper doesn't stand at the door all day: they get on with things, and each time the bell rings, they go and serve whoever came in.

Node's built-in node:http module gives you that shop. http.createServer takes a function, your request handler, and Node calls it once for every request that comes in. server.listen(3100) opens the door: it starts waiting for requests at port 3100 on your computer. A port is a numbered door; each program that waits for requests listens at its own.

In a folder of its own, with a package.json holding { "type": "module" }, make server.js:

import http from "node:http";

const server = http.createServer((req, res) => {
  console.log(req.method, req.url);
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Welcome to Greenleaf Community Garden!");
});

server.listen(3100, () => {
  console.log("Listening on http://localhost:3100");
});

Run it in VS Code's terminal:

node server.js
Listening on http://localhost:3100

The prompt doesn't come back. That's the server waiting, which is what you want. The function you gave listen ran once, as soon as the server was ready. Send it GET http://localhost:3100 from a .http file, or open that address in a browser, and the body comes back: Welcome to Greenleaf Community Garden!. localhost is the name every computer has for itself, so only you can reach this server for now.

Stopping and restarting

Click in the server's terminal and press Ctrl+C to stop it; the prompt comes back. A running server keeps the code it started with, so after every change, stop it and start it again. Or start it with node --watch server.js, and Node restarts it each time you save.

What's in a request: req.method and req.url

Your handler gets two objects every time. req (the request) holds what the client sent, and res (the response) is how you answer. The first line of the handler logs two things from req. Send three requests, GET /plots?free=true, POST /plots and DELETE /plots/3, and the terminal shows:

Listening on http://localhost:3100
GET /
GET /plots?free=true
POST /plots
DELETE /plots/3

req.method is the method, and req.url is the path and query string only, never the http://localhost:3100 part. That's why HTTP in Plain Words: Requests and Responses gave new URL() a base address.

Answering with JSON: res.writeHead and res.end

Every answer takes two steps. res.writeHead(status, headers) sets the status code and headers. res.end(body) sends the body and finishes the response. To send the plots as JSON, change the handler:

const plots = [
  { number: 1, size: "small", gardener: "Rosa", growing: "tomatoes" },
  { number: 2, size: "small", gardener: null, growing: null },
  { number: 3, size: "large", gardener: "Malik", growing: "pumpkins" },
];

const server = http.createServer((req, res) => {
  console.log(req.method, req.url);
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify(plots));
});

Restart it and send GET http://localhost:3100/plots:

HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 17 Nov 2026 17:11:43 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

[{"number":1,"size":"small","gardener":"Rosa","growing":"tomatoes"},{"number":2,"size":"small","gardener":null,"growing":null},{"number":3,"size":"large","gardener":"Malik","growing":"pumpkins"}]

Two mistakes are worth knowing by sight:

  • Forgetting res.end. The response never finishes, so REST Client keeps waiting. Every path through your handler must end with exactly one res.end.
  • Handing res.end the array itself. res.end sends text, so res.end(plots) stops the whole server with TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Array. JSON.stringify(plots) turns the array into JSON text first.

When the port is already taken

Start the server while another copy is still running, maybe in a second terminal you forgot about, and Node stops at once. The most important lines of what it prints:

Error: listen EADDRINUSE: address already in use :::3100

EADDRINUSE (read "E-ADDR-IN-USE", address in use) means another program is already listening at port 3100. Only one program can listen at a port. Find the other terminal and stop that server with Ctrl+C, or change the port, to 3101, say, in listen and in your requests.

Check yourself

2 questions to try on the lesson page.

So what

A server is a function that answers requests, plus one line that keeps it waiting: every web framework you'll use adds to exactly this, so when one misbehaves, you now know what's underneath.

Key terms

Related