Should you use Req.app.locals to store flash messages?

86 Views Asked by At

Is it safe to use req.app.locals to store req.flash messages? (using connect-flash)

With some research and some testing, I understand that req.app.locals is a global variable and not user specific, while req.flash is stored in the session so it is user specific (please correct me if I'm wrong). For that reason, it doesn't seem right to store the flash messages in req.app.locals to use in templates but that's how I have seen it done.

Here is a relevant code snippet to display what I am referring to.

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

Is there anything wrong with this? Is there a better way this should be done? I'm thinking res.locals instead but then that becomes a little less convenient to use in the ejs view templates.

Thanks in advance!

1

There are 1 best solutions below

0
Pefington On
app.use(flash({ locals: 'flashMessageVariable' }));

Works for me.