Sub topic 8
Headers and content types
This chapter assumes you can read a basic HTTP request and response (a start line, headers, a blank line, and a body). It also assumes you know what methods and status codes are. Here you will learn what headers do, which ones matter most, and the mistakes that cause real bugs.
What headers are
A header is a line of the form Name: value placed after the start line of an HTTP message. Headers carry metadata about the message or about the parties exchanging it. They describe the body, state what the client can accept, control caching, and carry credentials.
Four rules cover most of the syntax:
- Header names are case-insensitive.
Content-Typeandcontent-typeare the same header. HTTP/2 and HTTP/3 require lowercase names on the wire. - Header values are mostly case-sensitive, with exceptions. Media types and charset names are compared case-insensitively. Cookie values and ETags are not.
- A blank line ends the headers. Everything after it is the body.
- Some headers may appear more than once. Others must appear only once.
Set-Cookieis the usual multi-line exception, because it cannot be safely joined into one comma-separated line.
Here is a request and a response with their headers.
GET /index.html HTTP/1.1
Host: example.com
Accept: text/html
User-Agent: curl/8.5.0
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 14
<h1>Hello</h1>The response's Content-Length: 14 matches the body exactly. <h1>Hello</h1> is 14 bytes.
Groups of headers
Headers are easier to learn by purpose than as one long list.
| Group | Examples | What it does |
|---|---|---|
| Routing | `Host` | Says which site the request is for |
| Body description | `Content-Type`, `Content-Length`, `Content-Encoding`, `Content-Language` | Describes the payload |
| Negotiation | `Accept`, `Accept-Encoding`, `Accept-Language` | Lets the client state preferences |
| Identity and state | `Cookie`, `Set-Cookie`, `Authorization` | Carries sessions and credentials |
| Caching | `Cache-Control`, `ETag`, `If-None-Match` | Controls reuse of stored responses |
| Redirects | `Location` | Gives the target of a 3xx response |
| Client information | `User-Agent`, `Referer`, `Origin` | Says who is asking and from where |
The following sections cover the ones you will meet most often.
The Host header
Host is the only header HTTP/1.1 requires. One server at one IP address often hosts many sites. The TCP connection only tells the server the IP address, so the Host header tells it which site the client wants. Without it, a server cannot tell example.com from example.org when both share an address. A request without Host gets a 400 Bad Request from an HTTP/1.1 server. In HTTP/2 the same information travels in the :authority pseudo-header.
Content-Type and media types
Content-Type tells the receiver how to interpret the body. Its value is a media type (also called a MIME type), in the form type/subtype, optionally followed by parameters.
| Media type | Used for |
|---|---|
| `text/html` | HTML documents |
| `text/css` | Stylesheets |
| `text/javascript` | JavaScript |
| `application/json` | JSON data |
| `application/x-www-form-urlencoded` | Default HTML form submissions |
| `multipart/form-data` | Forms with file uploads |
| `image/png`, `image/jpeg`, `image/svg+xml` | Images |
| `application/octet-stream` | Arbitrary bytes with no more specific type |
The most common parameter is charset, which names the text encoding. In text/html; charset=utf-8, the body is HTML encoded as UTF-8. If the charset is missing or wrong, accented characters and symbols can turn into garbage such as é instead of é.
Content-Type appears on both requests and responses, because both can have bodies. When your JavaScript sends JSON with POST, it must say so. Many servers parse the body based on this header and ignore it if the type is missing or wrong.
const response = await fetch("https://example.com/api/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "notebook" }),
});
console.log(response.status);
console.log(response.headers.get("content-type"));Why browsers trust the header, not the file name
A browser decides how to treat a response from its Content-Type, not from the URL's extension. A URL ending in .png that is served as text/html is rendered as HTML. A script served as text/plain may be refused. Some browsers also try to guess the type when the header is missing or looks wrong, which is called content sniffing. Sniffing has caused security problems, such as an uploaded "image" that is executed as a script. The X-Content-Type-Options: nosniff response header tells the browser to trust the declared type.
Content-Length and framing
The receiver must know where a body ends. In HTTP/1.1 there are two common ways.
Content-Length: Nsays the body is exactly N bytes.Transfer-Encoding: chunkedsends the body in pieces, each with its own length, which is useful when the server does not know the total size in advance.
Note that Content-Length counts bytes, not characters. The text é is one character but two bytes in UTF-8. A wrong value breaks the connection. If it is too small, the client truncates the body and may read the leftover bytes as the start of the next response. If it is too large, the client waits for bytes that never come. Most servers and frameworks set it for you, so set it by hand only when writing low-level code.
Content negotiation
Negotiation lets one URL return different representations depending on the client's stated preferences.
Acceptlists the media types the client can handle, such asAccept: application/json.Accept-Encodinglists compression schemes, such asgzip, br.Accept-Languagelists preferred languages, such asen-GB, en;q=0.8.
The q value is a weight from 0 to 1. A higher value means a stronger preference, and the default is 1.
The server answers with the choice it made. If it compressed the body, it adds Content-Encoding: gzip. If the response varies by a request header, the server should add a Vary header naming it, for example Vary: Accept-Encoding. Vary tells caches that a stored copy is only valid for requests with the same value in that header. Leaving out Vary can cause a cache to serve a gzip body to a client that cannot decompress it.
curl -s -D - -o /dev/null -H "Accept-Encoding: gzip" https://example.com/This command sends one request header and prints only the response headers. -D - dumps headers to standard output, and -o /dev/null discards the body.
Authorization
Authorization carries credentials, such as Authorization: Bearer <token>. The server reads it, checks it, and answers 401 Unauthorized if it is missing or invalid. Treat this header as a secret. It must only travel over HTTPS, and it must not be written to logs.
Location and redirects
A 301, 302, 303, 307, or 308 response includes Location, the URL the client should request next. The value may be an absolute URL or a path relative to the current one. The status code decides whether the client keeps the method (307 and 308) or may switch to GET (301, 302, and 303 in common practice).
Origin, Referer, and User-Agent
User-Agentnames the client software. Servers should not rely on it for features, because values are inconsistent and easy to fake.Referergives the URL of the page that led to the request. The name is a historical misspelling of "referrer" that is now fixed in the standard. Browsers may trim it for privacy.Origingives the scheme, host, and port that started a request, without a path. Browsers send it on cross-origin requests and on manyPOSTrequests. Servers use it for CORS decisions and for protection against forged requests.
Custom headers
Applications can invent their own headers, such as X-Request-Id for tracing a request across services. The X- prefix was a convention for non-standard headers. Current guidance discourages it, because headers that become standard are then stuck with the prefix. A name without a prefix is fine as long as it does not clash with a registered one.
A server that sets headers
This Node.js server reads one request header and sets two response headers. Run it with node server.mjs.
import { createServer } from "node:http";
const server = createServer((req, res) => {
const accept = req.headers["accept"] ?? "none";
const wantsJson = accept.includes("application/json");
const body = wantsJson
? JSON.stringify({ path: req.url })
: `You asked for ${req.url}\n`;
res.writeHead(200, {
"Content-Type": wantsJson
? "application/json; charset=utf-8"
: "text/plain; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
Vary: "Accept",
});
res.end(body);
});
server.listen(3000);Node lowercases incoming header names, so you read req.headers["accept"]. The code uses Buffer.byteLength rather than body.length, because the first counts bytes and the second counts characters. It adds Vary: Accept, because the response depends on the Accept header.
Test it:
curl -i http://localhost:3000/hello
curl -i -H "Accept: application/json" http://localhost:3000/helloThe second command returns JSON with a JSON content type from the same URL.
Common errors
| Symptom | Likely cause |
|---|---|
| Browser shows raw HTML as text | Response sent as `text/plain` |
| Browser downloads a page instead of showing it | `application/octet-stream` or a `Content-Disposition: attachment` header |
| Garbled accented characters | Missing or wrong `charset` |
| Server ignores a JSON body | Request lacked `Content-Type: application/json` |
| Client hangs waiting for a body | `Content-Length` larger than the actual body |
| Wrong compressed or language version served | Missing `Vary` header |
| Stylesheet or script blocked | Wrong type combined with `nosniff` |
Diagram: headers in an exchange
Exercises
Exercise
A server returns a JSON body with the header Content-Type: text/html. What does the browser do with it, and what is the fix?
Show answer
The browser treats the body as HTML and tries to render it as a page, so the user sees broken or unformatted output instead of data. JavaScript calling response.json() may still parse it, but other consumers may not. The fix is to send Content-Type: application/json; charset=utf-8.
Exercise
A response contains the body Café encoded as UTF-8. What should Content-Length be, and why is it not 4?
Show answer
It should be 5. The letters C, a, and f take one byte each, and é takes two bytes in UTF-8. Content-Length counts bytes, not characters.
Exercise
A server returns gzip-compressed or plain content depending on Accept-Encoding, but a shared cache sometimes sends compressed data to a client that did not ask for it. Which header is missing, and what value should it have?
Show answer
The Vary header is missing. The server should send Vary: Accept-Encoding so the cache stores and matches copies by that request header.