Search code examples
node.jsajaxexpressfetch-apiflash-message

Flash error or success message to user after fetch/ajax request


I have an app that currently uses the fetch api to make AJAX requests for CRUD operations. In case of success or error, my server sends a response containing an array of error/success messages like: ['Missing email field', 'Password is too short']

If I wasn't using AJAX and instead reloading/rerendering the page, there are modules like connect-flash and express-session that allow you to flash error/success message to the user.

How can I achieve the same when doing AJAX requests with the fetch API? One method I thought of was creating a div on my view and then adding the error/success as li elements on that view via JS. However, I was wondering if there was a module that does all this for you like there is for when re-rendering the pages.

Further, if I use the approach described above of modifying the DOM with the messages, those messages persist on the view. I only want to show the messages for limited amount of time to the user.

Thanks for the help!

EDIT: I am only using express-handlebars and bootstrap modules so not using any big frameworks like Vue/React/Angular.


Solution

  • Since you are using Bootstrap, I'd recommend looking at their Alerts component, it supports the ability to dismiss via the UI or programmatically