Search code examples
node.jsexpresscookie-session

How to create a cookie with node cookie-session


I am running a small node app. And I am trying to get it to create a cookie for each visitor, called 'session' that contains - for example - the session id. But I cannot seem to get node to create a cookie through cookie-session. My code so far:

const fs = require('fs');
const http = require('http');
const https = require('https');
const privateKey = fs.readFileSync('PATHTOKEY');
const certificate = fs.readFileSync('PATHTOKEY');
const credentials = {key: privateKey, cert: certificate};
const Keygrip = require("keygrip");    

const express = require('express');
const app = express();    

const port = APORTNUMBER;
const secureport = APORTNUMBER;
const helmet = require('helmet');    

const options = {
  dotfiles: 'deny',
  etag: true,
  extensions: ['html', 'htm'],
  index: 'index.html',
  lastModified: true,
  maxAge: 0,
  redirect: true,
  setHeaders: function (res, path, stat) {
    res.set('x-timestamp', Date.now())
  }
};    

app.use(express.static('public', options), helmet());    

So far, no problems. But then comes the middleware cookie-session.

const session = require('cookie-session');
const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour    

app.use( 
  session({
    name: 'session',
    keys: new Keygrip(["MYSECRET1", "MYSECRET2"]),
    cookie: {
      secure: true,
      httpOnly: true,
      expires: expiryDate
    }
  })
);    

Above, I've specified the middleware to use these cookie-session parameters, but how do I proceed from here to actually get it to create this cookie?

const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);    

httpServer.listen(port);
httpsServer.listen(secureport);    

console.log("Node server started");

Solution

  • Well, after trying this myself I manages to successfully use the cookie-session middleware. yay

    I'm using the middleware like this:

    app.use(cookieSession({
      name: 'session', // replace this with your own name to suit your needs
      keys: [ 'your-secret-key-goes-here', 'your-secret-key-goes-here' ]
    })
    

    About the duplicate values in keys option - the docs and related examples always use 2 different keys, despite the TypeScript @types lib declares that

    The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.

    So.. I've used only one key.. twice... and it works as excepted

    Note that I'm using this middleware before I'm registering the express app routes in order for this middleware to take effect before the router is executed (per request)

    In each of my routes I can use the middleware using something like this

    app.get('/test', (req, res) => {
      req.session.test = { a: 5, b: 7} // yes - JSON payload are valid :)
    })
    

    To verify - ensure that your initial request got the following headers

    Set-Cookie: session=eyJ0ZXN0Ijp7ImEiOjUsImIiOjd9fQ==; path=/; secure; httponly
    Set-Cookie: session.sig=D4VVF4XSbBEWXI4b04ZvybAxppw; path=/; secure; httponly
    

    This is only an example where the session is the name of the cookie as I've defined earlier. Cheers