4

Using express-session and storing session in files. However every request it is creating new session id and new file is getting created.

Here is the code which i am using to create the session.

app.use(session({ secret: 'keyboard cat',
  resave: false,store: new FSStore(options),
  saveUninitialized: false , 
  cookie: { maxAge: 1000,secure: false,httpOnly: true }
}))

However i want it should create a single session id for each user or until session expires.

Kishan Rajdev
  • 1,919
  • 3
  • 18
  • 24

1 Answers1

2

My issue was with MaxAge which I set it 1000 milliseconds i.e 1 sec. Therefore it was creating a new session id everytime. I have set it to 1 hour, it works fine.

Here is the complete code

var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);

app.use(session({ secret: 'keyboard cat',
    resave: false,
    store: new FileStore,
    saveUninitialized: false ,
    cookie: { maxAge: 3600000,secure: false, httpOnly: true }
  })
);

app.get('/', function (req, res) {
  if (req.session.views) {
    req.session.views++;
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>views: ' + req.session.views + '</p>');
    res.end();
  } else {
    req.session.views = 1;
    res.end('Welcome to the file session demo. Refresh page!');
  }
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
Kishan Rajdev
  • 1,919
  • 3
  • 18
  • 24