javascriptnode.jsexpressejsconnect-flash

Why are messages not appearing when using connect-flash with res.locals in express.js and ejs templating?


here are some of the relevant code snippets. connect-flash is able to show messages on test1 and test2. the problem is that no messages is showing for test 3: user registration when all three tests are redirected to the same 'testing' page.

app.js

// Connect-Flash
app.use(flash());
app.use((req, res, next) => {
  res.locals.errorMessage = req.flash('errorMessage');
  res.locals.successMessage = req.flash('successMessage');
  next();
});

auth.js

// test 1 
router.get('/flashsucceed', function (req, res) {
  req.flash('successMessage', 'Flash success message!');
  res.redirect('/auth/testing');
});

// test 2
router.get('/flashfailed', function (req, res) {
  req.flash('errorMessage', 'Flash error message!');
  res.redirect('/auth/testing');
});

// ejs file (showing the flash messages)
router.get('/testing', function (req, res) {
  res.render('testing');
});

// test 3:  User Registration
router.post('/register', async (req, res) => {
  try {
      const newUser = await User.register(new User({
        userFullName: req.body.userFullName,
        username: req.body.username,
      }), req.body.password );

      req.flash('successMessage', 'Flash success message!');

      passport.authenticate('local')(req, res, () => {
        res.redirect('/auth/testing');
      });
  } catch (err) {
      res.send(err);
  }
});

testing.ejs

<%- include('partials/header.ejs') %>

<div class="container">
  <br>

  <%= successMessage %>
  <%= errorMessage %>

  <h3>Testing</h3>
</div>

<%- include('partials/footer.ejs') %>

any pointers? I would also welcome an alternative to connect-flash, if there is one.

connect-flash should show successMessage / errorMessage on the same testing.ejs file.


Solution

  • I moved the req.flash code from outside passport.authenticate to inside passport.authenticate

    // test 3:  User Registration
          ................
          passport.authenticate('local')(req, res, () => {
            req.flash('successMessage', 'Flash success message!');
            res.redirect('/auth/testing');
          });
      } catch (err) {
          res.send(err);
      }
    });
    

    and the problem is solved.

    maybe someone can enlighten me on why this works. thanks.