Avoid req.flash delete data on middleware

456 Views Asked by At

I'm using connect-flash with express to handle flash messages, but that messages are deleted when i read that properties, for example:

Defining flash message:

req.flash("myMessage", "Hey!");

Reading message:

console.log(req.flash("myMessage")); // Hey!
console.log(req.flash("myMessage")); // undefined

Data is erased on first read, and this is a problem, because i need to read the data of req.flash in a middleware to filter the http request and after in the controller (Which is in another file) i need to read the same req.flash data but i can't because in the read of the middleware was erased.

What can i do in this case?

3

There are 3 best solutions below

0
rdrey On BEST ANSWER

The messages are stored on req.session.flash internally, see the source code.

This means you can get the message by indexing directly into req.session.flash["myMessage"] without it getting cleared.

This is technically an implementation detail of req.flash() you shouldn't rely on, but I think if you pin the version of connect-flash in your requirements it's safe enough.

0
Arman Ortega On

Calling the req.flash again obviously the first call actually delete the flash data. So that's why when you call again the req.flash the data is now undefined or empty array.

1st console.log output: [ 'Hey!' ]
2nd console.log output: []

Does it make sense?

0
Rodrigo P. Dias On

Store the message in the request object like:

req.myMessage = req.flash("myMessage");

And that will be available in all middlewares you want for that specific request.

Btw, make sure you are using connect-flash because you are redirecting the user to another route and that starts a new request and you want to save data between requests (and that's why you want to use a session for that). That being said, removing the message from the session is encouraged instead of just trying to access it.

If you are not redirecting the user, rethink if connect-flash is necessary.