Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

402
Views
Express Session Not Saving

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!