Search code examples
javascriptnode.jsconnect-flash

How to call flash on the client-side?


CODE:

login.ejs

<script>
    req.flash('success_msg', 'You have logged in');
</script>

header.ejs

<div class = "alertMessage">

    <% if (success_msg != false){ %>
        <span class="alert alert-success containerMargins">
            <%= success_msg %>
        </span>
    <% } %>
    <% if (error_msg != false){ %>
        <span class="alert alert-danger containerMargins">
            <%= error_msg %>
         </span>
    <% } %>

    </div>

SITUATION:

This has nothing to do with using flash on the server-side and displaying the message on the client-side: it already works perfectly for me.

This has to do with calling flash from the client or replicating the same behaviour from the client with some other library.


QUESTION:

The code I showed of course does not work on the client-side, what can I do to replicate that behaviour on the client-side ?


Solution

  • The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.

    So you need code which:

    1. Stores some data somewhere that the client can access between pages
    2. Reads that data
    3. Deletes it after being read

    Start by picking somewhere for option 1 (such as localStorage, or a cookie). The rest should be trivial - the original module is about 80 lines of code, including about 50% comments — to implement (but specific to which choice you make).