Search code examples
node.jsexpresssessioncookiesnode.js-connect

Difference between secret of connect.session and connect.cookieParser?


I'd like to use secure cookies in my Express application using Connect's modules connect.session and connect.cookieParser. As per the docs, both accept a secret parameter. This key is used to prevent the user from tampering with the cookie.

Should I set the same key to both modules, or two different ones? Or should I only pass a key to one of them?


Solution

  • You only need to set it with one or the other. Though, you can pass to each in order to give them different secrets to use.

    The difference between them is in their so-to-say "greediness" with it.

    • session(secret) will keep the secret to itself, only using it for the cookie holding the session ID.

    • cookieParser(secret), on the other hand, will allow for any cookie to be signed.

      You can create signed cookies with Express' response.cookie().

      Signed cookies are also supported through this method. Simply pass the signed option. When given res.cookie() will use the secret passed to express.cookieParser(secret) to sign the value.

      res.cookie('name', 'tobi', { signed: true });
      

      Later you may access this value through the req.signedCookies object.