G.D
G.D

Reputation: 315

Express creating new session for each request

Express-session is creating a new session (new sessionID) for new request. And it happens intermittently, for example sometimes for first 3-4 hits it will work fine and keep using same existing session and on 4th hit it will create a new one, Sometimes it will create new session on first request itself.

Also this Issue comes on my hosted website. It works fine on localhost.

Things that i have already tried and are not working..

  1. Express session is created after static file routes.
  2. Express session secret and cookieParser secret are set to same.
  3. Using app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); for favicon.
  4. Setting very high value for max-age field while creating cookie.

Below is my app.js snippet -

var passport = require('passport');
var expressSession = require('express-session');
var app = express();
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views/partials'
}));
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));
var flash = require('connect-flash');
app.use(flash());

var initPassport = require('./passport/init');
initPassport(passport);
//app.use(bodyParser.urlencoded());
app.use(cookieParser('mysecret'));
app.use(expressSession({ secret: 'mysecret', name:'user', cookie: {maxAge: 60000000}}));
app.use(passport.initialize());
app.use(passport.session());

Any kind of help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 3577

Answers (2)

Genia
Genia

Reputation: 80

For those landing here for a similar multi session creation, I solved my issue by setting this flag in the session middleware to false. It saves your cookie in DB only when it has been updated with some additional data like an email for example. `

saveUninitialized: false

Upvotes: 1

enRaiser
enRaiser

Reputation: 2636

why don't you use MongoStore to store session data? may be that will solve your problem.

 app.use(session({
     secret: 'mysecret',
     resave: false,
     saveUninitialized: false,
     expires: new Date(Date.now() + (60 * 60 * 24 * 7 * 1000)),
     cookie: {  } ,
     store: new MongoStore({mongooseConnection: mongoose.connection})
 }));

Upvotes: 1

Related Questions