In this example I would expect that appTitle will be available to me, because this is what is says in docs.
The app.locals object has properties that are local variables within the application.
The same way I don't have to set the 'view engine', it just uses the one from the parent. But it's not the case, appTitle becomes undefined.
var express = require('express');
var app = module.exports = express();
app.set('view engine', 'pug');
app.locals.appTitle = 'yay';
var subapp = express();
subapp.get('/', function (req, res) {
res.render('index', {myVar: 'global var'});
});
app.use(subapp);
var port = 5000;
app.listen(port, () => console.log('running on ' + port));
The locals are not inherited by sub apps, though some settings are. This was a miss when Express 4.0 was released, I know, as the view settings should also have never inherited to the sub apps. The way it is supposed to work is that rendering is specific to an app and does not inherit, but we bugged the initial 4.0 release to inherit the view setting, which we will get fixed in 5.0. If you want to operate within the same app domain, you should use sub routers in your example.
My workaround for this is just to use res.locals instead:
app.use((req, res, next) => {
res.locals.appTitle = 'yay'
next()
})
But isn't it better for performance and readability of code to assign a "very static" variable without a middleware function?
Possibly @antpaw, but it's the only way around it unless you do as doug suggested above and move to sub-routers (which'll be fine for the above but you may have issues if you're using different rendering logic or the like within your sub-apps).
Personally I've never found it to be an issue with either though, particularly when it comes to performance; but all my apps do database work which completely blows away any minuscule performance drop from having one more catch-all route.