4

I have issue with express-session in node js and express 4. I set a session variable inside routes/index.js and is not available in app.js.But available on another route file users.js

routes/index.js

var sess;
router.get('/setsession',function(req,res){
    sess=req.session;
    sess.username="safeer"; 
    res.send("hi "+sess.username);
});

router.get('/getsession',function(req,res){
    sess=req.session;
    res.send("hi "+sess.username); //here session value available
});

routes/users.js

var sess;
router.get('/session3',function(req,res){
    sess=req.session;
    res.send("hi "+sess.username); // here also session is available
});

app.js

var session = require('express-session');
app.use(session({secret: 'secret',saveUninitialized: true,resave: true}));

var sess;
app.get('/session1',function(req,res){
    sess=req.session;
    res.send("hi "+sess.username); //here session is undefined
});
app.use('/', routes);
app.use('/users', users);

Can anyone give me a solution please. ?

Mohammed Safeer
  • 20,751
  • 8
  • 75
  • 78
  • Is `sess` a global (unscoped) variable? If so, you should expect undefined behaviour. Also, how and where are you declaring the `express-session` middleware? – robertklep Jun 03 '15 at 10:09
  • sess is defined. not included in code snippet. express-session is defined in app.js. i'll edit code snippet. – Mohammed Safeer Jun 03 '15 at 10:14
  • You're declaring `sess` as a module-scoped variable, which means that concurrent requests will overwrite it. It needs to be scoped to each request handler instead. – robertklep Jun 03 '15 at 10:21
  • we rewrites inside each request handler as sess=req.session; req.session matters i think – Mohammed Safeer Jun 03 '15 at 10:25
  • 1
    Once you start making async calls from within your request handlers, you will run into undefined behaviour because concurrent requests are sharing the same `sess` variable. This most likely isn't causing the problem you're describing here, but I felt it deserved a warning at least. – robertklep Jun 03 '15 at 10:28

1 Answers1

2

I suggest you set username in session:

In routes/index.js

router.get('/setsession',function(req,res){
       req.session.username="safeer"; 
       res.send("hi "+ req.session.username);
});

And in app.js

app.get('/session1',function(req,res){
    res.send("hi "+ req.session.username); //get from session. Can be set in variable too

});

BrTkCa
  • 4,703
  • 3
  • 24
  • 45