Express4. What's the difference between app.locals, res.locals and req.app.locals?

  • The app.locals object is a JavaScript object, and its properties are local variables within the application.

    app.locals.title
    // => 'My App' 
    app.locals.email
    // => '[email protected]'
    

    Once set, the value of app.locals properties persist throughout the life of the application

  • In contrast with res.locals properties that are valid only for the lifetime of the request. When you handle the route where you have a res object, you won't have an app object there and vice-versa for app.locals.

  • You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as app-level data. Locals are available in middleware via req.app.locals (see req.app)

    app.locals.title = 'My App';
    app.locals.strftime = require('strftime');
    app.locals.email = '[email protected]';
    

One picture from Node.js In Action book as below, describe the difference of app.local and res.local

enter image description here


From express documentation.

Here in short.

app.locals

The app.locals object is a JavaScript object, and its properties are local variables within the application.

This means you can declare a variable in your app.js with locals and access it within that script or pass it to the response object.

res.locals

With this you can set or send variables to client side html/view and it is only available in that view/html.

e.g.

app.get('/view', function(req, res) {
  res.locals.user = req.user;
});

Here the user variable is available in your html page requesting the view route.

req.app.locals

Locals are available in middleware via req.app.locals;