node.jsexpressconnect-flash

flash messages are not saved before the page is rendered (node)


As part of a generic get route in an express application, I want to send two flash messages with express-session and connect-flash. This all works except that req.flash does not save before the page is rendered. As a result, the flash messages do not show until the user loads another page or the same page again.

The code for the last function in the route:

    Post.countDocuments().exec(function(err, count){
        if(err) {
            console.log(err);
            res.redirect("back");
        }

        req.flash("success", ["It's working", "Hallelujah!"]);
        req.flash("error", ["Uh oh!", "We have a problem..."]);

        res.render("index", {posts: allPosts, dates: dates, current: pageNumber, pages: Math.ceil(count / pageLimit), showing: showing, total: count});
    });

and here's the code for one of the flash message templates (ejs):

    <div class="flash flash-success">
        <div class="flash-header">
            <span class="flash-title flash-title-success"><i class="fas fa-check"></i> <%= success[0] %></span>
            <span class="flash-close" onclick="return closeFlash(this);"><i class="fas fa-times"></i></span>
        </div>

        <hr class="flash-hr">
        <div class="flash-body-success"><%= success[1] %></div>
    </div>

I have tried using .exec() after req.flash to make the render statement run on completion but this didn't work and I've also tried req.session.save() with the render statement in a callback but this also failed.

The issue is not resolved by getting rid of one of the req.flash statements nor by only passing one string argument instead of an array of two.


Solution

  • The problem was that I had

    app.use(function(req, res, next) {
        res.locals.currentUser = req.user;
        res.locals.error = req.flash("error);
        res.locals.success = req.flash("success");
        return next();
    });
    

    in app.js and so this middleware was run before the route had chance to set values for req.flash meaning that error and success were set to be empty.

    I solved this by creating a function to save req.flash in res.locals just before rendering the page:

    var toolsObj = {};
    
    toolsObj.saveFlash = function(req, res) {
        res.locals.error = req.flash("error");
        res.locals.success = req.flash("success");
    };
    
    module.exports = toolsObj;