QA
Beginner LevelExpress JS

What is the difference between app.locals and res.locals for sharing data?

❓ Interview Prompt: Compare application-scoped app.locals vs request-scoped res.locals for sharing variables with templates and middleware.

Express provides two local variable storage objects for sharing data with template engines and downstream middleware:

1. 'app.locals':

•
Application-Scoped: Variables persist across the entire lifespan of the application and all requests. Ideal for site titles, app version numbers, or static global configs.

2. 'res.locals':

•
Request-Scoped: Variables persist ONLY during the current request-response cycle. A fresh object is created for every new HTTP request, ideal for storing the authenticated user ('res.locals.user').

Code Implementation Example

javascript
import express from 'express';
const app = express();

// 1. app.locals (Global application lifecycle variables)
app.locals.siteName = 'Enterprise Portal';
app.locals.apiVersion = 'v2.0';

// 2. res.locals (Request-scoped variables set in middleware)
app.use((req, res, next) => {
  res.locals.requestStartTime = Date.now();
  res.locals.currentUser = { name: 'Alice' }; // Available to views rendered in this request!
  next();
});
💡Global app.locals vs request-scoped res.locals variable assignment.
🎯 Interview Key Takeaway

Use app.locals for static application-wide variables; use res.locals for request-scoped user/template variables.

#app.locals#res.locals#Middleware#Beginner
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?