How HTTP works
Overview
Every time a browser loads a page, a mobile app fetches data, or one service calls another, they speak HTTP — the HyperText Transfer Protocol. Building back ends is, at heart, receiving HTTP requests and sending HTTP responses. Frameworks like Express make this convenient, but they don’t change the protocol underneath. Understanding it makes you far better at designing APIs and debugging them.
Request and response
HTTP is a request–response protocol. A client opens a connection, sends a request, the server sends back a response, and that exchange is complete. Both are just structured text (for HTTP/1.1) sent over a network connection.
A request has:
- a method — what you want to do (
GET,POST…); - a path and optional query string — what you want to do it to (
/api/courses?draft=true); - headers — extra information as
Name: valuelines; - an optional body — the data being sent.
A response has:
- a status code and reason phrase — how it went (
201 Created); - headers;
- an optional body — the data being returned.
Methods
| Method | Purpose | Has a body? | Safe | Idempotent |
|---|---|---|---|---|
GET |
read something | no | ✓ | ✓ |
POST |
create something / trigger an action | yes | ✗ | ✗ |
PUT |
replace something entirely | yes | ✗ | ✓ |
PATCH |
change part of something | yes | ✗ | ✗ |
DELETE |
remove something | usually not | ✗ | ✓ |
HEAD |
like GET, headers only | no | ✓ | ✓ |
OPTIONS |
ask what’s allowed (used by CORS) | no | ✓ | ✓ |
- Safe means it doesn’t change anything on the server. Browsers, caches and crawlers assume
GETis safe — never delete data in aGEThandler. - Idempotent means doing it twice has the same effect as doing it once. Deleting course 42 twice still leaves it deleted. Creating twice with
POSTcreates two courses. This matters for retries: idempotent requests can be safely retried after a network failure.
Status codes
The first digit tells you the family:
- 2xx — success.
200 OK(here’s the data),201 Created(made it; seeLocation),204 No Content(done, nothing to return). - 3xx — redirection. Look elsewhere (
301,302), or use your cached copy (304). - 4xx — the client’s fault. Bad input (
400/422), not logged in (401), logged in but not allowed (403), doesn’t exist (404), conflicts with current state (409), too many requests (429). - 5xx — the server’s fault. A bug or crash (
500), an upstream service failed (502), temporarily overloaded or down for maintenance (503).
Choosing the right code isn’t pedantry: clients, monitoring tools and retry logic all depend on it. A 5xx should page an engineer; a 4xx usually shouldn’t.
401 vs 403: 401 means “I don’t know who you are” (log in). 403 means “I know who you are, and you can’t do this”.
Headers
Headers carry metadata. A few you’ll use constantly:
| Header | Direction | Meaning |
|---|---|---|
Content-Type |
both | format of the body: application/json, text/html; charset=utf-8 |
Content-Length |
both | body size in bytes |
Accept |
request | formats the client wants back |
Authorization |
request | credentials, e.g. Bearer <token> |
Cookie / Set-Cookie |
request / response | small values the browser stores and sends back |
Location |
response | where a new or moved resource is |
Cache-Control |
response | how long the response may be cached |
Access-Control-Allow-Origin |
response | which other websites may call this API (CORS) |
Header names are case-insensitive. Node gives them to you in lower case: req.headers['content-type'].
Stateless
HTTP is stateless: each request stands alone. The server doesn’t automatically remember that the same person made the previous request. Anything that needs to persist between requests — who is logged in, what’s in the cart — must travel with each request, usually as a cookie or an Authorization header, and be looked up by the server. You’ll build both approaches in the authentication chapter.
Statelessness is also what makes scaling easy: if no request depends on server memory, any copy of your app can answer any request.
URLs
https://api.example.com:443/courses/42?include=lessons#top
└─┬─┘ └──────┬──────┘ └┬┘└────┬────┘ └──────┬──────┘ └┬┘
scheme host port path query fragmentThe fragment (#top) never reaches the server. Query values are strings, and special characters must be encoded (URLSearchParams does this for you).
HTTPS and versions
HTTPS is HTTP inside an encrypted TLS connection, so nobody between the client and server can read or alter the traffic. Every production API must use it. In practice, TLS is usually handled in front of your Node app — by a load balancer, reverse proxy or hosting platform — and your app speaks plain HTTP behind it.
HTTP/2 and HTTP/3 send the same requests and responses more efficiently (many requests over one connection, compressed headers). The concepts — methods, status codes, headers, bodies — are identical, which is why everything in this chapter applies regardless of version.
Try it: open your browser’s DevTools → Network tab, reload any page, and click a request. You’ll see the method, status, request headers, response headers and body — everything in this lesson, live.
Read real HTTP traffic
Use fetch in Node to request https://httpbin.org/get?course=node. Print the status code, the content-type header, and the parsed JSON body. Then make a POST to https://httpbin.org/post with a JSON body and check what the server says it received.
const res = await fetch('https://httpbin.org/get?course=node');
// your code hereconst res = await fetch('https://httpbin.org/get?course=node');
console.log(res.status, res.headers.get('content-type'));
console.log(await res.json());
const post = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Node.js', level: 'Intermediate' }),
});
const echo = await post.json();
console.log(post.status, echo.json); // { title: 'Node.js', level: 'Intermediate' }Summary
- HTTP is a request–response protocol: the client asks, the server answers, then they’re done.
- A request has a method, a path, headers and an optional body; a response has a status code, headers and an optional body.
- GET reads, POST creates, PUT/PATCH update, DELETE removes; GET, PUT and DELETE are idempotent.
- Status codes: 2xx success, 3xx redirect, 4xx the client’s fault, 5xx the server’s fault.
- HTTP is stateless — anything a server must remember travels in headers such as cookies or tokens.