node.jsexpressejsexpress-sessionconnect-flash

Flash message won't display in client side, how to solve?


I have been following this youtube tutorial and I'm trying to figure out how to work with connect-flash npm. This is the code I'm using:

SERVER-SIDE:

//app.js
const session = require('express-session');
const flash = require('connect-flash');

app.use(session({
  name: SESSION_NAME,
  resave: false,
  saveUninitialized: false,
  secret: SESSION_SECRET,
  cookie: {
      maxAge: SESSION_LIFETIME,
      sameSite: true,
      secure: IN_PROD
  }
}));
app.use(flash());

//users.js
//somewhere in USER LOGIN POST REQUEST:
if(!results.length) {
    console.log("    > Cannot fetch user from the database");
    req.flash('flash', 'some message in the alert');
    return res.redirect('/user_login');
}      

//USER LOGIN GET REQUEST:
router.get('/user_login', redirectHome, (req, res) => { 
    return res.render('userEntries/login', {message: req.flash('flash')});
});

CLIENT-SIDE (EJS)

<body>
    <% if(message.length > 0) { %>
        <div class="alert alert-success" style="text-align: center">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            <strong>INTRO: </strong>  <%= message %>
        </div>
    <% }%>
    ......

Now, the post and get request work fine in my application, but I just have no idea why flash messages won't work. These are the stuff I have tried:

Please note that sometimes the alerts will work, and sometimes the messages are passed multiple times! In the figure below, I've added an invalid username and password twice, waited for approx. five minutes and reloaded the page and this what happened:

DEMO

I have no idea what I'm doing wrong. If you have any useful information please let me know. Thanks


Solution

  • It's because you are printing the errors like this

       <%= message %>
    

    It won't work because message is an array. You can display your errors like below

        <%= message[0] %>
    

    OR you can loop through your message array.

     for( m of message) {
             <%= m %>
     }