Denny
Denny

Reputation: 1759

Express, Handlebars show flash messages

I'm using Node with express and handlebars. I have a login form, and should display a login error message to a user. My code is as follows: Validation (using passport):

...
else if (password != user.password) {
            return done(null, false, req.flash('message', 'Wrong password'));
...

In routes I got this:

app.post('/sign-in', passport.authenticate('local', {
        successRedirect : '/', // redirect to the home page
        failureRedirect : '/sign-in', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

Then to render my handlebars template,

app.get('/sign-in', function(req, res) {
        res.render("signin.handlebars", {layout: 'users.handlebars', action: 'Sign in', message: req.flash('message'),
                    csrf: 'CSRF token goes here' });
    })

Problem is, the flash message ain't shown as required when a wrong password is entered.

Edit: My express setup is:

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('models', __dirname + '/models');
app.use(express.static(__dirname + '/public'));     // set the static files location /public/img will be /img for users
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere', resave: true, 
                        saveUninitialized: true, }));
app.use(passport.initialize());
app.use(passport.session());
//app.use(session({ store: new RedisStore }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(flash());
app.use(morgan("dev"));
app.disable('x-powered-by');
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
});

Upvotes: 5

Views: 14070

Answers (2)

degs
degs

Reputation: 35

You need to add a global variable in your index.js

app.use((req, res, next)=>{
  app.locals.success = req.flash('success')
  next();
});

Then in your route you add the message

req.flash("success", "Your message");

Finally you .hbs

{{#if success}}
{{success}}
{{/if}}

Upvotes: 2

Denny
Denny

Reputation: 1759

I solved it btw like so: ...

if (!user) {
            return done(null, false, {
                message: 'The email you entered is incorrect'
            });

... That encodes the message in JSON. Then in routes I got:

app.get('/sign-in', function(req, res) {
        res.render("signin.handlebars", {layout: 'users.handlebars', action: 'Sign in', ***error: req.flash('error')***,
                    csrf: 'CSRF token goes here' });
    })

Then in my handlebars template:

{{#if error}}
    <div class="alert alert-danger">{{error}}</div>
{{/if}}

Upvotes: 8

Related Questions