Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

403
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda