res.locals in express
res.locals
is an object in Express.js that provides a way to pass data from middleware to the view engine.It is accessible throughout the entire lifecycle of the request-response cycle.
To use
res.locals
, you can set properties on it within middleware functions.The data set on
res.locals
is then available in the rendering engine when rendering views.For example, in a middleware function, you can do:
javascript app.use(function(req, res, next) { res.locals.currentUser = req.user; next(); });
Here,
currentUser
is set onres.locals
using the value ofreq.user
.Later, in a route handler or another middleware, you can access and use
currentUser
in the view engine:javascript app.get('/profile', function(req, res) { res.render('profile', { user: res.locals.currentUser }); });
In the example above, the
profile
view can now access thecurrentUser
data.This mechanism allows for the sharing of data between different parts of the application, making it available for rendering views.
It is commonly used for providing user authentication information, session data, or other global variables to views in Express.js applications.