Express res.locals Property

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 3 Code Examples

What you’ll learn

  • How to store request-scoped values in res.locals.
  • How middleware and routes can share data through locals.
  • How res.locals differs from app.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.locals as 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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

4 people found this page helpful