Maxim Maxim - 11 months ago 57
Node.js Question

Sessions on two local Node.js servers

I have two local Node.js servers:


  1. http://localhost:3000

  2. http://localhost:3001



I use express.js and passport.js for authentication. Authentication works correct, however if:


  1. I login on server 1

  2. I login on server 2



then session on server 1 disappears. How this could be prevented?

app.use(bodyParser());
app.use(cookieParser());
app.use(session({
secret: '12345',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());


passport.use(new LocalStrategy(
function(username, password, done) {
users.getActiveByUsername(username, function(err, user) {
if (err) {console.log(err); return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username' });
}
if (user.password != password) {
return done(null, false, { message: 'Incorrect password' });
}
return done(null, user);
});
}
));

passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(user, done) {
done(null, user);
});

app.post("/login", jsonParser, function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { res.status(400).send('Wrong username or password');return; }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.json({'success':'Successful login'});
});
})(req, res, next);
});

Answer Source

I assume you are using the same database for both of your applications.

You can't save sessions of different apps of the same host name on the same database by default. You have to make them distinguishable by using different names or prefixes.

If you are using express-session for handling your sessions, you can set different names via options:

app.use(session({
  secret: '12345',
  resave: true,
  saveUninitialized: true,
  name: 'app1'          // use a different name for the second app
}));

Read the official documentation of express-session for more info.

Note
if you have multiple apps running on the same hostname (this is just the name, i.e. localhost or 127.0.0.1; different schemes and ports do not name a different hostname), then you need to separate the session cookies from each other. The simplest method is to simply set different names per app.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download