Home > Blockchain >  express-session - is it possible to change the secret while the node app is running?
express-session - is it possible to change the secret while the node app is running?

Time:03-16

Usually the secret is hard-coded in node apps which use express-session, for example -

const session = require("express-session")
let RedisStore = require("connect-redis")(session)
const { createClient } = require("redis")
let redisClient = createClient({ legacyMode: true })
redisClient.connect().catch(console.error)
app.use(
  session({
    store: new RedisStore({ client: redisClient }),
    saveUninitialized: false,
    secret: "keyboard cat",
    resave: false,
  })
)

Obviously I can change this secret keyboard cat by editing the source and restarting the node script. It is possible to change it while the app is still running?

CodePudding user response:

As best I know there is no documented way to change the secret on a running set of express-session middleware. I can think of several "hack" approaches that do enough debug sleuthing to dip into the right private data structure in the express-session code or add a new method to express-session to change the secret or disable the original session middleware and install a new session middleware one with a new secret.

But, that would break any existing sessions that were active (because the cookie they are based is encrypted using that original secret) so it's probably not a practical choice.

My motivation is that I put most of my code on github and I prefer not to hard-code any passwords or secrets.

If this is your motivation, then usually, you make the session secret part of some configuration/deployment file that is NOT checked into github and is managed separately. This is the same type of config file you would put database passwords and other credentials needed for your server. That way, when your server starts up, it gets the credentials/secrets it needs from a local configuration file that is not stored in github.

Then, you also don't have to try to change a running session middleware secret on the fly either.


Now that you mention Heroku, here are the techniques that Heroku mentions for managing configuration variables:

https://devcenter.heroku.com/articles/config-vars

  • Related