Home > front end >  Express Session Not Saving
Express Session Not Saving

Time:05-17

I know other people have run into this, but my Express session is not saving. I looked through as many questions and threads and I could but couldn't find a fix. Please let me know what I'm doing wrong. Thanks!

Here's where it's initialized:

app.use(session({
  secret: 'BigSecret',
  resave: true,
  cookie: {
    maxAge: 24 * 60 * 60 * 1000 * 7, //seven days
    secure: false
  },
  saveUninitialized: true
}));

And where it's used in the route:

router.get('/route', async (req, res) => {
    if (!req.session.views) {
        req.session.views = 0;
    } else {
        req.session.views  
    }
    console.log(req.session);

    ...the rest of the route...

    res.render('pages', {
        key: val,
        anotherKey: anotherVal
    }
});

Also, for some context, I'm returning a rendered EJS page so that's what the render is at the end.

CodePudding user response:

The issue may be in this code here:

if (!req.session.views) {
  req.session.views = 0;
} else {
  req.session.views  ;
}

The first request, the value of req.session.views will be undefined, so !req.session.views will evaluate to true and you’ll set the value to 0.

The next request, and every request thereafter, the value of req.session.views will be 0. Each time !0 will evaluate to true and you’ll just set the value to 0 again.

You probably want to change it to something like if (!('views' in req.session)) or if (typeof req.session.views === 'undefined') etc.

Alternatively you may wish to just set req.session.views = 1; on the first request since this is the first view. Then on the second request !req.session.views will be !1 which will evaluate to false, and your value will be incremented.

  • Related