Q23: What is `res.locals` and how is it used?
res.locals is an object scoped exclusively to the lifetime of the current request-response cycle. It is used to pass request-scoped variables across middleware functions and template view engines.
Sharing Data via res.locals
app.use((req, res, next) => {
res.locals.user = req.user;
res.locals.appName = 'My Enterprise App';
next();
});
app.get('/dashboard', (req, res) => {
// Accessible inside template rendering or downstream handlers
res.render('dashboard', { title: 'User Dashboard' });
});💡 res.locals variables are automatically available to view engines like EJS or Pug.
Key Takeaways
- Variables attached to
res.localspersist throughout the request pipeline, but clear automatically when the request finishes. - Ideal for sharing data with view templates or downstream response formatters.