skip to content

With cookie-session in an Express app, what does its Keygrip signature protect, and what does it leave exposed?

level: seniorimportance: should knowfreq 28%

answer

  1. the whole session rides in the cookie
  2. a second cookie with .sig
  3. integrity is not secrecy
  4. nothing on the server to revoke

basics

~20 s

cookie-session stores the whole session as base64 JSON in the cookie and signs it with Keygrip, so tampering is detected; but anyone holding the cookie can read it, replay it until it expires, and the server cannot revoke it.

solid answer

~40 s

cookie-session keeps no server-side record: it serialises `req.session` to JSON, base64-encodes it into a cookie named `session` by default, and writes a second cookie, `session.sig`, holding a Keygrip HMAC of that value, made with `keys[0]` (HMAC-SHA1 unless you pass a configured `Keygrip`). On the next request a signature that no key in the list verifies is discarded and `req.session` starts empty, so a client cannot change its role or user ID. What it does not protect: **confidentiality**, because base64 decodes straight back to the JSON and the README says it does not encrypt; **replay**, because a copied cookie stays valid until it expires; and **revocation**, because `req.session = null` only clears the responding browser's cookie. Sign-out everywhere means rotating `keys`, which signs everyone out, or adding a server-side check.

code

javascript · 15 lines
javascript
const express = require('express')
const cookieSession = require('cookie-session')

const app = express()

app.use(cookieSession({
  name: 'session',
  keys: [process.env.COOKIE_KEY_NEW, process.env.COOKIE_KEY_OLD], // keys[0] signs
  maxAge: 8 * 60 * 60 * 1000
}))

app.post('/logout', (req, res) => {
  req.session = null // clears this browser's cookie only
  res.redirect('/')
})

go deeper

for a junior

Recall that cookie-session keeps the whole session in the browser cookie and signs it, unlike express-session, which keeps only an ID.

for a middle

Explain the two cookies, the base64 JSON value, the .sig HMAC from keys[0], and why an edited value comes back as an empty session.

for a senior

Name what signing does not give you, readability, replay and revocation, and what that rules out putting in the session.

for a principal

Decide where client-held session state is acceptable in a codebase and where a server-side store is required for revocation.

## Where cookie-session puts the session There are two ways to keep a session with cookies. **express-session** puts only a session ID in the cookie and keeps the data in a server-side store. **cookie-session** puts the **whole session in the cookie** and keeps nothing on the server. Its README presents the trade-off: no database or server resource is needed, and load-balanced setups get simpler, but the data travels with every request and must fit in a browser cookie. When a handler changes `req.session`, cookie-session writes two cookies on the response: 1. **`session`** (the default `name`) — the session object serialised with `JSON.stringify` and **base64-encoded**. 2. **`session.sig`** — a **Keygrip** signature: an HMAC over the string `session=<value>`, made with the first key in `keys`; with the default SHA-1 it is 27 characters of URL-safe base64. Keygrip's defaults are HMAC with SHA-1 and base64 output; passing a configured `new Keygrip(keys, 'sha256')` as `keys` changes the algorithm. cookie-session throws `.keys required.` at start-up if neither `keys` nor `secret` is given while signing is on, which is the default. ## What the signature protects On each request, cookie-session reads `session` and `session.sig` and asks Keygrip which key in the list produces that signature: - **No key matches** → the value is discarded, the `.sig` cookie is cleared, and `req.session` is a new, empty session. A user who edits the base64 to change `role` from `editor` to `admin` cannot produce a matching signature without a key, so the edit is simply thrown away. - **The first key matches** → the session loads normally. - **A later key matches** → the session loads, and a fresh `.sig` signed with `keys[0]` is set, moving the browser onto the current key. That last rule is how **key rotation** works: put the new key first, keep the old one after it so existing cookies still verify, and remove it once old cookies have aged out. So the signature buys **integrity and authenticity**: the server knows the value is one it issued. ## What it leaves exposed | Property | Protected by cookie-session? | Why | |---|---|---| | Tampering with the value | yes | the HMAC fails without a key | | Reading the value | **no** | base64 is an encoding, not encryption | | Replaying a copied cookie | **no** | it verifies until the cookie's own expiry | | Revoking one session server-side | **no** | there is no server record to delete | | Large session data | **no** | the browser's per-cookie size limit applies | In detail: - **Confidentiality.** Decoding the cookie gives back the JSON, for example `{"userId":42,"role":"editor"}`. The README's note is explicit: the module does not encrypt the contents, only signs them, and secret data should not go in `req.session` without encrypting it — or a server-side session should be used. - **Replay.** The README also says the module does not prevent session replay: the expiry is that of the cookie only. A cookie copied from one browser works in another until it expires. Its suggestion is to store an expiry inside `req.session` and check it on the server. - **Revocation.** Signing out sets `req.session = null`, which sends a cookie that clears the value — but only to the browser that made that request. A stolen copy stays valid. Killing all sessions means rotating `keys` away entirely, which signs out every user at once. Ending one session early needs some server-side state after all, such as a per-user counter stored in the database and compared on each request. - **Size.** The whole object rides in the cookie, so a growing session eventually exceeds what a browser will store; the cookie budget itself is covered with HTTP cookie limits. When signing alone is enough versus when the state must be encrypted, in general, belongs to the framework-neutral material on session identifiers; on this leaf the point is what this particular package does. ## Practical consequences - Keep only small, non-secret values in a cookie-session — an ID and a role, never tokens, personal data or anything a user should not read. - Treat the role in the cookie as a hint the server issued, not as permission that cannot be revoked; check sensitive actions against server-side data. - With `secure: true` behind a TLS-terminating proxy, set Express's `trust proxy`, or the cookie is never written. - If you need per-session revocation or secrecy, express-session with a server-side store is the simpler tool.

  • If a user presents a cookie signed with an older key from the list, what does cookie-session do?
    The value is accepted because Keygrip verifies against every key in `keys`. Because the matching key is not the first one, a fresh `session.sig` signed with `keys[0]` is set on the response, so the browser moves to the current key. That is what lets you rotate keys without signing users out.
  • Why does a session that is only read never refresh its expiry in the browser?
    cookie-session sends `Set-Cookie` only when the session's contents changed. A request that reads `req.session` without changing it sends nothing, so the cookie's expiry is not extended. The README's workaround is to update a small value, such as the current minute, so an active user's cookie is re-sent.

  • Keygrip encrypts the session, so users cannot read what is inside.
  • Setting req.session = null invalidates every copy of that cookie.
  • cookie-session stores only a session ID, like express-session.
  • A signed cookie cannot be replayed from another browser.
  • Rotating keys means putting the new key last in the list.