Send error message on redirect
Server side:
res.redirect('/login?error=' + encodeURIComponent('Incorrect_Credential'));
In view there will be a alert (Hope you guys are using bootstrap). But initially it will be hide. If error comes, it will be shown.
<div class="alert alert-success" role="alert" id="loginAlert">
<p style="text-align: center;">Incorrect Credential</p>
</div>
Showing Technique:
<script>
$('#loginAlert').hide();
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('error');
if(myParam == "Incorrect_Credential") {
$('#loginAlert').show();
}
</script>
With a redirect alone, it's not really possible to pass options other than in the query-string:
res.redirect('/login?e=' + encodeURIComponent('Incorrect username or password'));
A redirect instructs the client to start a new request and HTTP is on its own stateless.
To keep the message otherwise, you'll need a form of persistence to hold it for that next request -- cookies, sessions, etc.
req.session.error = 'Incorrect username or password';
res.redirect('/login');
Then:
res.render('login', { error: req.session.error });
delete res.session.error; // remove from further requests
This is also what Express 2's req.flash()
helped accomplish. And, a variant of it is still available for use with Express 3 and later -- just as connect-flash
rather than being bundled.