2

I would like to use the sessions from express.js, i know we can catch a session id from req.session.id, and i also know this id is always different (each time we visit a route):

I saw some people recommand to get and save the session in a global, but the problem is (except if i am wrong), if i save the session when a user connect my application this way:

app.get('/init', function(req, res) {                                                                                                                                    
        global.session = req.session;                                                                                                                                                                                                                                                        
    });

If User_1 connect my application, then User_2 connect my application and User_1 still there, global.session will contain the value of the User_2 session even for User_1 right ?

If i am right, how to save the the session properly ? I thought about an Array indexed by req.session.id from the init route but since this is always different even if the same user visit the same route (is it normal ?), it's impossible to prcess like this.

What is the best way you found to manage the sessions ?

Thanks !

1 Answer 1

1

Don't save sessions in a global variable, since that means each subsequent visitor to the site will use and modify that same variable (your using the same instance of express to handle all requests that come in.) You can use express's built in middleware to store sessions in memory while you're developing your application. Just put the following middleware before you start declaring your routes:

app.use(express.cookieParser()); /* Parses cookies. */
app.use(express.cookieSession({ secret: 'yoursecret' })); /* Handles sessions stored in your cookies. */
// ... your other middleware

app.get('/', function(req, res) {
    if (req.session) {
        res.json(req.session);
    } else {
        res.send('You have no session.');
    }
});

For production, it's recommended to use something like Redis to store your sessions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.