Search code examples
node.jsexpresshandlebars.js

how to render common variables from app.js to all routes in express


In my Node.js application some variables that render or every route are common.There are around 4-5 variables which render on every route. And I have around 20 routes.

Currently I am doing passing those variables in every route in res.render

Is there a method by which I can pass these common variables in some place '(eg:app.js)` which is being used by every route, so that I can clean up my code a bit.

I use express.js for node and handlebars for template.

EDIT:I think I should explain a bit more

res.render('abc', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

-------------------------------------
another route
res.render('xyz', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

I want to avoid this repeating in my every routes and want to render it from a common place.


Solution

  • For session or request dependent values you can store those common values in a global variable and then use them directly in res.render. To do that you have following options

    • Use app.use to store values :

    In your app.js add a middleware which does this for you. Remember to write this middleware before any other routes you define because middleware functions are executed sequentially.

    app.use(function(req, res, next){
        res.locals.items = "Value";
        next();
    });
    //your routes follow
    app.use(‘/’, home);
    

    In your routes you can place items directly in res.render like:

    res.render('layout', {title: 'My awesome title',view: 'home', item :res.locals.items });
    
    • Use express-session to store values :

    If you have express-session installed you can save some data in req.session.item and place them in any route like:

    res.render('layout', {title: 'My awesome title',view: 'home', item :req.session.items });