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

279
Visualizações
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 à 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