MegaRacer MegaRacer - 1 year ago 102
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 ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download