Reputation: 34929
I'm really confused by app.locals
and res.locals
because I don't know WHEN should I use them and how? And actually I want to know the app.locals
and res.locals
life cycle.
For example where should I save my user (authenticated user) details (username, roles etc.)? In app.locals
or res.locals
?
Upvotes: 25
Views: 9659
Reputation: 13799
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):
Upvotes: 70