Michael Seltenreich
Michael Seltenreich

Reputation: 3508

Session keeps resetting on Node.js Express

I have a basic post request:

router.post('/page',multipart(), function (req,res) {
    if(req.session.book=="") {
        console.log("Creating new session")
        req.session.book="Hello!"
    }

Which checks to see if there is a string in a session variable called 'book' and if the string is empty, a string is added to it.

My hopes is to get a new session variable when I post to this route only once. But for some reason, on every request I make, I get a console message saying "Creating new session" Why does the session variable keeps resetting?

Upvotes: 1

Views: 1268

Answers (1)

trex005
trex005

Reputation: 5115

once you add something to the session, you need to save it again to the sessionStore. That is generally done with req.session.save()

There are certain times when the session is automatically saved. When res.end is called, for example. But as you have experienced, that doesn't always happen, so I find it a good practice to save manually.

Upvotes: 1

Related Questions