res.locals in express

  1. res.locals is an object in Express.js that provides a way to pass data from middleware to the view engine.

  2. It is accessible throughout the entire lifecycle of the request-response cycle.

  3. To use res.locals, you can set properties on it within middleware functions.

  4. The data set on res.locals is then available in the rendering engine when rendering views.

  5. For example, in a middleware function, you can do: javascript app.use(function(req, res, next) { res.locals.currentUser = req.user; next(); });

  6. Here, currentUser is set on res.locals using the value of req.user.

  7. 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 }); });

  8. In the example above, the profile view can now access the currentUser data.

  9. This mechanism allows for the sharing of data between different parts of the application, making it available for rendering views.

  10. It is commonly used for providing user authentication information, session data, or other global variables to views in Express.js applications.