You've learned how Node.js works inside. Now you'll build something with it: an HTTP server, using only Node.js's built-in http module. Along the way you'll learn what servers, IP addresses, ports, sockets and HTTP messages really are: knowledge you'll use in every chapter of Season 2.
In this chapter you'll learn
- the two meanings of "server": hardware and software
- IP addresses, ports, and how a request finds the right program
- sockets, TCP connections and keep-alive; and how WebSockets differ
- what an HTTP request and response contain
- how to build a server with the
httpmodule, with simple routing and JSON responses - why almost everyone uses Express instead (Season 2)
Before you start: read Chapter 02: JS on the Server (client and server basics). The original example is in Code/Server.js.
What is a server?
"Server" has two meanings, and people switch between them all the time:
- Hardware: a physical computer, usually in a data centre, with a CPU, RAM, storage and a network connection. It runs all the time.
- Software: a program that listens for requests and sends back responses. Your Node.js app is a software server.
When someone says "deploy your app to a server", they mean all three layers:
- Hardware: a machine (today usually a rented virtual machine, such as an AWS EC2 instance)
- Operating system: usually Linux, running on that machine
- Server software: your Node.js app (and often Nginx in front of it), running on that OS
You'll do exactly this in Season 3: Chapter S3 01: Lanching an AWS Instance and Deploying frontend.
How a request finds your program
IP addresses
Every device on a network has an IP address, like a postal address: for example 142.250.183.14 (IPv4) or 2404:6800:4009::200e (IPv6). Your own machine is always reachable from itself at 127.0.0.1, also known as localhost.
People don't type IP addresses; they type names like google.com. DNS (Domain Name System) translates names into IP addresses. You'll set up DNS for your own domain in Chapter S3 03: Adding a custom Domain name.
Ports
One machine can run many server programs at once: a web server, a database, an SSH server... The IP address gets the request to the machine; the port gets it to the right program.
Think of an apartment building: the IP address is the building's address, and the port is the flat number.
- A port is a number from 0 to 65535 (it's stored in 16 bits), so it can have 1 to 5 digits.
- Each port can be used by one program at a time. Starting a second server on a busy port fails with
EADDRINUSE. - Some ports have standard uses:
| Port | Used for |
|---|---|
| 22 | SSH (remote login) |
| 80 | HTTP |
| 443 | HTTPS |
| 3000, 5000, 7777, 8080 | common choices for development servers |
| 5173 | Vite dev server (you'll use it in Chapter S2 15: DevTinder UI - Part 1) |
| 27017 | MongoDB |
- Ports below 1024 are privileged: on Linux and macOS, a normal user can't listen on them without
sudo. That's why development servers use ports like 3000.
The original course example uses port 999. On Linux and macOS, server.listen(999) fails with Error: listen EACCES: permission denied, because 999 is below 1024. Use a port like 3000 or 7777 instead. (On Windows it works, which is why the lecture didn't hit the problem.)
The same example also responds twice for /getSecretData (there's no return after the first res.end). On Node.js 22 that request gets its answer, but then the server crashes with ERR_STREAM_WRITE_AFTER_END, and the next request finds nothing listening. The routing example below fixes both problems.
So http://localhost:7777/api/user means: machine localhost, program listening on port 7777, path /api/user.
Sockets and TCP
To talk, a client and a server open a connection. Almost all web traffic uses TCP (Transmission Control Protocol), which guarantees that data arrives complete and in order.
- Each end of a connection is a socket: one on the client, one on the server.
- Opening a TCP connection takes a short handshake (three messages back and forth), plus a TLS handshake for HTTPS, to set up encryption.
- Once open, data can flow both ways.
Keep-alive: connections are reused
In very old HTTP (HTTP/1.0), the browser opened a new connection for every request and closed it afterwards. That's slow: every image, script and stylesheet paid the handshake cost again.
Since HTTP/1.1, connections are kept alive by default: the browser opens a connection once and sends many requests over it. You can see it in Node.js's response headers: Connection: keep-alive. HTTP/2 goes further and runs many requests at the same time over one connection.
WebSockets
HTTP is request → response: the server can only answer; it can't start a conversation. For apps where the server needs to push data at any moment (chat messages, live scores, notifications), there's the WebSocket protocol:
| HTTP | WebSocket | |
|---|---|---|
| Who starts a message | only the client asks; the server answers | either side, at any time |
| Connection | request/response, usually reused (keep-alive) | one long-lived connection, kept open on purpose |
| Typical use | web pages, REST APIs | chat, live dashboards, multiplayer games |
| Starts with | http:// / https:// | ws:// / wss:// (begins as an HTTP request, then "upgrades") |
What's inside an HTTP request and response
HTTP messages are plain text with a fixed structure.
A request:
GET /api/user?id=42 HTTP/1.1 ← method, path (+ query string), version
Host: localhost:7777 ← headers: extra information
Accept: application/json
Cookie: token=eyJhbGci...
← blank line, then an optional body (for POST/PUT/PATCH)GET /api/user?id=42 HTTP/1.1 ← method, path (+ query string), version
Host: localhost:7777 ← headers: extra information
Accept: application/json
Cookie: token=eyJhbGci...
← blank line, then an optional body (for POST/PUT/PATCH)A response:
HTTP/1.1 200 OK ← version, status code, status text
Content-Type: application/json ← headers
Connection: keep-alive
{"name":"Akshay","city":"Dehradun"} ← bodyHTTP/1.1 200 OK ← version, status code, status text
Content-Type: application/json ← headers
Connection: keep-alive
{"name":"Akshay","city":"Dehradun"} ← bodyThe key parts:
- Method: what you want to do:
GET(read),POST(create),PUT/PATCH(update),DELETE. Season 2 covers them in Chapter S2 04: Routing and Request handlers. - Path: which resource:
/api/user. - Headers: metadata, like
Content-Type(format of the body) orCookie. - Body: the data itself (JSON, HTML, a file...).
- Status code: the result:
200OK,404Not Found,500Server Error... (full list in Chapter S2 05: Middlewares and Error Handlers).
Building a server with the http module
The smallest possible server
The examples in this chapter use ES Modules (import), the modern standard. To run them, add "type": "module" to your package.json or name the files .mjs. The CommonJS form is const http = require("node:http"); see the CommonJS → ES Modules cheat sheet.
// server.js
import http from "node:http";
const PORT = 7777;
const server = http.createServer((req, res) => {
res.end("Namaste from Node.js!");
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});// server.js
import http from "node:http";
const PORT = 7777;
const server = http.createServer((req, res) => {
res.end("Namaste from Node.js!");
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});Run node server.js and open http://localhost:7777 in your browser.
http.createServer(callback)creates a server. The callback runs once for every incoming request.req(request) describes what the client asked for:req.method,req.url,req.headers.res(response) is how you answer:res.writeHead(),res.write(),res.end().server.listen(PORT)asks the operating system to send this port's connections to your program. The process now keeps running (the event loop has a server to watch: Chapter 09: libuv & event loop). Stop it withCtrl + C.
Handling different URLs (routing)
Routing means sending different requests to different code, based on the method and the path:
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
return res.end("Namaste from Node.js!");
}
if (req.method === "GET" && req.url === "/getSecretData") {
res.writeHead(200, { "Content-Type": "text/plain" });
return res.end("You are a human and the secret is safe. Chill.");
}
if (req.method === "GET" && req.url === "/api/user") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ name: "Akshay", city: "Dehradun" }));
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page not found");
});
server.listen(7777, () => console.log("Server running on port 7777"));import http from "node:http";
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
return res.end("Namaste from Node.js!");
}
if (req.method === "GET" && req.url === "/getSecretData") {
res.writeHead(200, { "Content-Type": "text/plain" });
return res.end("You are a human and the secret is safe. Chill.");
}
if (req.method === "GET" && req.url === "/api/user") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ name: "Akshay", city: "Dehradun" }));
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page not found");
});
server.listen(7777, () => console.log("Server running on port 7777"));Some details that matter:
return res.end(...): thereturnstops the function. Without it, the code keeps going and callsres.enda second time. On current Node.js versions, ending a response twice with data emitsERR_STREAM_WRITE_AFTER_END, and since nothing handles that error, the whole server crashes. (Setting headers after the response has been sent throwsERR_HTTP_HEADERS_SENT.) Alwaysreturnafter responding.- Paths are case-sensitive:
/getSecretDataand/getsecretdataare different URLs. req.urlincludes the query string: a request to/api/user?id=42hasreq.url === "/api/user?id=42", so the check above wouldn't match. You'd have to parse it withnew URL(req.url, "http://localhost").- JSON must be turned into a string (
JSON.stringify), with theContent-Type: application/jsonheader so the client knows how to read it.
Why we use Express
Look at what's missing from the server above: parsing query strings, reading a JSON body from a POST request (it arrives in chunks you must collect yourself), URL parameters like /user/:id, error handling, cookies... You'd have to write all of it, and the if chain gets long fast.
Express is a small framework built on top of the http module that does this for you:
import express from "express"; // Express is a CommonJS package; ESM imports it as the default export
const app = express();
app.get("/api/user", (req, res) => {
res.json({ name: "Akshay", city: "Dehradun" }); // sets Content-Type for you
});
app.listen(7777, () => console.log("Server running on port 7777"));import express from "express"; // Express is a CommonJS package; ESM imports it as the default export
const app = express();
app.get("/api/user", (req, res) => {
res.json({ name: "Akshay", city: "Dehradun" }); // sets Content-Type for you
});
app.listen(7777, () => console.log("Server running on port 7777"));Under the hood, Express still calls http.createServer. Everything you learned in this chapter still applies. You'll set up Express in Chapter S2 03: Creating our Express server. The DevTinder project there follows the original lectures and uses CommonJS (const express = require("express")); both forms do the same thing.
Common mistakes
- Port already in use (
EADDRINUSE): another program (often your own server, still running in another terminal) is using it. Stop it, or pick another port. - Privileged ports (
EACCES) below 1024 on Linux/macOS. - Forgetting
returnafterres.end(), so the code runs on and responds twice, which crashes the server. - Never calling
res.end(): the browser keeps loading forever (until it times out). - Sending objects directly:
res.end({ a: 1 })throws; useJSON.stringify.
Key takeaways
- A server is hardware (a machine) or software (a program that answers requests); deploying needs both, plus an OS.
- The IP address finds the machine, the port (0–65535) finds the program. Ports below 1024 are privileged.
- Clients and servers talk over TCP connections (sockets). HTTP/1.1 keeps connections alive and reuses them.
- WebSockets keep a connection open so the server can push messages.
- An HTTP request has a method, path, headers and body; a response has a status code, headers and body.
http.createServerruns your callback for every request. Always return after responding.
Interview questions
Q1. What happens when you type a URL in the browser and press Enter?
- The browser finds the server's IP address via DNS. 2. It opens a TCP connection to that IP and port (443 for HTTPS) and performs a TLS handshake. 3. It sends an HTTP request (method, path, headers). 4. The server processes it and sends an HTTP response (status, headers, body). 5. The browser renders the HTML and fetches other resources (CSS, JS, images), reusing the connection. Interviewers like this question because it touches every layer.
Q2. What is the difference between an IP address and a port?
The IP address identifies a machine on the network. The port (0–65535) identifies a specific program on that machine. Together (IP:port) they define where a connection goes, for example 127.0.0.1:3000.
Q3. What is the difference between HTTP and WebSockets?
HTTP is request–response: the client always asks and the server answers. WebSocket is a persistent, two-way connection where either side can send messages at any time, which is ideal for chat and live updates. A WebSocket connection starts as an HTTP request that is "upgraded".
Q4. What is the difference between HTTP and HTTPS?
HTTPS is HTTP over TLS: the connection is encrypted and the server proves its identity with a certificate. Nobody in between (public Wi-Fi, ISPs) can read or change the data. HTTPS uses port 443 by default; HTTP uses 80. You'll set up HTTPS in Chapter S3 03: Adding a custom Domain name.
Q5. What is HTTP keep-alive?
Keep-alive means the TCP connection stays open after a response, so the next requests reuse it instead of doing a new handshake each time. It's the default in HTTP/1.1, and Node.js sends Connection: keep-alive automatically. It makes pages load faster.
Q6. What are req and res in http.createServer((req, res) => {})?
req is an IncomingMessage object describing the request (method, URL, headers; the body arrives as a stream). res is a ServerResponse object used to build the reply: res.writeHead(status, headers), res.write(chunk) and res.end(data), which finishes the response.
Q7. What are TCP and UDP?
Both are transport protocols. TCP is connection-based and reliable: data arrives complete and in order, with retransmission of lost packets. It's used for HTTP, databases and email. UDP sends packets without a connection or delivery guarantee, but with less overhead. It's used for video calls, games and DNS, where speed matters more than a lost packet.
What's next
Most servers need to store data somewhere: users, posts, messages. In Chapter 12: Databases SQL and NoSQL you'll get an overview of the different kinds of databases, and why DevTinder uses MongoDB.