Search code examples
node.jsreactjsexpressexpress-session

Redirect to login page after session timeout using nodejs, expressjs and reactjs


i have node and react application. for middleware i am using expressjs.

i am trying to redirect to login page after session time out. i am using express-session for authentication, i am able to get session timeout but not able to redirect to login page.

My login url is http://localhost:8009/login which is implemented in react js for ui part. app.use('/', login); router in node and expressjs

below is my code.

var session = require('express-session');

app.use(session({
    secret: 'Test Service',
    name: "test",
    saveUninitialized: true,
    resave:false,
    cookie: {
        //maxAge: 24 * 60 * 60 * 1000,
        path: '/login',
        maxAge: 1 * 10 * 60 * 1000, 
        overwrite: false    
    }
}));

can anyone help me on this. i have also checked below urls but not able to get the solutions.

How to keep the session active when redirecting from domain to subdomain in Express js/ https://gitlab.com/dinh.dich/express-session-expire-timeout#README


Solution

  • In my opinion, here are two options you have

    1 - if you are talking about session and redirecting if there is no session :

    Create a function in your router as such :

    module.exports.home = (req,res)=>{
    if(!req.session.user){
        //index is the main page without any session
        res.render('index');
    }
    else{
        //render to a different page
    }
    };
    

    Hopefully this will give you a better idea. Good luck !