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

281
Views
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
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!