Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

409
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda