4

I'm new to NodeJS. I am developing a REST API and using express-session to deal with sessions. So, to get the session ID I'm using

var sessionID = req.sessionID

This sessionID is generated from the server side. So, when I scale up to two or more servers, this is a problem. For example, if one server shuts down and the request is redirected to another server (Assuming I have a load balancer), a new session ID is generated. So, is there a way to retrieve the session ID from the client side?

  • You can't. Push sessions to `Redis` or whatever database you like, but cookie-based sessions should be foregone. Authorization headers are recommended. – Explosion Pills Oct 01 '15 at 02:10

1 Answers1

5

Good question! Session management can be challenging to get up and running with - especially since to get up and running with any sort of sophisticated session management in node you need a ton of different packages, each with their own set of docs. Here is an example of how you can set up session management with MongoDB:

'use strict';

var express = require('express'),
  session = require('express-session'),
  cookieParser = require('cookie-parser'),
  mongoStore = require('connect-mongo')(session),
  mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/someDB');

var app = express();

var secret = 'shhh';

app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secret,
  store: new mongoStore({
    mongooseConnection: mongoose.connection,
    collection: 'sessions' // default
  })
}));

// ROUTES, ETC.

var port = 3000;

app.listen(port, function() {
  console.log('listening on port ' + port + '.')
});

This configuration gives you access to req.sessionID but now it should persists across app servers if the user's session cookie has not expired.

I hope this works!

Huston Hedinger
  • 511
  • 2
  • 9
  • 1
    Thank You! Now, I have another question here. So, in my case I should run mongo in a different server (that is I should have a third server running)? So that it is "shared" between the two? Because giving 'localhost' would bring the Store down when the entire server shuts down right? – Aishwarya Krishnan Oct 02 '15 at 20:35
  • This is a "big" question that you are asking, and I don't think I can do it justice... You don't HAVE to store mongo on a third server. Which ever app server is NOT on the same host would then need to make request from Mongo based on the IP and port of the server Mongo is running on... The reality is, if you are going to the trouble of deploying multiple app servers behind a load balancer and your app demands that sort of scale, it will likely make sense to put mongo on a third server. Check out how to configure a mongo connection [here]( http://mongoosejs.com/docs/connections.html). – Huston Hedinger Oct 02 '15 at 21:16