Search code examples
node.jsexpressibm-cloudexpress-session

Bluemix Node.js work with session in multiple instances


I have a problem in my bluemix application when the project has two or more instances.

If I keep the project with only one instance, this code works as expected and when the url '/load' is called, I receive the data saved in the '/save'. But, when I put more instances in the application, the '/load' sends nothing is most times.

Its like the session is saved in one instance of the project and when the user hits another url, the '/load' is being executed in another instance.

So, does anyone knows how to make sure that the user only use one instance or share the session value between the instances?

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

var app = express();



app.use(express.static(__dirname + '/public'));

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

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

var appEnv = cfenv.getAppEnv();

app.get("/save", function (req, res) {
   req.session.fullname = "John Galt";
   res.send("Saved session");
});

app.get("/load", function (req, res) {
   res.send(req.session.fullname);
});

app.listen(appEnv.port, '0.0.0.0', function () {
   console.log("server starting on " + appEnv.url);
});

Solution

  • You should design your app as stateless process. This is actually one of the 12 factors (see 12 factor app).

    If you want to share a state between invocations and between instances of your app, a common practice is to use a database to store that data. There are frameworks to allow caching of data/states across the instances.