2

im trying to set up a session in NodeJS and use it in my /auth route after that but i'm getting undefined troubles with the session.

In the app.js :

const express = require('express'),
  path = require('path'),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose'),
  config = require('./config/DB');

const app = express();
  const session = require('express-session')
  const MongoStore = require('connect-mongo')(session);

mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => { console.log('Database is connected') },
  err => { console.log('Can not connect to the database' + err) },
  options
);
const db = mongoose.connection


const adUnitRoutes = require('./routes/adunit.route');
const userProfileRoutes = require('./routes/userprofile.route');


app.use('/adunits', adUnitRoutes);
app.use('/userprofile', userProfileRoutes);

app.use(session({
  secret: 'my-secret',
  resave: false,
  saveUninitialized: true,
  store: new MongoStore({ mongooseConnection: db })
}));

In the route :

userProfileRoutes.route('/authentification').post((req, res) => {

  console.log('req session : ' + req.session.userId);
//here I got cant read property of userId because session is undefined

});

1 Answers1

0

This happens because you are setting your routes before adding the middleware. Your handlers are essentially middleware so if they are added before session, your session has not been processed and added to the request yet.

Adding the routes after setting your middleware will make it work as expected.

See this minimized example:

const express = require('express');
const app = express();
const session = require('express-session');

app.get('/broken', (req, res) => {
  console.log('req session : ' + req.session.userId);
  res.write(String(req.session.userId));
  req.session.userId = 1;
  res.end();
});

app.use(
  session({
    secret: 'my-secret',
    resave: false,
    saveUninitialized: true
  })
);

app.get('/ok', (req, res) => {
  console.log('req session : ' + req.session.userId);
  res.write(String(req.session.userId));
  req.session.userId = 1;
  res.end();
});

app.listen(8089);
lucascaro
  • 16,550
  • 4
  • 37
  • 47
  • Seems logic but I missed it. I'll remember it, thanks. But after refactoring and placing the session before the routes, I'm still getting an undefined statement for req.session.userId after my ('/auth').post route. Any other suggestions? –  Nov 09 '18 at 08:10
  • do you mean `req.session.userId` is `undefined` or `req.session` is `undefined`? The former would make sense until you set the value in the session (`req.session.userId = 1;`), the latter would mean the error is in the difference between your code and my minimal example. – lucascaro Nov 09 '18 at 08:14
  • Yeah my bad, I think I missed one thing. Do we have to manually assign a value to the req.session.userId? I thought the assignment of a default value was automatic. Thanks for the help –  Nov 09 '18 at 08:18
  • Yes, you control the value of everything in your `req.session` (your `userId` is application logic specific to your service). Glad to hear it helped! – lucascaro Nov 09 '18 at 08:25
  • Im just getting confused about smthing and maybe you could help me (once again :P). On the page after auth, my userId is well defined as I wanted like Session { cookie: ... } , {userId : idFromDB}. But after navigation, this userId disapears and the Session is now like Session {cookie : ...} without the variable userID. Isnt the session supposed to keep in memory cache the variable through all pages, so I can use it anywhere on the app? Thanks in advance –  Nov 09 '18 at 09:50
  • As far as I know the session should persist between calls, if that's not working I would need more context to be able to know what's going on. Feel free to add another question with a [mcve] of the new error and let me know :) – lucascaro Nov 10 '18 at 01:09
  • https://stackoverflow.com/questions/53224056/req-session-userid-disapears-on-other-nodejs-routes Here is the topic a little more detailled, if you could help me I'd be grateful :) –  Nov 12 '18 at 21:51