Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 133 ยท Networking and HTTP

Headers, Cookies and Caching

Use HTTP headers in Node.js - Set-Cookie attributes, parsing cookies, signed cookie sessions with crypto, CORS and preflight, ETag and 304 responses, Cache-Control and compression negotiation.

Status codes and bodies get the attention, but much of what makes the web work happens in headers: small Name: value lines before the body. Headers carry identity (cookies), permission (CORS), freshness (caching) and format (compression, content type). A server that gets them right is faster, safer and cheaper to run.

In this lesson you will set and parse cookies, protect a cookie with a signature so that it can serve as a tiny session, answer cross-origin requests with CORS headers, make responses cacheable with ETag and Cache-Control, and negotiate compression. Every example runs a loopback server and calls it from the same program, as in The http Module: Servers. If you need a refresher on how headers look on req and res, start there.

Reading and writing headers

On the server, req.headers is an object with lower-case keys. To send headers, use res.setHeader(name, value) (one at a time, before the body starts) or res.writeHead(status, headers). A header that may repeat, such as Set-Cookie, takes an array: each element becomes its own header line. Names are case-insensitive, and on the client side Headers objects from fetch normalise them for you.

Node.js Request and response headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Note getSetCookie(): plain headers.get('set-cookie') would glue the lines together with commas, which is ambiguous because cookie dates also contain commas. Always use getSetCookie() for cookies.

Cookies

A cookie is a tiny piece of text the server asks the browser to store and send back on later requests. The server sets it with a Set-Cookie header; the browser returns it in a single Cookie: a=1; b=2 header. Cookies are how a stateless protocol remembers who you are.

A Set-Cookie value is name=value followed by attributes that control how the browser treats it:

Attribute Meaning
Path=/ Which URL paths get the cookie. Usually /.
Max-Age=3600 Lifetime in seconds. Without Max-Age/Expires it is a session cookie (until the browser closes). Max-Age=0 deletes it.
Expires=<date> Expiry as an HTTP date; Max-Age wins if both are set.
HttpOnly JavaScript in the page cannot read it (document.cookie). Use for session cookies.
Secure Only sent over HTTPS. Always on in production.
SameSite=Lax Not sent on cross-site sub-requests (images, fetch, form POSTs); this blocks most CSRF. Strict is stricter, None allows cross-site and requires Secure.
Domain=example.com Share with subdomains. Leave it out and the cookie stays on the exact host (safer).

The Cookie header, by contrast, has no attributes: just names and values. Parsing it is a few lines. Keep in mind that values may be percent-encoded, so decode them, and tolerate junk.

Node.js Setting and parsing cookies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Browsers do the jar work automatically. Node's fetch has no cookie jar, so a script talking to a login-protected site must copy Set-Cookie values by hand, as above.

Cookies are plain text controlled by the user. If you store isAdmin=true in one, anybody can edit it with the developer tools. Store a random session ID (and keep the data on the server), or sign the cookie so tampering is detected, as in the next section.

Signed cookies: a session by hand

A signed cookie contains the data plus an HMAC of that data made with a secret only the server knows. When the cookie comes back, the server recomputes the HMAC and compares. If the user changed one character of the payload, the signatures no longer match. (The payload is readable by the user, only tamper-proof; for secrets use a server-side session ID or encryption, see Hashing and HMAC and Encryption: AES, RSA and Keys.)

The comparison must use crypto.timingSafeEqual, which takes the same time however many bytes match. A normal === returns earlier for an early mismatch, which in theory leaks information about the correct signature. The two buffers must have equal length, so check that first.

Node.js A signed session cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This is the idea behind signed JWTs and framework session cookies. Two cautions: rotate the secret if it leaks (every session dies, which is the right outcome), and always put an expiry inside the signed payload, because a stolen cookie is otherwise valid for ever. Passwords, scrypt and Tokens builds a full token flow.

CORS: letting browsers call your API

Browsers enforce the same-origin policy: a page from https://app.example may not read the response of a request to https://api.example unless the API opts in with CORS headers. Two things to know:

  1. CORS is enforced by the browser. A curl command or Node's fetch ignores it. It protects users, not your server.
  2. For "non-simple" requests (JSON bodies, custom headers, PUT/DELETE) the browser first sends a preflight: an OPTIONS request asking "may I?". Your server answers with the allowed methods and headers, and only then the real request goes out.

The headers you send:

  • Access-Control-Allow-Origin: the allowed origin, or * for public data without cookies.
  • Access-Control-Allow-Methods / Access-Control-Allow-Headers: used in the preflight answer.
  • Access-Control-Allow-Credentials: true: lets cookies through; then the origin cannot be *.
  • Access-Control-Max-Age: how long (seconds) the browser may cache the preflight result.
  • Vary: Origin: required when you echo different origins, so shared caches do not mix them up.

Echo the origin only if it appears on an allow-list you control; never reflect any Origin blindly together with credentials.

Node.js A CORS handler with an allow-list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The server answers the unknown origin normally, just without the CORS headers: the browser then refuses to hand the response to the page's JavaScript. That is why "CORS errors" show up only in browsers.

HTTP caching: ETag and 304

Sending the same 200 KB response over and over wastes bandwidth. HTTP lets a client keep a copy and ask the server "is my copy still current?". The server labels each version with an ETag (an opaque fingerprint, usually a hash of the content). The client later sends If-None-Match: <etag>. If it still matches, the server replies 304 Not Modified with no body, and the client reuses its copy.

Node.js ETag and conditional requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The server still did the work of building the body to compute the hash; a 304 saves bandwidth, not CPU. To save CPU too, derive the ETag from something cheap, such as a version number or a file's modification time. Node's fetch does not cache anything by itself, so we sent If-None-Match manually; a browser does it for you.

Cache-Control

Cache-Control says who may store a response and for how long. The values you will use most:

  • no-store: never store it (private data such as account pages).
  • no-cache: store it, but always revalidate with the server first (as above).
  • max-age=3600: the browser may reuse it for an hour without asking.
  • public / private: shared caches (CDNs) may or may not store it.
  • s-maxage=600: like max-age for shared caches only.
  • immutable: it will never change; pair it with max-age=31536000 for files whose name contains a content hash (app.3f9a1c.js).
  • stale-while-revalidate=60: serve a stale copy while fetching a fresh one in the background.

A good default is: fingerprinted static assets get public, max-age=31536000, immutable; HTML pages get no-cache (with an ETag); responses with personal data get private, no-store. The dangerous mistake is caching a personalised page publicly, so that user A sees user B's data. For that reason always add Vary for every request header that changes the response (Accept, Accept-Language, Accept-Encoding, Cookie).

Compression negotiation

Text compresses very well. The client lists what it can decode in Accept-Encoding: gzip, br; the server picks one, compresses the body and states the choice in Content-Encoding. Always add Vary: Accept-Encoding. Node's zlib module provides gzipSync and brotliCompressSync (the streaming versions are in Compression with zlib). Do not compress already-compressed formats (JPEG, PNG, MP4, zip) and skip tiny bodies where the header overhead cancels the gain.

Node.js Choosing gzip or Brotli

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

fetch decompressed the body transparently, which is why we could call .json(). The Content-Length header still shows the compressed size that crossed the wire. In production you usually let a reverse proxy or CDN do compression (see Deploying Node.js Applications) so that Node's single thread is not spent on it.

Security headers in one place

A few response headers harden an application at almost no cost: X-Content-Type-Options: nosniff (do not guess content types), Content-Security-Policy (restrict where scripts load from), Strict-Transport-Security (HTTPS only), Referrer-Policy: strict-origin-when-cross-origin and X-Frame-Options: DENY (no framing). Setting them is one setHeader call each, usually in a middleware; what each protects against is covered in Web Application Security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you read cookies from a Fetch response with headers.getSetCookie()?

    Several Set-Cookie headers cannot be safely joined with commas because cookie dates contain commas. getSetCookie() returns an array with one entry per header line.
  2. 2. Which attribute stops JavaScript running in the page from reading a cookie?

    HttpOnly hides the cookie from document.cookie, which limits the damage of an XSS bug. Secure only controls HTTPS, and SameSite controls cross-site sending.
  3. 3. A signed cookie is verified with crypto.timingSafeEqual instead of ===. What does this achieve?

    A plain comparison can return early on the first different byte. A constant-time comparison avoids leaking how much of the signature was correct.
  4. 4. A client sends If-None-Match with the current ETag. What should the server answer?

    The ETag says the client's copy is still current, so 304 tells it to reuse the copy and saves sending the body.
  5. 5. Why can a request from Node's fetch succeed while the same request from a browser page fails with a CORS error?

    The server answers either way. The browser decides whether the page's script may read the response, based on the Access-Control-Allow-* headers. Node clients have no such policy.

Summary

  • Headers travel before the body; req.headers has lower-case keys, repeated headers like Set-Cookie are arrays, and getSetCookie() reads them on the client.
  • Cookies are set with Set-Cookie and attributes (HttpOnly, Secure, SameSite, Max-Age, Path) and come back as one Cookie header; Node's fetch has no cookie jar.
  • Never trust cookie values; use random session IDs or an HMAC signature checked with timingSafeEqual, and include an expiry in the signed data.
  • CORS is a browser rule: allow-list origins, answer OPTIONS preflights, send Vary: Origin, and never combine * with credentials.
  • ETag plus If-None-Match yields cheap 304 replies; Cache-Control controls storage (no-store, no-cache, max-age, immutable).
  • Negotiate compression with Accept-Encoding, set Content-Encoding and Vary, and consider letting a proxy do it.

Next: Middleware Pattern