MegaRacer MegaRacer - 7 months ago 19
Node.js Question

How to use variable as secret key in express-session's session object

I have an express.js file which requires config.js which loads development.js. Now I want to use secret as a variable in session object of express-session. I will give you a quick breakup of how I had setup my code so far.

Config folder


-- development.js

-- config.js

-- express.js


module.exports = function(){
sessionSecret: 'developmentSessionSecret'


module.exports = require('./env/' + process.env.NODE_ENV + '.js' );

** Express.js **

var config = require('./config'),
session = require('express-session');
saveUninitialized: true,
resave: true,
secret: config.sessionSecret

The problem is that console.log(config.sessionSecret) is undefined.
Why this is not working and what will be the correct way to set up ?


Your development.js is exporting a constructor function which you never call (and it doesn't return anything either).

Based on the syntax you used in the callers, you probably meant for development.js to be this:

module.exports = {
    sessionSecret: 'developmentSessionSecret'

where it just exports a static object that can be directly used by the rest of your code.