Flash Message on redirect - Express

Richlewis picture Richlewis · May 1, 2018 · Viewed 7.1k times · Source

I cannot get my flash message to show when using a redirect (though all ok when using a render)

If i use this code to render a view the message appears fine

req.flash('success_msg', 'Successfully Registered');
res.locals.message = req.flash();
res.render('home');

but if i want to redirect (which i do in this instance) then the message is not displayed

req.flash('success_msg', 'Successfully Registered');
res.locals.message = req.flash();
res.redirect('/');

index.js

// Global Vars
app.use(function(req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});

// Use Routes
app.use('/', routes);
app.use('/', users);

Any ideas on how to handle this please, if i havent provided enough info please let me know what to add here

What i have noticed though is that i can log out the message before the redirect

req.flash('success_msg', 'Successfully Registered');
var message = res.locals.message = req.flash();
console.log(message); // { success_msg: [ 'Successfully Registered' ] }
res.redirect('/');

But it never shows in my view

<% if (locals.message) { %>
  <div class="alert alert-success alert-dismissible fade show text-center" role="alert">
    <strong><%= message.success_msg %></strong>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
<% } %>

Thanks

Answer

rodurico picture rodurico · Jul 12, 2018

I'm pretty sure the problem is somewhere in the function for your global vars.

This works flawlessly here:

...
req.flash('msg', 'some msg');
res.redirect('/page');

And for the .get()

app.get('/page', (req, res) => {
    res.render('page', { flash: req.flash('msg') });
});

Be aware that everytime you get the flash content, it is deleted:

req.flash('msg', 'some msg');
console.log(req.flash('msg')); // prints 'some msg'
console.log(req.flash('msg')); // prints []

Also, I suggest you to check this very good gist from Brian MacArthur.