What's the best way to handle Node.js flash messages?

1k views Asked by At

I am a beginner with Node.js and i absolutely love it. I wonder how can i handle flash message the best and easiest way.

I used connect-flash package in my site. Does it have better ones?

I always put my flash messages in my render function like this:

res.render('auth/login', {
        title: 'Log in',
        success: req.flash('success'),
        error: req.flash('error')
    });

Does it have a way to handle the gloabally? like in the res.locals.messages variable or something like this?

I use JADE html templating, so i print them like #{success}. How can i access a global variable this way to print my flash messages?

Thank you very much for your help and advices!

1

There are 1 answers

0
Evan Hahn On BEST ANSWER

If you want to set the success and error variables in every request, you can use res.locals like you mentioned. You can accomplish this with middleware that you'll include after connect-flash:

// ...

app.use(function(req, res, next) {
  res.locals.success = req.flash('success');
  res.locals.error = req.flash('error');
  next();
});

// ...

Now, success and error will always be in every call to res.render.