Search code examples
node.jsexpress

"secret" option required for "app.use(express.cookieSession())"


The website does not specify any requirement of 'secret' for using app.use(express.cookieSession()); but when using the same in express it calls for 'secret option required. Why?

Even when I provide secret app.use(express.cookieSession({secret: 'abc'})); the following error shows in browser:-

TypeError: Cannot read property 'connect.sess' of undefined


Solution

  • you can't use cookies without supplying a crypting key and secret. You can either pass the secret in the cookie parser, or you can be more elaborate and pass all the necessary values when setting up session management. The latter offers greater control and as such is usually the better idea.

    ...
    app.use(express.compress());
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.cookieSession({
      key: "mysite.sid.uid.whatever",
      secret: process.env["SESSION_SECRET"],
      cookie: {
        maxAge: 2678400000 // 31 days
      },
    }));
    ...
    

    (having different secrets for different users is even better of course, but requires a lot more work)