req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware
As you mentioned, both req.locals
, res.locals
or even your own defined key res.userData
can be used. However, when using a view engine with Express, you can set intermediate data on res.locals
in your middleware, and that data will be available in your view (see this post). It is common practice to set intermediate data inside of middleware on req.locals
to avoid overwriting view data in res.locals
, though this is not officially documented.
res.locals An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to
app.locals
.This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
Source: http://expressjs.com/en/api.html#res.locals