Unable to access req.session variables in Express / NodeJS

I have seen many variations of this question, but no one seems to have solved my problem. I am trying to configure a Node.js server using Express . Here is my server configuration:

 var express = require('express'), RedisStore = require('connect-redis')(express); var app = express(); app.use(express.urlencoded()); app.use(express.json()); app.use(express.cookieParser()); app.use(express.session({ store: new RedisStore(), secret: APP_SECRET })); // Initialize redis connection var client = redis.createClient(); client.on('connect', function() { console.log('Connected to Redis server') }) client.on('error', function (err) { console.log('Error ' + err); }); // Enable cross-origin resource sharing app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); var api = require('./controllers/api.js'); app.post('/login', api.login); app.get('/auth', api.auth); app.listen(3000); 

And here are some simple routes:

 exports.login = function(req, res) { var user = new User(req.username, req.password); req.session.user = user; console.log(req.session.user); //works res.json({user:user}); } exports.auth = function(req, res) { console.log(req.session.user); //doesn't work res.json(req.session.user); } 

So, in my login route, I can print the session variable as expected. But if I visit the auth route after visiting the login route, the session variable is undefined. How can I get Express Sessions to work?

+8
javascript session express
source share
3 answers

In a typical web application, the credentials used to authenticate the user will only be transmitted during the login request. If authentication succeeds, a session will be created and maintained through a set of cookies in the user's browser.

Each subsequent request does not contain credentials or all user data, but rather a unique cookie that identifies the session. To support login sessions, you must serialize and deserialize user instances per session and from session in each request.

In your case, you assigned req.session.user = user; only in the /login request. It will not be available for further queries ( /auth ).

You should get the user information in the /auth request also by session ID. (Or) Better you can use passport for authentication.

+4
source share

I think maybe your redis client doesn’t connect well, try something like this and be sure to start the redis service

 sudo service redis-server start 

or the way you call the RedisStore variable, see an example

Example:

 var express = require('express'); var app = express(); var cookieParser = require('cookie-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); app.set('port',process.env.PORT || 3000); app.use(cookieParser()); app.use(session({ resave: true, saveUninitialized: true, store: new RedisStore({ host: 'localhost', port: 6379 }), secret: 'some string/hash secret' })); var counter=0; app.get('/', function(request, response){ //adding some value to request.session counter = counter+1; request.session.color = {'anyValue': counter}; // console.log('Session ID: ', request.sessionID); console.log('Session: ', request.session); response.send('some text counter: '+request.session.color['anyValue']); }); app.listen(app.get('port')); 
+1
source share

Currently, the accepted answer did not understand that express.session is already processing cookie-based sessions with the req.session object. I tried trimming your version without using redis and it worked. Looking at the connect-redis docs, it looks like you need to pass a session to connect-redis. You are currently transmitting his express. I believe that this will change your problem.

PS I would update your node / express versions as current express versions no longer have embedded middleware along with other improvements.

Later express versions:

 var session = require('express-session'); var cookieParser = require('cookie-parser'); var json = require('express-json'); var bodyParser = require('body-parser') 

Instead

 express.session express.cookieParser express.json express.bodyParser 
+1
source share

All Articles