I am trying to pass a parameter from one middleware to the next. The first middleware is just storing a secret key in req.cookieKey. The second middleware is using express's cookie-session. Normally I would know how to do this but something is breaking when I try to return cookieSession( in the second middleware. See my code below and an example on codesandbox.io linked at the bottom.
This middleware comes first:
const asyncMiddleware = async (req,res,next) => {
const data = await SecretKeeper.getCredentialPair('cookie');
req.cookieKey = data.credential;
next()
}
In my routes I am calling:
//get key from SecretKeeper to encrypt cookie that will be set in next middleware
app.use(asyncMiddleware);
//set cookie middleware, use key from SecretKeeper to sign and verify cookie
app.use((req, res, next) => {
return cookieSession({
name: 'MySession',
keys: [req.cookieKey],
// Cookie Options
maxAge: .30 * 60 * 60 * 1000 // 30 min
})
})
It works if I don't try to add in the key from SecretManager (the first middleware) and I remove the extra function layer (req, res, next) =>
from my second middleware.
I was hoping I could use the req.cookieKey that I set earlier and then just return the cookieSession function but that doesn't seem to be working. I tested to make sure that I can get the req.cookieKey when I am setting cookie middleware but for some reason I can't get the cookieSession to work correctly. Anyone have any suggestions? I have included the working version without passing the parameter here: https://codesandbox.io/s/l2lw7499q9
cookieSession(options)
returns function(req, res, next)
, so you must run it:
app.use((req, res, next) => {
cookieSession({
name: 'MySession',
keys: [req.cookieKey],
// Cookie Options
maxAge: .30 * 60 * 60 * 1000 // 30 min
})(req, res, next) //here
})