Signing cookies in express

Viewed 10000

If I understood cookie signing correctly, then what it does is: Sign a cookie with a secret when setting it. Unsign the cookie with the same secret to validate that it hasn't been changed when recieving it.

Now in expressjs there is res.cookie() to set cookies and that takes a "signed" boolean to set if the cookie should be signed or not.

Now, what secret is used for signing? I think it might use the secret provided to cookieParser(), but that isn't actually mentioned explicitly in the documentation anywhere.

So my question is essentially: How do I set the secret to be used for signing cookies in expressjs?

I did read the express documentation and searched google and stackoverflow for an answers, sorry if I am missing something obvious.

3 Answers

Express will indeed use the secret provided to cookie-parser to sign your cookie. Cookie-parser will inject the secret into your request object. Then, express will use it in order to sign the cookie. If no secret is provided to cookie-parser (or another middleware), then express will throw an error when trying to set a new signed cookie.

Answering your question, that's how you should set the secret (using cookie-parser):

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser('your-secret'))

app.get('/', (req, res, next) => {
  res.cookie('name', 'value', { signed: true })
  res.json({})
})

Then it will be available in req.signedCookies.

This cookieParser() takes secret and option. For signed cookie, you can access through req.signedCookies and for unsigned cookies just req.cookies. For sending cookies with response use cookie-like

app.use(cookieParser('12345'));
     res.cookie('username', 'john doe', { maxAge: 900000, httpOnly: true, signed: true, secret: '12345' });
    res.cookie('user_name', 'anik islam', { maxAge: 900000, httpOnly: true, signed: false, secret: '12345' });

And you can access cookies like

console.log(req.cookies);
console.log(req.signedCookies);
Related