Step 13

There is a potential issue with the way I have used cookies for passing messages between different views. Let's observe the issue first: open the homepage and enter an invalid user credentials.

You will get the "Incorrect username and password" message. Now click on the "registration" link.

Notice there is again the "Incorrect username and password" message. This is due to the simple fact that the cookie with the error message still exist. So potentially, we will see this message in every view until the cookie is deleted or overwritten.

We must update the program so the (flash) message is only available once, for the next request.

That is if we store a (flash) message in a cookie and render a page, the message is read and displayed but if we render the same (or another) page, the message is not present (it is destroyed).

There are a number of strategies to achieve this desired outcome. I will use this opportunity to show you how we can write our own Express middleware. The middleware we write will destroy the flash message after it is read.