How do I use req.flash() with EJS?

user775171 picture user775171 · Jun 25, 2012 · Viewed 21.4k times · Source

I want to be able to flash a message to the client with Express and EJS. I've looked all over and I still can't find an example or tutorial. Could someone tell me the easiest way to flash a message?

Thanks!

Answer

Poison Oak picture Poison Oak · Jan 28, 2015

I know this is an old question, but I recently ran across it when trying to understand flash messages and templates myself, so I hope this helps others in my situation. Considering the case of Express 4, the express-flash module, and an ejs template, here are 2 routes and a template that should get you started.

First generate the flash message you want to display. Here the app.all() method maps to /express-flash. Request baseurl/express-flash to create a message using the req.flash(type, message) setter method before being redirected to baseurl/.

app.all('/express-flash', req, res ) {
  req.flash('success', 'This is a flash message using the express-flash module.');
  res.redirect(301, '/');
}

Next map the message to the template in the res.render() method of the target route, baseurl/. Here the req.flash(type) getter method returns the message or messages matching the type, success, which are mapped to the template variable, expressFlash.

app.get('/', req, res ) {
  res.render('index', {expressFlash: req.flash('success') });
}

Finally, display the value of expressFlash, if it exists, in index.ejs.

<p> Express-Flash Demo </p>    
<% if ( expressFlash.length > 0 ) { %>
  <p>Message: <%= expressFlash %> </p>
<% } %>

Then start the server and visit baseurl/express-flash. It should trigger a redirect to baseurl/ with the flash message. Now refresh baseurl/ and see the message disappear.