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

289
Vistas
session timeout in a nodejs + express app using setTimeOut( ) and a callback, and redirect the user to login page

I am trying to implement a session time out for a nodejs + express + passport app. I am using setTimeOut() to call a method where I am calling req.session.destroy() and req.logout() (for logging out passport session) to invalidate the session.

I am passing in the req and res to setTimeOut - setTimeOut(timeOutMethod, 10000, req, res). I see the session being set to null. I verified the request objects during different times, and they match.

I want to be able to call /logout endpoint in the timeOutMethod() (this is a callback for the setTimeOut()) or go back to the main page, but there will be no context. I can't use a res object to redirect the user. The app actually crashes at this point.

Is there anyway we can redirect or refresh the page so that user the sent back to the login screen?

Can someone please help me with this? Thanks a ton in advance!

:Code:

router.get(callback_url, passport.authenticate(login_strategy, {failureFlash: true, failureRedirect: '/page'}),
    function (req, res) {
        if(req && req.session){//max timeout is set to 1 min for testing...
            setTimeout(sessionTimeOut,  1 * 60 * 1000, req, res);
        }
        res.redirect('/');
    });

// a callback for session timeout...
function sessionTimeOut(req, res){
    if (req.session) {
        req.session.destroy(err => {
            if (err) {
              //log statements
            }
            else {
              //log statements
                if (req.user) {
                    //remove passport.js session user value if present
                    req.logout();
                }
            }
        });
        req.session = null;
    }
    else {
        //log statements
    }
    res.redirect('/page');
}

//error thrown when es.redirect('/page') as we don't have the context here.
_http_outgoing.js:561
[0]     throw new ERR_HTTP_HEADERS_SENT('set');
[0]     ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0]     at ServerResponse.setHeader (_http_outgoing.js:561:11)
about 4 years ago · Juan Pablo Isaza
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