You can consider app.locals
to be global. Some examples of things you might want to store in app.locals
: URL helpers, application-level constants. You should put anything here that you want accessible in every single view.
res.locals
stores data only for a particular response (which responds to a particular request). For example, GET /something will create a new res.locals that gets passed through all the middleware responding to '/something.' Appropriate information here is stuff like authenticated user details from your question.
The lifecycle looks like this, where your responsibilities are bold (everything else is done for you by express):
- app is created (var app = express();)
- app.locals is created
- request arrives
- res.locals is created for that request
- you add things to res.locals like user roles (res.locals.role = 'admin';)
- you serve a response to the request (res.render('some/view');)
- res.locals for that request is garbage collected, gone
- app.locals continues to exist as long as the app exists
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…