I'm using express-sessions in a project and I'm struggling to understand when it creates a cookie on the browser to use with the session storage.
In my project when I request my home page ("/") a cookie isn't created, however when I request any other page a cookie is created. If I'm away from the homepage (i.e. "/user/signup"), delete the cookie from the browser and then navigate back to the homepage, it doesn't create a cookie for the session storage.
My problem is understanding why it creates a session cookie for every other request apart from the home page.
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({
secret: 'mysupersecret',
resave: false,
saveUninitialized: false,
store: new mongoStore({
mongooseConnection: mongoose.connection
}),
cookie: {maxAge: 180 * 60 *1000}
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/user', userRoutes)
app.use('/', indexRoutes);
router.get('/', function(req, res, next) {
Product.find(function(err, docs){
if(err){
console.log(err);
} else {
var prodRows = [];
var rowLength = 3;
for(var i = 0; i < docs.length; i += rowLength){
prodRows.push(docs.slice(i, i + rowLength))
};
res.render('shop/index', { title: 'Shopping Cart', prods: prodRows});
}
});
});
router.get('/user/signin', function(req, res, next){
console.log('Session2: ', req.session);
console.log('Cookies2: ', req.cookies);
var messages = req.flash('error');
console.log('Session3: ', req.session);
console.log('Cookies3: ', req.cookies);
res.render('user/signin', { csrfToken: req.csrfToken(), messages: messages, hasErrors: messages.length > 0});
});
Any help would be much appreciated.
You are not receiving a cookie on your home page because 'saveUninitialized' is set to 'false'. When you navigate to your home page a session is created but it is never modified thus never saved. If you set 'saveUninitialized' to 'true' then it will be saved whether anything is modified or not and this will fix your problem.