Loading

T9 APIs · Lesson 5

Requests and responses

A request is more than an address, and an answer more than a body. Read every header a request brings, answer one address in several forms, give the client cookies to keep, send files and downloads safely, and answer 304 to a client that already holds the answer.

  • read every header a request carries, and ask req.is what kind of body came with it
  • set several headers on an answer at once, and give one header two values
  • answer one address in several forms with res.format, and say 406 to a form you cannot make
  • set, read and clear cookies, with the options that keep them safe
  • send a file, offer a download under a name of its own, and keep every request inside its folder
  • answer 304 to a client that already holds the answer, with ETags and conditional requests
About 70 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-15); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-15); Express, from npm (the kit compares every Express block with it, in its sandbox; the page runs the small Express of plan 25) 5.3.0 (2026-11-15)Play this lesson's games

The back cover

A parcel is more than its address, and a reply more than its contents. The slip on the outside says what is inside, how to handle it, how long it keeps, and whether the sender already has a copy.

These pages read every note that a request brings and write notes on the answer. They answer one address in several forms, give the client cookies to keep and bring back, and send files and downloads safely. Last, they skip sending a body that the client already holds, with fingerprints and caching rules.

Before you start

The story: Notes on every parcel

Three complaints reach the Yardmaster's desk before breakfast. The Clock Tower asked for the boiler's reading and got a crate of JSON, when it wanted one plain line. The Archive asked for yesterday's ledger to keep, and got it read aloud at the door instead. And the Engine Hall has fetched the same unchanged ledger forty times since dawn.

Every one of those requests said what it wanted, in the notes pinned to its parcel. Nobody at the benches read them.

Yardmaster Waybill taps the bundle of notes on a parcel. "A request is more than an address," she says. "Read every note it carries, and write the right notes on every answer. Learn to read a parcel all the way through."

In lesson 03 you read a request's path, its query and a header or two, and answered with text or JSON. A request carries much more than that. It brings a set of notes, its headers, and many of them say what the client wants: which form of answer it can read, or which copy it already holds.

An answer carries notes back: a cookie to keep, a name to save a file under, a fingerprint to show next time. This lesson reads every part of what comes in, and writes every part of what goes out.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Headers.req.get("x-hall")Every header of a request.
Content-Type.application/jsonAsking what a body is.
Status codes.201, 404, 415406 and 304 join them.
res.set and res.type.res.set("X-Yard", "east")Several headers at once.
How res.send labels a body.res.send("hi") is text/htmlOne address, several forms.
The ETag.W/"d-wEue..."Answers the client already has.
Stateless requests.?page=2Cookies, the client's own notes.
express.static.express.static("public")Sending one file.
The error handler.(err, req, res, next)A file that is missing.
fetch with headers.fetch(url, { headers })Notes sent with a request.

By the end of this lesson you will be able to:

  • read every header a request carries, and ask req.is what kind of body came with it;
  • set several headers on an answer at once, and give one header two values;
  • answer one address in several forms with res.format, and say 406 to a form you cannot make;
  • set, read and clear cookies, with the options that keep them safe;
  • send a file, offer a download under a name of its own, and keep every request inside its folder;
  • answer 304 to a client that already holds the answer, with ETags and conditional requests.

How to follow this lesson

Every block is an Express app and its own client, as in lessons 03 and 04. It runs on the page in the small Node with its small Express, and it has also been run with the real Express 5.3.0 in real Node 22, where it prints the same.

Watch the headers in each block. Some the client writes, some fetch adds by itself, and some Express adds to the answer. The output shows which is which.

In one line

A request and its answer each carry headers, notes that say what the client wants and what the server sends back; this lesson reads them all and writes them all.

Headers in both directions

At a glance

A request has three parts: the first line, the headers and sometimes a body. Much of its meaning hides in the middle part.

A request brings the headers that its client wrote, and others that fetch added without being asked. The call req.get reads any one of them, req.rawHeaders shows them exactly as they came, and req.is asks what kind of body arrived. On the answer, res.set sets headers, one or several at once, and res.append adds a second value to a header that already has one.

Take a guess: Should a header of your own still start with X-?

A request has three parts. The first line holds the method and the address. Then come the headers, and last, sometimes, a body. You have used the first part and the last. The middle part is where much of a request's meaning hides.

A header is one note: a name, a colon and a value, such as Content-Type: application/json. The client writes some headers itself, and fetch adds others without being asked. This server prints every header that arrives, exactly as it arrived:

app.js

const express = require("express");
const app = express();
app.post("/readings", (req, res) => {
  for (let i = 0; i < req.rawHeaders.length; i += 2) {
    console.log(req.rawHeaders[i] + ":", req.rawHeaders[i + 1]);
  }
  res.sendStatus(204);
});
const server = app.listen(3000, async () => {
  await fetch("http://localhost:3000/readings", {
    method: "POST",
    headers: { "Content-Type": "text/plain", "X-Hall": "engine" },
    body: "boiler 95",
  });
  server.close();
});

Terminal: node app.js

host: localhost:3000
connection: keep-alive
Content-Type: text/plain
X-Hall: engine
accept: */*
accept-language: *
sec-fetch-mode: cors
user-agent: node
accept-encoding: gzip, deflate
content-length: 9

The client wrote two headers, Content-Type and X-Hall, and they kept the capital letters we gave them. The other eight came from fetch, which writes its names in small letters.

req.rawHeaders is the list of headers as they arrived, in their order: a name, then its value, then the next name. That is why the loop steps by two.

Header that fetch addedIts value hereWhat it tells the server
hostlocalhost:3000which name and port the client asked for; one machine can answer for many names
connectionkeep-alivekeep the line open for the next request
accept*/*which forms of answer the client takes; */* means any (the next section)
accept-language*which languages the client reads; * means any
sec-fetch-modecorshow the request was made, a note that browsers add and fetch copies
user-agentnodewhich program sent the request
accept-encodinggzip, deflatewhich ways of squeezing a body the client can undo
content-length9the body's size in bytes: boiler 95 is nine characters

Header names do not care about case: Content-Type and content-type name the same header. Node keeps each name as it came in req.rawHeaders, but req.headers is an object whose keys are all in small letters. req.get(name) finds a header whatever case you write:

You writeYou get
req.get("X-Hall") or req.get("x-hall")engine
req.headers["x-hall"]engine
req.headers["X-Hall"]undefined, because the keys of req.headers are in small letters

What kind of body is it? req.is

A body arrives with its label, the Content-Type header. req.is(kinds) compares that label with a list of kinds. It answers with the first kind that matches, or false when none does. It saves you reading the header and comparing strings by hand:

app.js

const express = require("express");
const app = express();
app.post("/readings", (req, res) => {
  const kind = req.is(["json", "text", "urlencoded"]);
  console.log(req.get("content-type"), "->", kind);
  res.sendStatus(kind ? 202 : 415);
});
app.get("/readings", (req, res) => {
  console.log("a GET with no body ->", req.is("json"));
  res.sendStatus(200);
});
const server = app.listen(3000, async () => {
  const bodies = [
    ["application/json", '{"value":95}'],
    ["text/plain", "boiler 95"],
    ["application/x-www-form-urlencoded", "value=95"],
    ["image/png", "not really a picture"],
  ];
  for (const [type, body] of bodies) {
    const r = await fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": type }, body });
    console.log("client:", r.status);
  }
  await fetch("http://localhost:3000/readings");
  server.close();
});

Terminal: node app.js

application/json -> json
client: 202
text/plain -> text
client: 202
application/x-www-form-urlencoded -> urlencoded
client: 202
image/png -> false
client: 415
a GET with no body -> null

Each short name stands for a full type: json for application/json, text for text/plain, urlencoded for a form's body. req.is gave back the short name that matched. The picture matched none of the three, so req.is said false and the server answered 415, the status from lesson 02 for a body it cannot read.

The last line is a GET with no body at all. There was nothing to compare, and req.is answered null.

The requestreq.is(["json", "text"]) answers
a body labelled application/jsonjson
a body labelled text/plaintext
a body labelled text/csvfalse, because text means text/plain only
no body at allnull

Notes on the answer: res.set and res.append

An answer carries headers too. You met res.set in lesson 03 with one name and one value. Given an object, it sets several headers at once. And res.append adds a value to a header that already has one, where res.set would replace it:

app.js

const express = require("express");
const app = express();
app.get("/gauges/boiler", (req, res) => {
  res.set({ "X-Hall": "engine", "Cache-Control": "no-store" });
  res.append("X-Checked-By", "stoker");
  res.append("X-Checked-By", "clerk");
  res.json({ value: 95 });
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges/boiler");
  for (const name of ["x-hall", "cache-control", "x-checked-by", "content-type"]) {
    console.log(name + ":", r.headers.get(name));
  }
  server.close();
});

Terminal: node app.js

x-hall: engine
cache-control: no-store
x-checked-by: stoker, clerk
content-type: application/json; charset=utf-8

The two calls to res.append gave X-Checked-By two values. They travel as two separate lines, and on the client r.headers.get joined them with a comma and a space.

Cache-Control: no-store is a real instruction, not a made-up note. It asks every cache never to keep this answer; the caching section comes back to it.

CallWhat it does
res.set(name, value)sets one header, replacing any value it had
res.set({ name: value, ... })sets several headers at once
res.append(name, value)adds a value, so a header can carry two or more
res.get(name)reads back a header that is already set

Worked example 1

Take a reading as JSON or as plain text, and refuse any other kind of body with 415 and a message that says which kinds are welcome.

What we have: a POST route for /readings, with express.json and express.text to read the two kinds of body

What we need: 201 and the value for a JSON body and for a text body, and 415 for a CSV body

The plan: ask req.is(["json", "text"]) first; if it answers false, send 415 at once; otherwise read the value from whichever kind of body arrived

app.js

const express = require("express");
const app = express();
app.use(express.json());
app.use(express.text());
app.post("/readings", (req, res) => {
  if (!req.is(["json", "text"])) {
    return res.status(415).json({ error: "send application/json or text/plain", got: req.get("content-type") });
  }
  const value = typeof req.body === "string" ? Number(req.body.split(" ")[1]) : req.body.value;
  res.status(201).json({ saved: value });
});
const server = app.listen(3000, async () => {
  const send = (type, body) => fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": type }, body });
  const answers = [await send("application/json", '{"value":95}'), await send("text/plain", "boiler 96"), await send("text/csv", "boiler,97")];
  for (const r of answers) console.log(r.status, await r.text());
  server.close();
});

Terminal: node app.js

201 {"saved":95}
201 {"saved":96}
415 {"error":"send application/json or text/plain","got":"text/csv"}
  1. req.is answered json and then text for the first two bodies, so the route went on to read them.
  2. A text body arrives as a string, so the route took the number after the space. A JSON body arrives as an object, so the route read its value.
  3. text/csv is not text/plain, so req.is answered false, and the route sent 415 before reading anything.

The three answers are 201 {"saved":95}, 201 {"saved":96} and 415 with the message.

Check: The CSV body never reached the line that reads a value, and the 415 told the client what to send instead.

Another way: move the check into a middleware that every POST route shares, so that each route starts with a body it can read.

A path that fails: checking req.body instead of asking req.is. A CSV body leaves req.body undefined, so the route would crash on req.body.value with a TypeError: a 500, instead of a helpful 415.

When you are stuck: A header comes back undefined

Is the name in small letters? The keys of req.headers are: write req.headers["x-hall"], or req.get("X-Hall"), which ignores case.

Did the client send it at all? Print req.rawHeaders on the server: it lists every header that arrived.

Is it in the answer? On the client, print [...r.headers] to list every header the answer brought.

Your turn

Which header tells the server how many bytes the body holds, and who wrote it in our first block?Tap to reveal
  1. The client wrote only two headers itself.

Content-Length, which fetch added: it counts the body's bytes.

A GET request has no body. What does req.is("json") answer?Tap to reveal
  1. There is nothing to compare.

null.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res) => {
  res.append("X-Step", "one");
  res.append("X-Step", "two");
  res.send(req.get("HOST") + " " + req.headers["user-agent"]);
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(r.headers.get("x-step"), "|", await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
one, two | localhost:3000 node
  1. res.append gives X-Step two values, and the client joins them with a comma.
  2. req.get ignores case, and Host holds the name and the port.

It prints one, two | localhost:3000 node.

Did you know?

The X- prefix, retired

Made-up headers often start with X-, such as X-Yard. That habit was retired in June 2012. RFC 6648 says that the convention causes more problems than it solves, and deprecates it for new names. Its analysis gives the main problem: unstandardized names tend to leak into the standards, and then must migrate from the X- name to a standard one.

Why it fits here: It answers this topic's question: since RFC 6648 of 2012, new header names should not start with X-.

Source: RFC 6648: Deprecating the X- Prefix and Similar Constructs in Application Protocols

Headers after the body

Not every header comes first. HTTP allows a trailer section after the body, and RFC 9110 calls its fields trailer fields, or trailers. It says that they can carry message integrity checks, digital signatures, delivery metrics or post-processing status, things that a sender may know only once the whole body has gone.

Why it fits here: It adds to this topic's headers: trailers are headers sent after the body, for facts known only at the end.

Source: RFC 9110: HTTP Semantics

In one line

A request brings the headers its client wrote and the ones fetch added. Read any of them with req.get, see them as they came in req.rawHeaders, and ask req.is what the body is. On the answer, res.set sets headers, one or several at once, and res.append adds a second value.

One address, several forms

At a glance

One address can answer in several forms, such as JSON for a program and HTML for a person. The client says which it wants.

It lists the types it takes in the header Accept, each with a weight q that says how much it wants it. On the server, res.format runs the function for the best match, sets Content-Type and adds Vary: Accept. It needs a default, or it answers 406 Not Acceptable itself. The call req.accepts only asks which type would win, and answers nothing.

Take a guess: Must a server answer 406 when it has no form the client asked for?

The same reading can be written in several forms: JSON for a program, one plain line for a person at a terminal, HTML for a browser. In lesson 01, one address named one resource. So the boiler's gauge should not need three addresses for its three forms.

Instead, the client says which forms it can read, and the server picks one of them. This is called content negotiation: the two sides agree on the form of the answer.

The client says it in the Accept header, a list of the types it takes. fetch sends */* unless you write your own, and */* means any type at all.

On the server, res.format(object) takes an object whose keys are types and whose values are functions. It runs the function for the type that the client wants most:

app.js

const express = require("express");
const app = express();
app.get("/gauges/boiler", (req, res) => {
  res.format({
    "application/json": () => res.json({ name: "boiler", value: 95 }),
    "text/plain": () => res.send("boiler 95"),
    "text/html": () => res.send("<p>boiler <b>95</b></p>"),
    default: () => res.status(406).json({ error: "we answer in JSON, plain text or HTML" }),
  });
});
const server = app.listen(3000, async () => {
  for (const accept of ["application/json", "text/plain", "text/html", "*/*", "image/png"]) {
    const r = await fetch("http://localhost:3000/gauges/boiler", { headers: { Accept: accept } });
    console.log(accept, "->", r.status, r.headers.get("content-type"));
    console.log("  ", await r.text());
  }
  server.close();
});

Terminal: node app.js

application/json -> 200 application/json; charset=utf-8
   {"name":"boiler","value":95}
text/plain -> 200 text/plain; charset=utf-8
   boiler 95
text/html -> 200 text/html; charset=utf-8
   <p>boiler <b>95</b></p>
*/* -> 200 application/json; charset=utf-8
   {"name":"boiler","value":95}
image/png -> 406 application/json; charset=utf-8
   {"error":"we answer in JSON, plain text or HTML"}

Read the lines in pairs. The client asked for JSON, plain text and HTML in turn, and got each one with the matching Content-Type. With */*, every key matched, so res.format took the first one, JSON. That is why the key you write first is the answer for a client that does not say.

No key matched image/png, so the function under default ran and answered 406 Not Acceptable. 406 means the server has no form of this resource that the client said it would take.

Several wishes at once: q

An Accept header can name several types, each with a weight called q, from 0 to 1, that says how much the client wants it. A type written without q has a q of 1.

res.format picks the type with the highest q among those it can make. Among equal weights, the more exact match wins, then the order the client wrote them in, then the order of your keys:

app.js

const express = require("express");
const app = express();
app.get("/gauges/boiler", (req, res) => {
  res.format({
    "application/json": () => res.json({ value: 95 }),
    "text/plain": () => res.send("boiler 95"),
  });
});
const server = app.listen(3000, async () => {
  const accepts = ["text/plain;q=0.5, application/json", "application/json;q=0.2, text/plain", "image/png, text/*", "text/html, */*;q=0.1"];
  for (const accept of accepts) {
    const r = await fetch("http://localhost:3000/gauges/boiler", { headers: { Accept: accept } });
    console.log(JSON.stringify(accept), "->", r.headers.get("content-type"), "| vary:", r.headers.get("vary"));
  }
  server.close();
});

Terminal: node app.js

"text/plain;q=0.5, application/json" -> application/json; charset=utf-8 | vary: Accept
"application/json;q=0.2, text/plain" -> text/plain; charset=utf-8 | vary: Accept
"image/png, text/*" -> text/plain; charset=utf-8 | vary: Accept
"text/html, */*;q=0.1" -> application/json; charset=utf-8 | vary: Accept

Take the four lines one by one. In the first, JSON has q 1 and plain text q 0.5, so JSON wins. The second is the other way round. In the third, this server cannot make image/png, but text/* means any text type, and text/plain is one. In the fourth, the server has no HTML; */* with its low q matches both keys, and the first key, JSON, wins.

A browser sends a list like the fourth: its page types first, then */* with a low q, so that it still gets something it can show.

Every answer carried Vary: Accept, which res.format adds by itself. It is a warning for caches: the answer at this address varies with the Accept header. A cache that kept the JSON must not hand it to a client that asked for text.

Asking without answering: req.accepts

res.format asks and answers in one call. To ask only, use req.accepts(types): it answers with the best type of your list for this client, or false if none will do. Like req.is, it understands short names:

app.js

const express = require("express");
const app = express();
app.get("/", (req, res) => res.json({ best: req.accepts(["json", "html"]), csv: req.accepts("text/csv") }));
const server = app.listen(3000, async () => {
  for (const accept of ["*/*", "text/html", "text/html;q=0.9, application/json", "image/png"]) {
    const r = await fetch("http://localhost:3000/", { headers: { Accept: accept } });
    console.log(JSON.stringify(accept), await r.text());
  }
  server.close();
});

Terminal: node app.js

"*/*" {"best":"json","csv":"text/csv"}
"text/html" {"best":"html","csv":false}
"text/html;q=0.9, application/json" {"best":"json","csv":false}
"image/png" {"best":false,"csv":false}

With */*, the first type of the list won, json. A short name came back short, and a full type, text/csv, came back full. A browser's text/html chose html, and image/png matched nothing, so both answers were false.

If you choose the form yourself with req.accepts, add res.vary("Accept") so that caches know; res.format does it for you.

ToolWhat it doesWhat you get
the Accept headerthe client's list of types it takes, with q weightssent with the request; fetch sends */*
req.accepts(list)asks which of your types suits this clientthe best type, or false
res.format({ type: fn })asks, then runs the function for the chosen typeContent-Type and Vary: Accept set for you
default: fnruns when no key suits the clientyour own 406; without it, Express's HTML 406 page

Worked example 2

Offer the readings as JSON to programs, and as CSV, the comma-separated text that spreadsheets open, to anyone who asks for text/csv.

What we have: a list of two readings, and a client that asks once with fetch's own Accept and once with Accept: text/csv

What we need: the JSON list for */*, and a header line plus one line per reading for text/csv

The plan: res.format with application/json first, so that a client that does not say gets JSON, and a text/csv key that builds the lines with map and join

app.js

const express = require("express");
const app = express();
const readings = [{ gauge: "boiler", value: 95 }, { gauge: "fan", value: 40 }];
app.get("/readings", (req, res) => {
  res.format({
    "application/json": () => res.json(readings),
    "text/csv": () => res.send("gauge,value\n" + readings.map((r) => `${r.gauge},${r.value}`).join("\n")),
  });
});
const server = app.listen(3000, async () => {
  for (const accept of ["*/*", "text/csv"]) {
    const r = await fetch("http://localhost:3000/readings", { headers: { Accept: accept } });
    console.log("Accept:", accept, "->", r.headers.get("content-type"));
    console.log(await r.text());
  }
  server.close();
});

Terminal: node app.js

Accept: */* -> application/json; charset=utf-8
[{"gauge":"boiler","value":95},{"gauge":"fan","value":40}]
Accept: text/csv -> text/csv; charset=utf-8
gauge,value
boiler,95
fan,40
  1. The first request sent */*, so the first key, JSON, answered.
  2. The second asked for text/csv. res.format set Content-Type to text/csv, and res.send added the charset, as it does for every string.
  3. Each reading became one line: map turned each object into its gauge and value with a comma between, and join put a newline between the lines.

JSON for */*, and three lines of CSV, starting with gauge,value, for text/csv.

Check: The same address gave two forms of the same two readings; only the Accept header changed.

Another way: also accept ?format=csv in the query, for a link that a person clicks, where nobody can choose the Accept header.

A path that fails: putting text/csv first. Then fetch's */* would get CSV, and every program that did not ask would receive text it cannot read as JSON.

Worked example 3

Choose the form by hand: answer a browser with a small HTML page, every other client with JSON, and warn caches that the answer depends on Accept.

What we have: a gauge, a client that sends an Accept header like a browser's, and one that sends fetch's own */*

What we need: HTML for the browser's list, JSON for */*, and Vary: Accept on both answers

The plan: set Vary with res.vary("Accept") first; ask req.accepts(["json", "html"]); send HTML when it answers html, and JSON otherwise

app.js

const express = require("express");
const app = express();
const gauge = { name: "boiler", value: 95 };
app.get("/gauges/boiler", (req, res) => {
  res.vary("Accept");
  if (req.accepts(["json", "html"]) === "html") {
    return res.send(`<h1>${gauge.name}</h1><p>${gauge.value}</p>`);
  }
  res.json(gauge);
});
const server = app.listen(3000, async () => {
  const browser = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  for (const accept of [browser, "*/*"]) {
    const r = await fetch("http://localhost:3000/gauges/boiler", { headers: { Accept: accept } });
    console.log(r.headers.get("content-type"), "| vary:", r.headers.get("vary"));
    console.log("  ", await r.text());
  }
  server.close();
});

Terminal: node app.js

text/html; charset=utf-8 | vary: Accept
   <h1>boiler</h1><p>95</p>
application/json; charset=utf-8 | vary: Accept
   {"name":"boiler","value":95}
  1. The browser's list puts text/html first, with q 1, and */* last, with q 0.8, so req.accepts chose html.
  2. fetch's */* matched both kinds equally, so the first of the list, json, won.
  3. Vary: Accept came from res.vary; without that line, the hand-made choice would carry no warning for caches.

text/html for the browser and application/json for */*, both with Vary: Accept.

Check: Each client got a form from its own list, and both answers told caches why they differ.

Another way: the same with res.format and two keys, application/json first and text/html second, which sets Vary for you.

A path that fails: putting html first in the list given to req.accepts. Then */* would choose html, and programs that did not ask would get a page instead of JSON.

When you are stuck: The wrong form comes back, or a 406

What did the client send in Accept? fetch sends */* unless you set it, and */* takes your first key.

Is the type spelled as the client spells it? text/csv and text/plain are different types; text/* covers both.

A 406 in Express's HTML page means that no key matched and there was no default. Add a default that answers 406 in JSON.

Your turn

A client sends Accept: application/json;q=0.5, text/plain. res.format has the keys application/json and text/plain. Which function runs?Tap to reveal
  1. A type written without q has q 1.

text/plain: its q of 1 beats 0.5.

Which header does res.format add to every answer, and why?Tap to reveal
  1. It is a warning for caches.

Vary: Accept: the answer depends on the Accept header, so a cache must not give one client's form to another.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send(String(req.accepts(["html", "json"]))));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/", { headers: { Accept: "application/json, text/html;q=0.8" } });
  console.log(await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
json
  1. application/json has q 1; text/html has q 0.8.
  2. req.accepts answers with the short name you gave it.

It prints json.

Did you know?

406, or something useful

A server need not answer 406. RFC 9110 says that when none of the available forms is acceptable, the origin server can either honor the header by sending 406 Not Acceptable, or disregard it and answer as if no negotiation had been asked for. A default in res.format makes the second choice: a form the client did not list, rather than nothing.

Why it fits here: It answers this topic's question: the standard lets a server skip 406 and send a form the client did not ask for.

Source: RFC 9110: HTTP Semantics

The rules of q

The weight q has firm rules. RFC 9110 says it runs from 0 to 1, where 0.001 is the least preferred and 1 the most, and that q=0 means not acceptable at all. A type with no q has the weight 1. Its grammar allows at most three digits after the point, so q=0.0001 is not a weight at all.

Why it fits here: It sharpens this topic's q: weights run from 0 to 1 with three decimals at most, and q=0 refuses a type.

Source: RFC 9110: HTTP Semantics

In one line

One address can answer in several forms. The client lists the types it takes in Accept, with q for how much; res.format runs the function for the best one, sets Content-Type and Vary: Accept, and needs a default for its own 406; req.accepts only asks.

Cookies: a note the client brings back

At a glance

A cookie is a small note that a server asks the client to keep, and to bring back with every request. The server writes it once, and the client carries it from then on.

The call res.cookie writes the header Set-Cookie, with options such as HttpOnly, Secure, SameSite and Max-Age. The client sends the note back in the header Cookie, which req.get("cookie") reads, and res.clearCookie asks the client to delete it. A cookie lives on the client's side, and a client can change it, so a server never trusts a cookie alone.

Take a guess: Can a cookie's name itself promise that it is safe?

In lesson 01 you learned that HTTP is stateless: each request carries all it needs, and the server keeps no memory of the last one. Yet a site remembers that you signed in, and a shop remembers your basket. How?

The server gives the client a small note to keep, and the client brings it back with every later request to that server. The note is called a cookie: a name and a value, such as theme=dark.

The server hands a cookie over in a Set-Cookie header on its answer. res.cookie(name, value, options) writes that header for you, one Set-Cookie line for each call:

app.js

const express = require("express");
const app = express();
app.get("/visit", (req, res) => {
  res.cookie("hall", "engine");
  res.cookie("courier", "c-17", { httpOnly: true, sameSite: "lax" });
  res.send("welcome");
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/visit");
  for (const line of r.headers.getSetCookie()) console.log("Set-Cookie:", line);
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

Set-Cookie: hall=engine; Path=/
Set-Cookie: courier=c-17; Path=/; HttpOnly; SameSite=Lax
welcome

Two calls made two Set-Cookie headers. On the client, r.headers.getSetCookie() gives them as a list, one cookie for each item. Each line starts with name=value, then the cookie's options, separated by semicolons.

Express added Path=/ to both. That asks the client to send the cookie back for every path on this server.

Option in res.cookieWritten asWhat it means
(none)Path=/send it back for every path on this server
httpOnly: trueHttpOnlythe page's own scripts cannot read it; it is only sent to the server
secure: trueSecuresend it back only over HTTPS, never over plain HTTP
sameSite: "lax" or "strict"SameSite=Lax or Strictwhether it rides along with requests that start on other sites
maxAge: 60000Max-Age=60 and Expireshow long to keep it; without it, it goes when the browser closes
path: "/ledger"Path=/ledgersend it back only for /ledger and the paths below it

Here is each option at work, and res.clearCookie(name), which deletes a cookie. The block replaces the first cookie's date with words, because the real date is one minute after the moment the block runs, and would differ every time:

app.js

const express = require("express");
const app = express();
app.get("/options", (req, res) => {
  res.cookie("note", "kept a minute", { maxAge: 60000 });
  res.cookie("pass", "p-9", { secure: true, httpOnly: true, sameSite: "strict", path: "/ledger" });
  res.cookie("prefs", { theme: "dark" });
  res.clearCookie("old");
  res.sendStatus(204);
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/options");
  for (const line of r.headers.getSetCookie()) {
    console.log(line.includes("Max-Age") ? line.replace(/Expires=.*GMT/, "Expires=(one minute from now)") : line);
  }
  server.close();
});

Terminal: node app.js

note=kept%20a%20minute; Max-Age=60; Path=/; Expires=(one minute from now)
pass=p-9; Path=/ledger; HttpOnly; Secure; SameSite=Strict
prefs=j%3A%7B%22theme%22%3A%22dark%22%7D; Path=/
old=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT

Look at each line. maxAge is in milliseconds in Express, but Max-Age is in seconds on the wire, so 60000 became 60. A value with a space is encoded, so the space became %20. An object became j: and its JSON, encoded the same way.

The last line is res.clearCookie at work. It sends the cookie again, empty, with an expiry date in 1970. A client deletes a cookie whose time has passed, so the old cookie is gone.

Bringing it back

Now the other half of the trip. A browser keeps cookies by itself and sends them back in a Cookie header. Node's fetch keeps no cookies, so our client does the browser's job by hand: it takes name=value from Set-Cookie and sends it back.

On the server, the Cookie header is one plain string, such as courier=c-17; hall=engine. A small function splits it into names and values:

app.js

const express = require("express");
const app = express();
function readCookies(req) {
  const jar = {};
  for (const part of (req.get("cookie") ?? "").split(";")) {
    const [name, ...rest] = part.trim().split("=");
    if (name) jar[name] = decodeURIComponent(rest.join("="));
  }
  return jar;
}
app.get("/visit", (req, res) => {
  const jar = readCookies(req);
  if (jar.courier) return res.send(`welcome back, ${jar.courier}`);
  res.cookie("courier", "c-17", { httpOnly: true });
  res.send("welcome, new courier");
});
const server = app.listen(3000, async () => {
  const first = await fetch("http://localhost:3000/visit");
  console.log(await first.text());
  const note = first.headers.getSetCookie()[0].split(";")[0];
  console.log("the client keeps:", note);
  const second = await fetch("http://localhost:3000/visit", { headers: { Cookie: note } });
  console.log(await second.text());
  server.close();
});

Terminal: node app.js

welcome, new courier
the client keeps: courier=c-17
welcome back, c-17

readCookies splits the header at each semicolon, trims the spaces, and splits each part at its first equals sign. decodeURIComponent undoes the encoding, so %20 becomes a space again.

The first visit had no cookie, so the server set one. The second brought it back, and the server recognised the courier. The npm package cookie-parser does the same splitting and puts the result in req.cookies; without it, req.cookies is undefined.

Worked example 4

Count a client's visits without the server remembering anything: keep the count in a cookie, and add one on every visit.

What we have: a route that reads visits from the Cookie header, and a client that sends back the cookie it was given each time

What we need: visit numbers 1, 2 and 3, and what happens when a client changes its cookie

The plan: find visits in the Cookie header with a regular expression, add one, set the new number with res.cookie, and answer with it

app.js

const express = require("express");
const app = express();
app.get("/", (req, res) => {
  const match = (req.get("cookie") ?? "").match(/visits=(\d+)/);
  const visits = (match ? Number(match[1]) : 0) + 1;
  res.cookie("visits", String(visits));
  res.send(`visit number ${visits}`);
});
const server = app.listen(3000, async () => {
  let cookie = null;
  for (let i = 0; i < 3; i++) {
    const r = await fetch("http://localhost:3000/", { headers: cookie ? { Cookie: cookie } : {} });
    cookie = r.headers.getSetCookie()[0].split(";")[0];
    console.log(await r.text(), "| the client keeps", cookie);
  }
  const forged = await fetch("http://localhost:3000/", { headers: { Cookie: "visits=999" } });
  console.log(await forged.text(), "| a client that changed its cookie");
  server.close();
});

Terminal: node app.js

visit number 1 | the client keeps visits=1
visit number 2 | the client keeps visits=2
visit number 3 | the client keeps visits=3
visit number 1000 | a client that changed its cookie
  1. The first request had no cookie, so match was null, the count started at 0, and became 1.
  2. Each answer set visits to the new number, and the client sent that back the next time.
  3. The server stored nothing between the requests; the count travelled with the client.
  4. The last client wrote visits=999 into its own Cookie header, and the server believed it.

visit number 1, 2 and 3, then 1000 for the client that changed its cookie.

Check: The count rose by one with each request, and only the cookie carried it from one request to the next.

Another way: keep the count on the server, in an object under a long random id, and put only the id in the cookie. Then a client can change nothing but which id it shows.

A path that fails: trusting a cookie for anything that matters, such as visits=999 or admin=yes. The client holds the cookie and can write any value into it. A cookie that must be trusted holds only an id, or is signed.

When you are stuck: The cookie does not come back

Is anything keeping it? A browser does; Node's fetch does not, so send it back yourself in a Cookie header.

Does its Path cover the address? A cookie with Path=/ledger is not sent for /gauges.

Are you reading req.cookies? It is undefined unless the cookie-parser package fills it; read req.get("cookie") instead.

Your turn

Which header carries a cookie from the server to the client, and which carries it back?Tap to reveal
  1. One is on the answer, the other on the request.

Set-Cookie on the answer; Cookie on the request.

res.cookie("note", "x", { maxAge: 120000 }) writes Max-Age equal to what?Tap to reveal
  1. maxAge is in milliseconds; Max-Age is in seconds.

Max-Age=120.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res) => {
  res.cookie("theme", "dark", { httpOnly: true });
  res.clearCookie("old");
  res.end();
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(r.headers.getSetCookie().length, r.headers.getSetCookie()[0]);
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2 theme=dark; Path=/; HttpOnly
  1. res.clearCookie writes a Set-Cookie line too.
  2. Express adds Path=/ before the HttpOnly option.

It prints 2 theme=dark; Path=/; HttpOnly.

Did you know?

Names that carry a promise

A cookie's name can carry a promise. Under the draft revision of the cookie standard, a cookie whose name begins with __Host- is accepted only if it was set with Secure, with Path=/ and with no Domain. MDN explains the gain: such a cookie is sent only to the host that set it, never to other hosts of the same domain.

Why it fits here: It answers this topic's question: a name that begins with __Host- promises Secure, Path=/ and no Domain.

Sources: IETF draft: Cookies: HTTP State Management Mechanism (rfc6265bis); IETF Datatracker: draft-ietf-httpbis-rfc6265bis; MDN: Set-Cookie

Max-Age wins

A cookie may carry both an age and a date. RFC 6265 says that if a cookie has both Max-Age and Expires, Max-Age has precedence and controls when it expires. A cookie with neither is kept until the current session is over, as the browser defines it, which usually means until the browser closes.

Why it fits here: It adds to this topic's options: when Max-Age and Expires disagree, Max-Age decides.

Source: RFC 6265: HTTP State Management Mechanism

In one line

A cookie is a small note the server asks the client to keep. The call res.cookie writes Set-Cookie, with options such as HttpOnly, Secure, SameSite and Max-Age. The client sends it back in Cookie, which req.get("cookie") reads, and res.clearCookie deletes it. A client can change a cookie, so never trust it alone.

Files and downloads

At a glance

Some answers are files: a receipt, a report, a picture. Express sends them in one call.

The call res.sendFile(name, { root }) sends one file from the folder root, with a type from its extension. The calls res.download and res.attachment add the header Content-Disposition: attachment, so the browser saves the body under a name instead of showing it. With root, a name that tries to climb out with .. gets 403, and a missing file or a dot-file gets 404, both sent to the error handler.

Take a guess: Can a download's file name be written in Hindi?

In lesson 04, express.static served a whole folder. Sometimes one route must send one file: a report, a picture, a ledger to download.

res.sendFile(name, { root }) sends one file. res.download(path, name) sends it as a download, under a name of its own. Here is a CSV file in a folder called files, sent both ways:

files/readings.csv

gauge,value
boiler,95
fan,40

app.js

const express = require("express");
const app = express();
app.get("/readings", (req, res) => res.sendFile("readings.csv", { root: "files" }));
app.get("/readings/download", (req, res) => res.download("files/readings.csv", "boiler-readings.csv"));
const server = app.listen(3000, async () => {
  for (const path of ["/readings", "/readings/download"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, r.status);
    console.log("  type:", r.headers.get("content-type"));
    console.log("  length:", r.headers.get("content-length"));
    console.log("  disposition:", r.headers.get("content-disposition"));
    console.log("  body:", JSON.stringify(await r.text()));
  }
  server.close();
});

Terminal: node app.js

/readings 200
  type: text/csv; charset=utf-8
  length: 29
  disposition: null
  body: "gauge,value\nboiler,95\nfan,40\n"
/readings/download 200
  type: text/csv; charset=utf-8
  length: 29
  disposition: attachment; filename=boiler-readings.csv
  body: "gauge,value\nboiler,95\nfan,40\n"

Both answers carried the same 29 bytes, with the type text/csv, which Express chose from the file's extension, .csv. They differ in one header.

The download added Content-Disposition: attachment; filename=boiler-readings.csv. Content-Disposition tells a browser what to do with the body. Attachment means: save it as a file, under that name, instead of showing it in the page.

The root option names the folder, and the file name is looked for inside it. Without root, res.sendFile needs an absolute path, one that starts at the top of the disk with /. The mistakes section shows what happens otherwise.

res.download needs neither: it takes a path from the folder the program runs in, as fs does.

Keeping every request inside its folder

A route that takes the file's name from the address is handy, and dangerous. A client could ask for ../app.js and read your server's own code, or a file that holds a password.

With root, res.sendFile refuses any name that climbs out of the folder. Here the folder holds the readings and a hidden file, .secret:

files/readings.csv

gauge,value
boiler,95
fan,40

files/.secret

key=brass

app.js

const express = require("express");
const app = express();
app.get("/files/:name", (req, res) => res.sendFile(req.params.name, { root: "files" }));
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ status: err.status, code: err.code ?? null }));
const server = app.listen(3000, async () => {
  for (const path of ["/files/readings.csv", "/files/nothing.csv", "/files/..%2Fapp.js", "/files/.secret"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, r.status, (await r.text()).split("\n")[0]);
  }
  server.close();
});

Terminal: node app.js

/files/readings.csv 200 gauge,value
/files/nothing.csv 404 {"status":404,"code":"ENOENT"}
/files/..%2Fapp.js 403 {"status":403,"code":null}
/files/.secret 404 {"status":404,"code":null}

%2F is a slash written in code, so that it stays inside one part of the address; Express decodes it, and req.params.name was ../app.js. res.sendFile did not send that file. It passed an error with status 403, which means Forbidden, to the error handler.

A file that is not there gave an error with status 404 and the code ENOENT, short for error, no entry: no such file or folder. And .secret, a name that starts with a dot, counted as missing, so it got a 404 too. Each error went to the error handler from lesson 04, which answered in JSON.

The client asks forres.sendFile with root
a file in the foldersends it: 200
a file that is not therepasses an error with status 404 and code ENOENT
a name with .. that leaves the folderpasses an error with status 403
a name that starts with a dot, such as .secretpasses an error with status 404

Building the path yourself

A route that joins the folder and req.params.name into one path and passes it without root loses this protection. Keep the folder in root, and pass only the name.

Worked example 5

Offer today's readings as a download, report-2026-11-15.csv, built from data in memory: there is no file on the disk to send.

What we have: a list of two readings in the program

What we need: an answer that a browser saves under that name, with the type text/csv

The plan: res.attachment(name) sets Content-Disposition and, from the name's extension, the Content-Type; then res.send sends the text built with map and join

app.js

const express = require("express");
const app = express();
const readings = [{ gauge: "boiler", value: 95 }, { gauge: "fan", value: 40 }];
app.get("/report", (req, res) => {
  res.attachment("report-2026-11-15.csv");
  res.send("gauge,value\n" + readings.map((r) => `${r.gauge},${r.value}`).join("\n"));
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/report");
  console.log(r.status, r.headers.get("content-type"));
  console.log(r.headers.get("content-disposition"));
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

200 text/csv; charset=utf-8
attachment; filename=report-2026-11-15.csv
gauge,value
boiler,95
fan,40
  1. res.attachment wrote attachment; filename=report-2026-11-15.csv.
  2. It also set the Content-Type from .csv, and res.send added the charset.
  3. No file was read or written: the body came straight from the list.

200 text/csv, saved as report-2026-11-15.csv, with three lines of CSV.

Check: The body has the header line and one line for each reading, as in the CSV example of the last section.

Another way: if the report were already a file on the disk, res.download(path, name) would do the same in one call.

A path that fails: calling res.download with a name that is not a file on the disk. It needs a real path, and here it would answer 404; build the text and use res.attachment and res.send instead.

When you are stuck: A file will not send

A TypeError about an absolute path? Give root, or an absolute path: res.sendFile("readings.csv", { root: "files" }).

A 404? The name is looked for inside root: check the folder, the spelling and the extension. A name that starts with a dot counts as missing.

A 403? The name climbed out of the folder with .. ; that is the protection doing its job.

Your turn

Which header makes a browser save the body as a file, and what does its value say?Tap to reveal
  1. Two parts of its value matter.

Content-Disposition: attachment, and the filename to save it under.

A route calls res.sendFile(req.params.name, { root: "files" }), and a client asks for ..%2Fapp.js. Which status comes back?Tap to reveal
  1. root keeps every request inside the folder.

403, Forbidden.

mkdir -p files
echo "a,b" > files/x.csv
cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/x", (req, res) => res.download("files/x.csv", "mine.csv"));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/x");
  console.log(r.headers.get("content-disposition"), r.headers.get("content-type"));
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
attachment; filename=mine.csv text/csv; charset=utf-8
  1. res.download names the file with its second argument.
  2. The type comes from the extension, .csv, and the charset is added for text.

It prints attachment; filename=mine.csv text/csv; charset=utf-8.

Did you know?

Names in any script

A download's name can be in any script, such as a receipt named in Hindi. A name outside ISO-8859-1 travels in the parameter filename*, as RFC 6266 of June 2011 shows: filename*=UTF-8''%e2%82%ac%20rates names a file with a euro sign, in UTF-8 and percent codes. Express's content-disposition package handles such Unicode names by itself.

Why it fits here: It answers this topic's question: a name in Hindi travels as filename*, in UTF-8, which Express writes for you.

Sources: RFC 6266: Use of the Content-Disposition Header Field in HTTP; Express on GitHub: package.json; content-disposition on GitHub

An attack with a name

Climbing out with .. is an old attack with a name. OWASP calls it path traversal, or directory traversal: by using dot-dot-slash (../) sequences, or absolute paths, an attacker may reach files outside the web root, even the application's source code. The 403 that res.sendFile gives with root is a guard against exactly this.

Why it fits here: It names this topic's 403: a name with .. is a path traversal attack, which root stops.

Sources: OWASP: Path Traversal; PortSwigger Web Security Academy: Path traversal

In one line

The call res.sendFile(name, { root }) sends one file, with a type from its extension, and res.download and res.attachment add Content-Disposition: attachment, so the browser saves the body under a name. With root, a name that climbs out with .. gets 403, and a missing one or a dot-file 404, sent to the error handler.

Answers the client already has

At a glance

The fastest answer is the one the client already has. HTTP lets a client ask whether its copy is still good.

An ETag is a fingerprint of the body. A client that holds an answer sends its ETag back in If-None-Match, and while it still matches, Express answers 304 Not Modified, with no body. From fetch, the request needs Cache-Control: max-age=0, or fetch's own no-cache makes Express send the whole body again. On an answer, Cache-Control tells every cache how it may keep it.

Take a guess: Can an answer tell the client never to check it again while it is fresh?

In lesson 03 you saw that Express puts an ETag on every answer: a fingerprint of the body, W/ followed by the body's length in hexadecimal and part of a hash. The same body always gets the same ETag, and a changed body gets a new one. Now the fingerprint earns its keep.

A client that already holds an answer can send its ETag back in an If-None-Match header. It means: send the body only if its fingerprint is no longer this one. If nothing changed, Express answers 304 Not Modified, with no body, and the client uses its own copy:

app.js

const express = require("express");
const app = express();
const gauges = { boiler: 95 };
app.get("/gauges", (req, res) => res.json(gauges));
const server = app.listen(3000, async () => {
  const first = await fetch("http://localhost:3000/gauges");
  const tag = first.headers.get("etag");
  console.log("first:", first.status, tag, await first.text());
  const again = await fetch("http://localhost:3000/gauges", { headers: { "If-None-Match": tag, "Cache-Control": "max-age=0" } });
  console.log("again:", again.status, JSON.stringify(await again.text()));
  gauges.boiler = 97;
  const changed = await fetch("http://localhost:3000/gauges", { headers: { "If-None-Match": tag, "Cache-Control": "max-age=0" } });
  console.log("changed:", changed.status, changed.headers.get("etag"), await changed.text());
  server.close();
});

Terminal: node app.js

first: 200 W/"d-wEueY+wFmua+fBw6isMvSUj/6F8" {"boiler":95}
again: 304 ""
changed: 200 W/"d-vB6sCKovdUz8Y6HrHxgmcB6obAA" {"boiler":97}

The first answer was 200, with the body and its ETag. The second request sent the ETag back, and Express answered 304 with an empty body. The reading had not changed, so the thirteen bytes of JSON did not travel again.

Then the reading changed, so its fingerprint changed too. The third request still sent the old ETag, which no longer matched, so it got 200, the new body and a new ETag.

A request with If-None-Match is called a conditional request: it asks for the body only on a condition. For thirteen bytes the saving is small, but for a list of ten thousand readings, fetched every minute, it is most of the traffic.

res.sendFile and express.static also send a Last-Modified header with the file's date. A client can send that date back in If-Modified-Since, another conditional request, and get the same 304.

Why the Cache-Control: max-age=0?

You may wonder why the client also sent Cache-Control: max-age=0 with its ETag. Here is what happens without it:

app.js

const express = require("express");
const app = express();
const gauges = { boiler: 95 };
app.get("/gauges", (req, res) => res.json(gauges));
const server = app.listen(3000, async () => {
  const first = await fetch("http://localhost:3000/gauges");
  const tag = first.headers.get("etag");
  const plain = await fetch("http://localhost:3000/gauges", { headers: { "If-None-Match": tag } });
  console.log("If-None-Match alone:", plain.status);
  const asked = await fetch("http://localhost:3000/gauges", { headers: { "If-None-Match": tag, "Cache-Control": "max-age=0" } });
  console.log("with Cache-Control: max-age=0:", asked.status);
  server.close();
});

Terminal: node app.js

If-None-Match alone: 200
with Cache-Control: max-age=0: 304

The ETag was the right one both times, yet only the second request got its 304. The reason lies in fetch, not in Express. The Fetch standard, which Node's fetch follows, says that a program which writes its own If-None-Match is doing its own caching.

So fetch adds Cache-Control: no-cache to such a request, unless the program wrote a Cache-Control of its own. No-cache asks for a fresh answer, and Express obeys it by sending the whole body. Writing Cache-Control: max-age=0 yourself stops fetch adding no-cache, and Express is free to answer 304.

Only programs need this

A browser's own cache sends If-None-Match by itself, and gets its 304s with no help. The extra header is needed only when a program that uses fetch keeps its own copy, as the example below does.

Telling caches what to do: Cache-Control on the answer

Cache-Control also works the other way: on an answer, it tells every cache how it may keep the body. You set it with res.set:

Cache-Control on the answerWhat it means
no-storenever keep this answer
no-cachekeep it, but check with the server, with a conditional request, before every use
max-age=60use it for 60 seconds without asking at all
public, max-age=0what res.sendFile sends: any cache may keep it, but must check it every time
privateonly the client's own cache may keep it, not caches shared by many people

Worked example 6

Write a client that keeps a copy of /gauges and its ETag, asks with If-None-Match every time, and uses its copy whenever the answer is 304.

What we have: a /gauges route that answers JSON, and a PUT route that changes one gauge

What we need: a first 200, a 304 while nothing has changed, and a new 200 after the change

The plan: keep copy and tag in two variables; send If-None-Match and Cache-Control: max-age=0 once there is a tag; on 304 return the copy, otherwise keep the new body and its tag

app.js

const express = require("express");
const app = express();
const gauges = { boiler: 95, fan: 40 };
app.get("/gauges", (req, res) => res.json(gauges));
app.put("/gauges/:name", express.json(), (req, res) => {
  gauges[req.params.name] = req.body.value;
  res.sendStatus(204);
});
let copy = null;
let tag = null;
async function getGauges() {
  const headers = tag ? { "If-None-Match": tag, "Cache-Control": "max-age=0" } : {};
  const r = await fetch("http://localhost:3000/gauges", { headers });
  if (r.status === 304) {
    console.log("304: the copy is still good");
    return copy;
  }
  tag = r.headers.get("etag");
  copy = await r.json();
  console.log(r.status + ": a new copy, tag " + tag);
  return copy;
}
const server = app.listen(3000, async () => {
  console.log(await getGauges());
  console.log(await getGauges());
  await fetch("http://localhost:3000/gauges/fan", { method: "PUT", headers: { "Content-Type": "application/json" }, body: '{"value":45}' });
  console.log(await getGauges());
  server.close();
});

Terminal: node app.js

200: a new copy, tag W/"16-L3clStlnswEhgL8MWllMWajHDmQ"
{ boiler: 95, fan: 40 }
304: the copy is still good
{ boiler: 95, fan: 40 }
200: a new copy, tag W/"16-VfJLiICIZhBclDSmzGaWzNnA9MI"
{ boiler: 95, fan: 45 }
  1. The first call had no tag, so it sent no condition, and got 200 with the body and its tag.
  2. The second call sent the tag. Nothing had changed, so the server sent 304 with no body, and the function returned its copy.
  3. The PUT changed the fan, so the body changed, so its fingerprint changed: the third call got 200 and a new tag.
  4. Both tags begin with W/"16-, because both bodies are 22 bytes long, and 22 is 16 in hexadecimal; only the hash part differs.

200, then 304 with the copy, then 200 with the fan at 45.

Check: The 304 came only while the body was the same; the change gave a new tag at once.

Another way: keep one copy and tag for each address in a Map, so that one client can cache many addresses.

A path that fails: sending If-None-Match from fetch without Cache-Control: max-age=0. Every answer is then 200, and the client saves nothing.

When you are stuck: No 304, ever

Does the client send the ETag back exactly as it came, with its W/ and its quotes, in If-None-Match?

Does a client that uses fetch also send Cache-Control: max-age=0? Without it, fetch adds no-cache and Express sends the whole body.

Did the body change? Any change, even one space, gives a new ETag. And app.set("etag", false) turns ETags off altogether.

Your turn

What does a 304 answer carry in its body?Tap to reveal
  1. The client already holds the body.

Nothing: the client uses its own copy.

Which request header carries an ETag back to the server?Tap to reveal
  1. It asks for the body only if the fingerprint has changed.

If-None-Match.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.set("etag", false);
app.get("/gauges", (req, res) => res.json({ boiler: 95 }));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges");
  console.log(r.status, r.headers.get("etag"));
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
200 null
  1. app.set("etag", false) turns the fingerprints off.
  2. headers.get answers null for a header that is not there.

It prints 200 null.

Did you know?

Files that never change

Some files never change at their address, such as a script whose name holds a fingerprint of its contents. RFC 8246, of September 2017, gave them the Cache-Control extension immutable: the response will not be updated while it is fresh. So a client should not ask again during that time, not even on a reload, unless the person forces one.

Why it fits here: It answers this topic's question: Cache-Control: immutable tells a client not to check a fresh answer, even on a reload.

Source: RFC 8246: HTTP Immutable Responses

Two lifetimes in one answer

One answer can carry two lifetimes. RFC 9111 says that s-maxage applies only to shared caches, which keep answers for more than one user, and that there it overrides both max-age and Expires. So Cache-Control: max-age=60, s-maxage=3600 lets each browser keep the answer for a minute, and a shared cache for an hour.

Why it fits here: It adds to this topic's Cache-Control: s-maxage sets a separate lifetime for caches shared by many users.

Source: RFC 9111: HTTP Caching

In one line

An ETag is the body's fingerprint. A client that holds an answer sends it back in If-None-Match, and Express answers 304 Not Modified, with no body, while it still matches. From fetch, add Cache-Control: max-age=0, or fetch's own no-cache makes Express send the whole body. On an answer, Cache-Control tells caches how they may keep it.

Where it is used

Every API reads and writes these parts of a request and its answer, most of them on every single request. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
request headers and req.getevery APIa key or a token sent in a header and checked by a guard
req.is and 415APIs that take uploadsa picture service that refuses a file of the wrong type
content negotiationAPIs with several formsone address that gives a report as JSON or as CSV
cookiesevery site with sign-ina session id kept in an HttpOnly, Secure cookie
res.download and Content-Dispositionexportsa month's orders saved as a spreadsheet
ETags and 304browsers, and APIs fetched again and againa page's pictures and scripts not downloaded twice

Browsers lean on all of it without being asked: they send Accept and Accept-Language with every request, keep cookies, and revalidate their cached copies with If-None-Match. A server that answers these headers well makes every page faster.

In the Couriers' Yard, the headers are the notes pinned to each parcel, the cookie is the token a returning courier shows at the gate, and the 304 is the stamp that says unchanged.

Mistakes and debugging

These are the mistakes that beginners make most with requests and responses, each with the way to see it and the fix.

1. res.format with no default

A client that asks for a form you do not make gets Express's own 406 page, in HTML, even from a JSON API. The block below picks the first line out of that page:

app.js

const express = require("express");
const app = express();
app.get("/gauges/boiler", (req, res) => res.format({ "application/json": () => res.json({ value: 95 }) }));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges/boiler", { headers: { Accept: "text/plain" } });
  console.log(r.status, r.headers.get("content-type"));
  console.log((await r.text()).match(/<pre>([^<]*?)<br>/)[1]);
  server.close();
});

Terminal: node app.js 2>/dev/null

406 text/html; charset=utf-8
NotAcceptableError: Not Acceptable

Express passed a NotAcceptableError to its own error handler, which answered in HTML. Add a default to every res.format, and answer 406 in JSON from it.

2. Looking for req.cookies

Express does not split the Cookie header by itself:

app.js

const express = require("express");
const app = express();
app.get("/c", (req, res) => res.json({ cookies: typeof req.cookies, header: req.get("cookie") }));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/c", { headers: { Cookie: "hall=engine" } });
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

{"cookies":"undefined","header":"hall=engine"}

req.cookies is undefined; the cookie is still there, in the header. Read req.get("cookie") and split it as readCookies did, or add the cookie-parser package.

3. A relative path without root

res.sendFile refuses a path that does not start at /, unless root says where to look:

app.js

const express = require("express");
const app = express();
app.get("/readings", (req, res) => res.sendFile("files/readings.csv"));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/readings");
  console.log(r.status, r.headers.get("content-type"));
  console.log((await r.text()).match(/<pre>([^<]*?)<br>/)[1]);
  server.close();
});

Terminal: node app.js 2>/dev/null

500 text/html; charset=utf-8
TypeError: path must be absolute or specify root to res.sendFile

The TypeError became a 500, with Express's HTML page, and the file was never read. Write res.sendFile("readings.csv", { root: "files" }), which also keeps every request inside the folder.

4. Waiting for a 304 that never comes

A client that uses fetch and sends only If-None-Match gets 200 every time, because fetch adds Cache-Control: no-cache. Add Cache-Control: max-age=0 to the request. A browser needs no such help.

5. Trusting a cookie

A cookie lives with the client, and the client can change it, as visits=999 showed. Never keep a role, a price or a balance in a cookie. Keep such things on the server, and put only a long random id in the cookie.

6. Choosing the form by hand and forgetting Vary

A route that reads req.accepts and answers differently must say so with res.vary("Accept"). Without it, a cache may keep the JSON and give it to a client that asked for CSV. res.format adds Vary: Accept for you.

The debugging corner: see every header

On the server, print req.rawHeaders: every header that arrived, in its order and case. On the client, print [...r.headers] for every header of the answer, and r.headers.getSetCookie() for its cookies, one by one.

When a form, a cookie or a 304 goes wrong, the answer is almost always in one header that is missing, or spelled another way.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

app.js

const express = require("express");
const app = express();
const gauge = { name: "boiler", value: 95 };
app.get("/gauges/boiler", (req, res) => {
  if (!(req.get("cookie") ?? "").includes("seen=yes")) res.cookie("seen", "yes", { httpOnly: true });
  res.format({
    "application/json": () => res.json(gauge),
    "text/plain": () => res.send(`${gauge.name} ${gauge.value}`),
    default: () => res.status(406).json({ error: "JSON or plain text only" }),
  });
});
app.get("/report", (req, res) => {
  res.attachment("report.csv");
  res.send(`name,value\n${gauge.name},${gauge.value}\n`);
});
const server = app.listen(3000, async () => {
  const url = "http://localhost:3000";
  const a = await fetch(url + "/gauges/boiler");
  console.log(1, a.status, a.headers.get("content-type"), a.headers.getSetCookie(), await a.text());
  const b = await fetch(url + "/gauges/boiler", { headers: { Accept: "text/plain", Cookie: "seen=yes" } });
  console.log(2, b.status, b.headers.get("content-type"), b.headers.getSetCookie(), await b.text());
  const c = await fetch(url + "/gauges/boiler", { headers: { Accept: "image/png" } });
  console.log(3, c.status, await c.text());
  const d = await fetch(url + "/gauges/boiler", { headers: { "If-None-Match": a.headers.get("etag"), "Cache-Control": "max-age=0", Cookie: "seen=yes" } });
  console.log(4, d.status);
  const e = await fetch(url + "/report");
  console.log(5, e.headers.get("content-disposition"), JSON.stringify(await e.text()));
  server.close();
});

Terminal: node app.js

1 200 application/json; charset=utf-8 [ 'seen=yes; Path=/; HttpOnly' ] {"name":"boiler","value":95}
2 200 text/plain; charset=utf-8 [] boiler 95
3 406 {"error":"JSON or plain text only"}
4 304
5 attachment; filename=report.csv "name,value\nboiler,95\n"
When you seeIt meansDo
406 Not Acceptableno form the client said it takesmake that form, or answer 406 in JSON from a default
415 Unsupported Media Typea body of a kind the route does not readsend the type it takes; on the server, check with req.is
304 Not Modifiedthe client's copy is still currentuse the copy you kept
Set-Cookie on an answerthe server asks the client to keep a notesend it back in a Cookie header
Vary: Acceptthe answer depends on the Accept headercaches keep one copy for each form
403 from res.sendFilethe name tried to leave the folderonly names inside root are sent
TypeError: path must be absoluteres.sendFile got a relative path and no rootgive root: { root: "files" }

The story: Answers that fit the asker

Now every bench reads the notes before it answers. The Clock Tower gets its one plain line, the Engine Hall its JSON, and a hall that asks for a form the yard cannot make gets a polite refusal, stamped 406.

A returning courier shows the small token the yard gave at the last visit, and walks straight through the gate. The Archive's ledger arrives as a file with its name on the label. When the Engine Hall asks again for a ledger it already holds, the yard answers with one stamp, unchanged, and the courier goes home light.

"Tomorrow," says the Yardmaster, "the parcels that go wrong, and how a good yard fails."

Reagents gathered: request header, content negotiation, cookie, Content-Disposition, ETag, 304 Not Modified.

Sources

  • The Express documentation (CC BY-SA 3.0 US (the site's footer, read 2026-11-15); facts and ideas only)
  • The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
  • MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)