Express res.locals Property
What you’ll learn
- How to store request-scoped values in
res.locals. - How middleware and routes can share data through locals.
- How
res.localsdiffers fromapp.locals. - How to keep template context clean and safe.
Basic usage
javascript
res.locals.user = { name: 'Mari' };
res.render('profile');1
Set locals in auth middleware
javascript
app.use(function (req, res, next) {
res.locals.isLoggedIn = Boolean(req.user);
res.locals.currentUser = req.user || null;
next();
});2
Use locals when rendering a view
javascript
app.get('/dashboard', function (req, res) {
res.locals.pageTitle = 'Dashboard';
res.locals.notifications = 3;
res.render('dashboard');
});3
Compare app.locals and res.locals
javascript
app.locals.siteName = 'CodeToFun';
app.get('/about', function (req, res) {
res.locals.pageTitle = 'About';
res.json({
site: app.locals.siteName,
page: res.locals.pageTitle
});
});⚠️ Common pitfalls
- Do not treat
res.localsas persistent storage; it lasts only for one request. - Avoid storing large objects unnecessarily in locals.
- Sanitize user-provided values before exposing them to templates.
❓ FAQ
It is an object used to store data scoped to the current request-response cycle.
It is often used to pass values from middleware into rendered templates.
No, each request gets its own res.locals object.
res.locals is per-request, while app.locals is shared globally across the app.
Yes, short-lived request data like user context is a common and safe use case.
Did you know?
res.locals is request-scoped and ideal for passing data from middleware to views without polluting global app state.
4 people found this page helpful
