Undying
Undying

Reputation: 141

How To Access Session Variables From Seperate Route Files

I am currently using express and express-session to save information. If I save a session variable like this in file 'routes/login.js'

req.session.user = "User1"

How do I then access that same variable from 'routes/index.js' because currently if I just do

console.log(req.session.user)

it will log undefined but if I do the same thing from inside 'routes/login.js' it will log "User1"

EDIT:

Inside 'routes/login.js' file will log "User1"

 var express = require('express');
    var redis = require('redis');
    var session = require('express-session');
    var RedisStore = require('connect-redis')(session);

    var router = express.Router();
    var client = redis.createClient();

    var store = new RedisStore({host: 'localhost', port: 6379, client: client, ttl: 260});

    router.use(session({
         resave: true,
         saveUninitialized: true,
         secret: "secret",
         store: store
        }));

    router.get('/user', function(req, res) {
        req.session.test = "User1";
        res.send(req.session.test); //Logs "User1"
    });

module.exports = router;

Inside 'routes/index.js' file will log undefined

var express = require('express');
var router = express.Router();
var config = require('../config/config')

/* GET home page. */
router.get('/', function(req, res, next) {
    console.log(req.session); //Logs undefined
});

module.exports = router;

Upvotes: 4

Views: 4323

Answers (2)

Dev Matee
Dev Matee

Reputation: 5947

use express-session in your entry point like app.js where your app is actually initialized

Before accessing routes in app.js put the following code

app.use(session({
         resave: true,
         saveUninitialized: true,
         secret: "secret",
         store: store
        }));

Remember to maintain the order.

Upvotes: 0

Undying
Undying

Reputation: 141

I was able to solve my problem by using the express session middle ware with my app and then accessing it from routes.

Inside app.js

app.use(session({
     resave: true,
     saveUninitialized: true,
     secret: "secret",
     store: store
 }));

Now I can save a variable to request.session and it will persist through both route files.

Upvotes: 1

Related Questions