Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 43 ยท Request and Response

Cookies and Headers

Set and read cookies in Express with res.cookie and cookie-parser, choose httpOnly, secure and sameSite, sign cookies, and use Cache-Control and ETag headers.

HTTP is stateless: the server forgets you after every response. Cookies are the oldest trick for remembering a browser between requests. The server sends a Set-Cookie header, the browser stores it, and from then on it sends the value back in a Cookie header. Headers more broadly also control caching, content types and security. This lesson covers both, because cookies are just headers with rules.

Real Express and cookie-parser code is read-only here. The runnable examples use the mini Express stand-in with hand-written helpers and a tiny cookie jar, and they say where they simplify.

Express has res.cookie(name, value, options) built in:

JavaScript
app.get('/theme/dark', (req, res) => {
  res.cookie('theme', 'dark', {
    maxAge: 7 * 24 * 60 * 60 * 1000,  // milliseconds!
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
  });
  res.send('Theme saved');
});

This adds a header like Set-Cookie: theme=dark; Max-Age=604800; Path=/; Expires=...; HttpOnly; Secure; SameSite=Lax. Note that Express takes maxAge in milliseconds but writes Max-Age in seconds, a classic surprise.

Cookie options that matter

httpOnly JavaScript in the page cannot read it.
secure Sent only over HTTPS.
sameSite Limits sending on cross-site requests.
maxAge How long the browser keeps it.

Session and login cookies should use all four.

1 / 2

Other options are path (default /), domain, expires (a Date) and signed. If you omit maxAge and expires, you get a session cookie that disappears when the browser closes.

Express does not parse the incoming Cookie header for you. The cookie-parser package adds req.cookies:

JavaScript
import express from 'express';
import cookieParser from 'cookie-parser';

const app = express();
app.use(cookieParser('a-long-random-secret'));

app.get('/', (req, res) => {
  res.send(`Theme: ${req.cookies.theme ?? 'light'}`);
});

Without the middleware req.cookies is undefined. If you do not need signed cookies, call cookieParser() with no secret.

JavaScript
res.clearCookie('theme');   // options like path/domain must match how you set it

A browser only deletes a cookie when name, path and domain match the original, so pass the same options you used in res.cookie.

Signed cookies

Anyone can edit a cookie in the browser's developer tools. A signed cookie carries a signature made with a secret only the server knows, so tampering can be detected. It does not hide the value; it only proves the server wrote it.

JavaScript
res.cookie('plan', 'free', { signed: true });   // needs cookieParser(secret)
// later
req.signedCookies.plan;        // 'free', or false if the signature is wrong

Express writes the value as s: + value + . + an HMAC-SHA256 signature in base64. The stand-in below does the same thing with node:crypto so you can watch it work.

With cookie-parser, signed values appear in req.signedCookies (a tampered value becomes false), unsigned ones in req.cookies. A cookie whose value starts with j: holds JSON; cookieParser.JSONCookie(str) parses one such string and cookieParser.JSONCookies(cookies) parses all of them in an object. res.cookie('cart', { items: 2 }) writes the j: form for you.

This example writes simplified copies of res.cookie and a Cookie parser as middleware, then prints the Set-Cookie header. The real res.cookie also handles encoding, expires and more option checks.

Node.js res.cookie and req.cookies, simplified

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 first request shows the exact header a browser would store. The two calls to / show the same route answering differently depending on the Cookie header, which is all that "remembering the user" means at the HTTP level.

Signing and tamper detection

Node.js A signed cookie with HMAC

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 signature changes whenever the value changes, so a forged value fails verification. Notice the last line: the value is plainly readable. Never put secrets in a cookie only because it is signed. For login state, store a random session id in the cookie and keep the data on the server; see Sessions and Login.

Caching headers

Headers also tell browsers and CDNs what they may reuse. The most useful are:

JavaScript
res.set('Cache-Control', 'public, max-age=3600');   // reuse for one hour
res.set('Cache-Control', 'no-store');               // never store (private data)
res.set('Cache-Control', 'no-cache');               // store, but revalidate first

Be careful with no-cache: it does not mean "don't cache". It means "check with the server before reusing".

ETag and conditional requests

Express adds a weak ETag (a fingerprint of the body) to res.send and res.json responses by default. On the next visit the browser sends If-None-Match: <etag>. If the body is unchanged, Express answers 304 Not Modified with no body, saving bandwidth. You can turn it off with app.set('etag', false).

The stand-in below fingerprints the body with a hash and answers 304 when it matches:

Node.js ETag and 304 Not Modified

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 revisit costs almost nothing: the status is 304 and the body is empty. After the data changes, the fingerprint no longer matches and the full response comes back. For long-term performance advice, see Performance and Caching.

Reading and writing arbitrary headers

req.get('User-Agent') reads a request header (case-insensitive) and res.set() writes a response header, as you saw in The Response Object. Custom headers traditionally started with X-, but that convention is no longer recommended; pick a clear name such as Request-Id.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What unit does the maxAge option of res.cookie use in Express?

    Express takes maxAge in milliseconds and converts it to seconds for the Max-Age attribute.
  2. 2. What does the httpOnly option do?

    httpOnly stops document.cookie from reading the cookie, which limits the damage of an XSS bug. It does not encrypt anything.
  3. 3. What does signing a cookie provide?

    A signature proves the server wrote the value. The value itself stays readable.
  4. 4. What happens when a browser sends a matching If-None-Match header?

    A matching ETag means the cached copy is still valid, so the server skips the body and answers 304.

Summary

  • res.cookie(name, value, options) sets cookies; cookie-parser fills req.cookies and req.signedCookies.
  • Use httpOnly, secure and sameSite for anything sensitive; maxAge is in milliseconds.
  • Signed cookies detect tampering but do not hide values.
  • Cache-Control controls reuse; ETags let browsers revalidate and receive cheap 304 answers.
  • Clear a cookie with the same path and domain you set it with.

Next: Static Files, Downloads and Streaming.