0

I use express-session to set up session management in the following way:

var express = require('express');
var session = require('express-session');
var app = express();
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);

mongoose.connect('mongodb://localhost/sessionTest');


app.listen(3000, function () {
});

app.use(session({
    secret: 'justsomestuff',
    resave: false,
    saveUninitialized: false,
    cookie: {  } ,
    store: new MongoStore({mongooseConnection: mongoose.connection})
}));

app.get('/first', function (req, res) {
    console.log('first');
    req.session.test = 'Tester';
    req.session.save();
    console.log(req.sessionID);
    res.send(req.sessionID);
}); 

app.get('/second', function (req, res) {
    console.log('second');
    if (req.session)
            console.log('session exists');
    console.log(req.sessionID);
    console.log(req.session.test);
    res.send(req.sessionID);
});

But a new session is established with a new session id every time I call /first or /second with

curl 127.0.0.1:3000/first
curl 127.0.0.1:3000/second

I use

"connect-mongo": "^1.2.1",
"express": "~4.13.4",
"express-session": "^1.14.0",

All sessions are in the mongo database as well.

It seems such a straight forward issue, but I simply cannot figure it out.

Timo
  • 3
  • 1

1 Answers1

1

You are using curl. and curl don't support cookies implicitly. You have to pass the cookies value explicitly via command. and also read the cookie when the server is trying to set etc..

Why don't you test using browser.?

or If you still want curl then use -b and -c parameters like this.

curl -b cookies.txt -c cookies.txt 

-b tells curl to store incoming cookies in cookies.txt and -c tells curl to embed all cookies from cookies.txt into this request.

Moreover Increase cookies life by adding expires field.

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