How to create an Express middleware that runs just before res.render (model rendering)?

advertisements

I'd like to hook into the part right before Express templates are rendered (when res.render is called), so that I can do things like assign appropriate things from res. to res.locals., making it available to the templates. For example, doing res.locals.user = res.user.

The standard middleware isn't good enough for this because it runs before everything, so in this case user wouldn't be available yet. Right now I have to do this in every route function separately.

res.locals.user = res.user;
res.render('template.html', context);

Also hooking in at this point would be useful for things like i18n, etc.


The standard middleware isn't good enough for this because it runs before everything

That is not correct, you can define where in the chain you put your middlewares, i.e (using passport):

//passport setup
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
    ...
});

passport.deserializeUser(function(usr, done) {
    ...
});

// set locals
app.use(function(req, res, next) {
    // req.user is available
    res.locals.user = req.user;
    next();
});

In this case passport.session() middleware will alter the req object to provide the user deserialised by passport.deserializeUser fn, making req.user available anywhere further in the chain.