Jon Rumsey

An online markdown blog and knowledge repository.


Project maintained by nojronatron Hosted on GitHub Pages — Theme by mattgraham

Using Cookies with Express

Table of Contents

Overview of Cookies

Cookies are just Key-Value Pairs with some additional Attributes that define when and where the cookie can be used.

When a server sets a cookie with a reply to a client (user agent) request, the user agent stores that Cookie and sends it back to the server on its next request. The idea is to store state information between user agent and server, enabling session-tracking capability.

Generally:

Technically:

When using Set-Cookie the primary article is a Key-Value pair. There are also attributes that could (should) be set:

As mentioned elsewhere SameSite=None must be followed by Secure otherwise the Cookie will not get set by the User Agent.

Supercookies

Session Management:

User Logon Process

  1. User opens the Logon page (Server-side rendered: The server also sends a unique Session ID to the user agent within a Cookie).
  2. When user successfully logs in and cookie is sent back to the server by the user-agent.
  3. Server processes the returned Session ID via the cookie.
  4. The user agent supplies an Authorization header and, if validated, the server sets a new cookie granting access to authorized resources.

Personalization Cookies

Tracking Cookies

Cookies and Authentication

Users need to authenticate themselves, via a logon page or functionality.

Authentication cookies are usually encrypted.

Risks of decrypting an Auth Cookie include:

JSON Web Tokens

HTTP Auth

URL aka Query String

Hidden Form Fields

Window.Name DOM Property

Other Means of Tracking

SameSite Key

'SameSite' is an Attribute.

Possible values:

Lax

Note: Browsers might implement 'Lax-Allowing-Unsafe' to enable cross-site unsafe requests within a short timeframe, therefore a value should be set by the developer.

Strict

None

  1. Install Cookie-parser: npm install cookie-parser
  2. Load in Express (JS): const cookieParser = require('cookie-parser')
  3. Initialize as middleware function: app.use(cookieParser())
  4. Acquire a specific cookie from a user agent request: const receivedCookie = req.cookies["key"]
  5. Set a cookie in user agent browser via a Response: res.cookie('keyString', 'valueString', { options })
  6. Set options as a destructured object (see below).
const options = {
  maxAge = 1000 * 60 * 15, // 1 sec * 60 sec * 5 => 5 minutes
  httpOnly: true, // only useable by the server
  signed: true // only include if the cookie is signed
};
res.cookie('name', 'value', options);
res.send('');

Signed Cookies

  1. Prefixed with s:.
  2. Include a secure string to sign them.
  3. Set signed: true property on the cookie options.

JSON Cookies

  1. Prefixed with j:. Parsed using JSON.parse.
  2. Return parsed JSON value: cookieParser.JSONCookie(String).
  3. Iterate over the keys to return an object: cookieParser.JSONCookies(Array[cookies]).
  4. Signed JSON cookies can also be parsed: cookieParser.signedCookie(String, Secret). Signature must be valid, if not, returns false.
  5. Iterate over the keys to check for signed values: cookieParser.signedCookies(cookies, Secret). Secret can be an array of Secrets or a single Secret String. In either case, all Secret(s) will be used to 'unsign' each cookie in signedCookies.

Review the expressjs cookie-parser documentation for a few more details about JSON Cookies.

See StackOverflow set cookie using express framework, where a user noted that Fetch didn't seem to respect cookie setting. Fetch options must be set in order to work around the problem.

You will not see a SecureCookie, this is on purpose. Be sure to use a valid secret to sign cookies, and utilize req.signedCookies to retrieve them.

Resources Used For These Notes

Return to Conted Index.

Return to Root README.