node.jsexpressejsconnect-flash

Flash message not displaying after logging out


Log out route

router.get('/logout', (req, res) => {
  delete req.session.returnTo;
  req.flash('success', 'Successfully Logged Out!');
  req.session.destroy();
  res.redirect('/home');
})

Route for rendering home view

app.get('/home',(req,res) =>{
    const isLoggedIn = req.session.user ? true : false;
    res.render('home', { isLoggedIn });
})

Home view

<% } if (!isLoggedIn)  { %>
        <% if (success.length > 0 ) {%>
          <div class="alert alert-success alert-dismissible fade show" role="alert">
            <%= success %>
            <alert type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></alert>
        </div>
        <% } %>
   <% } %>

Explaination of main issue

My flahes are working fine for every other route and view for example login and signup the only issue i am facing is that in my logout route after deleting the session the flash message does not appear

when i removed the code req.session.destroy(); the flash message worked fine i a;so searched internet to find solution but didnt find something usefull. your help will be appreciated a lot.


Solution

  • As we know destroying a session will affect its dependent references, therefore the flash messages if any stored in the session object will also be lost. Please see below for two workarounds:

    Use a global property as below.

    app.get('/logout', (req, res) => {
      delete req.session.returnTo;
      req.session.destroy();
      global.location = 'logout';
      res.redirect('/home');
    });
    
    app.get('/home', (req, res) => {
      const isLoggedIn = req.session.user ? true : false;
      if (global.location == 'logout') {
        req.flash('message', 'Successfully Logged Out!');
        delete global.location;
      }
      res.render('home', { isLoggedIn });
    });
    

    Use redirect with a query string as shown below.

       app.get('/logout', (req, res) => {
          delete req.session.returnTo;
          req.session.destroy();
          res.redirect(
            require('url').format({
              pathname: '/home',
              query: {
                location: 'logout',
              },
            })
          );
        });
        
        app.get('/home', (req, res) => {
          const isLoggedIn = req.session.user ? true : false;
          if (req.query.location == 'logout') {
            req.flash('message', 'Successfully Logged Out!');
          }
          res.render('home', { isLoggedIn });
        });
    

    Citations:

    How do I redirect in expressjs while passing some context?

    how to send flash logout message express or check if redirected