Manage Cookies with Express

By

Published · Updated

Tagged: Express.js

Learn how to manage cookies in Express with the res.cookie() method, set options like httpOnly, secure, and expires, and clear one with res.clearCookie().

Use the Response.cookie() method to manipulate your cookies.

Examples:

res.cookie('username', 'Flavio')

This method accepts a third parameter, which contains various options:

res.cookie('username', 'Flavio', { domain: '.flaviocopes.com', path: '/administrator', secure: true })

res.cookie('username', 'Flavio', { expires: new Date(Date.now() + 900000), httpOnly: true })

All res.cookie() does is add a Set-Cookie header to the response. The browser stores the cookie and sends it back on the next requests.

The most useful parameters you can set are:

ValueDescription
domainThe cookie domain name
expiresSet the cookie expiration date. If missing, or 0, the cookie is a session cookie
httpOnlySet the cookie to be accessible only by the web server. See HttpOnly
maxAgeSet the expiry time relative to the current time, expressed in milliseconds
pathThe cookie path. Defaults to ’/‘
secureMarks the cookie HTTPS only
signedSet the cookie to be signed
sameSiteValue of SameSite
partitionedStores the cookie in partitioned storage (CHIPS), for cookies used in third-party contexts
priorityValue of the Priority attribute

I tested the examples below with Express 5.3 and cookie-parser 1.4.

For a cookie that identifies a logged-in user, I’d start from this:

res.cookie('sessionId', 'a1b2c3', {
  maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
  httpOnly: true,
  secure: true,
  sameSite: 'lax'
})

This produces the header:

Set-Cookie: sessionId=a1b2c3; Max-Age=2592000; Path=/; Expires=Wed, 16 Dec 2026 06:02:41 GMT; HttpOnly; Secure; SameSite=Lax

Notice one thing: maxAge in Express is in milliseconds, but the Max-Age attribute in the header is in seconds. Express converts it, and also adds a matching Expires. If you pass maxAge: 3600 thinking of one hour, the cookie lasts 3.6 seconds.

sameSite: true is the same as 'strict'.

Reading cookies

Express doesn’t parse the Cookie request header for you. Without extra middleware, req.cookies is undefined.

Install cookie-parser:

npm install cookie-parser

Then add it:

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

const app = express()
app.use(cookieParser())

app.get('/', (req, res) => {
  console.log(req.cookies.username) // 'Flavio'
  res.send('ok')
})

A cookie you set with res.cookie() is not in req.cookies during the same request. It shows up from the next request, when the browser sends it back.

Signed cookies

A user can edit their cookies in the browser. If you want to know when that happened, sign the cookie.

Pass a secret to cookie-parser, and set signed: true:

app.use(cookieParser(process.env.COOKIE_SECRET))

app.get('/login', (req, res) => {
  res.cookie('userId', '42', { signed: true, httpOnly: true })
  res.send('ok')
})

app.get('/me', (req, res) => {
  console.log(req.signedCookies.userId) // '42'
  res.send('ok')
})

Signed cookies are in req.signedCookies, not in req.cookies. If someone changes the value, the signature doesn’t match anymore and you get false instead of the value.

Signing doesn’t hide anything. The cookie looks like s:42.<signature>, so anyone can read 42. Never put secrets in a cookie. For login state, store a session ID in the cookie and keep the data on the server, which is what Express sessions do.

Storing an object

You can pass an object as the value:

res.cookie('cart', { items: [1, 2, 3] })

Express serializes it as JSON with a j: prefix. cookie-parser recognizes the prefix and turns it back into an object, so req.cookies.cart.items is [1, 2, 3].

A cookie can be cleared with:

res.clearCookie('username')

This sends a Set-Cookie header with an expiration date in the past, and the browser deletes the cookie.

The catch: the browser only deletes it if the path and domain match the ones you used to set it. This doesn’t work:

res.cookie('admin', 'yes', { path: '/admin' })

// later
res.clearCookie('admin') // sends Path=/, the cookie stays

Pass the same options:

res.clearCookie('admin', { path: '/admin' })

In Express 5, clearCookie() ignores the expires and maxAge options, so you can pass the same options object you used for res.cookie().

Want me to talk about your product? You can sponsor this site.

Related posts about express: