Search code examples
node.jsexpresseveryauth

flash is undefined with Express 3, connect-flash, and everyauth


After upgrading to Express 3 I went through the "joys" of implementing connect-flash and have it working.

I implement like this:

var flash = require('connect-flash');

app.use(flash());

app.use( function (req, res, next) {
    res.locals.everyauth.user = req.user;
    res.locals.user = req.user;
    res.locals.flash = req.flash();
    next();
});

I display the flash alerts in my jade layout template (used by all pages, and have a similar line for flash.info, flash.warning, etc) like this:

- if ('undefined' !== typeof flash.error && flash.error.length)
    - each msg in flash.error
        div.error= msg

All is well EXCEPT when I render my /login and /register pages via express, when I get a "flash is not defined" error. Any ideas?


Solution

  • Well, it's not pretty, but I've found a workaround for this. Basically, I've added the first if statement to the block in my express template that handles the flash messages:

    - if (flash !== null)
        - if ('undefined' !== typeof flash.error && flash.error.length)
            - each msg in flash.error
                div.error= msg
    
        - if ('undefined' !== typeof flash.warning && flash.warning.length)
            - each msg in flash.warning
                div.warning= msg
    
        - if ('undefined' !== typeof flash.info && flash.info.length)
            - each msg in flash.info
                div.info= msg
    
        - if ('undefined' !== typeof flash.success && flash.success.length)
            - each msg in flash.success
                div.success= msg
    

    Then, I added a local variable in everyauth's page rendering statement that sets flash to null, like this (you'll need one for the register and login pages):

    .registerView('register.jade')
        .registerLocals({
            title: 'Hi there, I am a register page',
            flash: null
        })
    

    Like I said, it ain't pretty, but it seems to be working.