In Express, how do res.locals and app.locals differ, and which one should middleware use to pass the signed-in user downstream?
answer
- two objects, two lifetimes
- one request versus the whole process
- both feed res.render
- shared across concurrent users
basics
~20 sres.locals is a fresh object for each request and is discarded when that request ends; app.locals lives as long as the application and every request shares it. Per-request data such as the signed-in user goes on res.locals, app-wide constants and helpers on app.locals.
solid answer
~40 sExpress creates `res.locals` as an empty object at the start of every request, so whatever middleware puts there is visible to later middleware, handlers and templates for that request only. `app.locals` is created once with the app; the reference says its properties persist throughout the life of the application, and middleware reads it as `req.app.locals`. Both reach templates: `res.render` merges `app.locals`, then `res.locals`, then the options passed to it, so a later source wins on a clash. The signed-in user belongs on `res.locals` (or on `req`, as authentication libraries commonly do): writing it to `app.locals` makes every concurrent request read whichever user was written last. The docs also warn not to put user-controlled input into locals keys, because view engines read them.
code
javascript · 16 linesconst express = require('express');
const app = express();
app.locals.appName = 'Billing'; // set once, shared for the app's lifetime
app.use((req, res, next) => {
// Bug: app.locals.user = req.get('x-user') would be shared by every request.
res.locals.user = req.get('x-user'); // this request only
next();
});
app.get('/whoami', (req, res) => {
res.json({ app: req.app.locals.appName, user: res.locals.user });
});
app.listen(3000);go deeper
Recall the lifetimes: res.locals is per request, app.locals is per application, and middleware reaches app.locals through req.app.locals.
Explain how Express creates each object and the render merge order of app.locals, res.locals and the render options.
Recognise the interleaving bug where per-user data on app.locals leaks between concurrent requests, and the locals-key warning around view engines.
Decide a team convention for request-scoped data, res.locals or typed properties on req, so middleware and handlers agree on one place and its type.
## Two objects, two lifetimes Express gives you two places to stash values for later code, and the difference is entirely about **lifetime and sharing**: | | `res.locals` | `app.locals` | |---|---|---| | Created | At the start of each request | Once, when the app is created | | Lives until | That request's response ends | The process stops | | Shared by | Code handling this one request | Every request the app serves | | Read from middleware as | `res.locals` | `req.app.locals` (or `app.locals` where the app is in scope) | | Typical contents | Signed-in user, request id, per-request flags | App name, support email, formatting helpers | | Reaches `res.render` | Yes | Yes | The API reference says the same thing in two sentences: `app.locals` properties "persist throughout the life of the application", while `res.locals` properties "are valid only for the lifetime of the request". ## How Express creates them The source makes both lifetimes concrete: - When an app is constructed, Express sets `app.locals` to an empty object created with `Object.create(null)` and stores a reference to the app's settings on it as `app.locals.settings`. - At the start of every request, the app's handler gives the response a new `res.locals`, also created with `Object.create(null)`, unless one already exists. A mounted sub-app therefore shares the `res.locals` of the request that reached it, while keeping its own `app.locals`. Because both are **null-prototype** objects, they have no inherited `hasOwnProperty` or `toString`. Call `Object.hasOwn(res.locals, 'user')` rather than `res.locals.hasOwnProperty('user')`. ## How they meet in res.render When a handler calls `res.render(view, options)`, Express builds the template's variables from three sources, in this order: 1. `app.locals`, the app-wide values; 2. `res.locals`, this request's values, which override app-wide ones with the same key; 3. the `options` object passed to `res.render`, which overrides both. So with `app.locals.title = 'A'`, `res.locals.title = 'C'` and `res.render('page', { title: 'B' })`, the template sees `B`. This order is why the common pattern works: put defaults on `app.locals`, per-user values on `res.locals`, and page-specific values in the render call. ## The shared-state bug The classic mistake is a middleware like this: ```js app.use((req, res, next) => { app.locals.user = req.user; // wrong: shared by every request next(); }); ``` Node runs JavaScript on one thread, but requests **interleave**: while request A awaits a database call, request B runs this middleware and overwrites `app.locals.user`. When A resumes and renders, it shows B's identity. Under light traffic it looks fine; under load it leaks one user's data into another user's page. Moving the assignment to `res.locals.user` fixes it, because each request has its own `res.locals`. ## Choosing where per-request data goes - **`res.locals`** is the documented per-request bag, and it flows into templates automatically. It suits anything a view needs: the user, a CSRF token, a request id for the footer. - **A property on `req`**, such as the `req.user` that authentication middleware usually sets, is equally per request and is the common choice in JSON APIs that render nothing. In TypeScript, the Express guide shows declaring such a property with declaration merging on `Express.Request`. - **`app.locals`** is for values that are the same for every request: configuration-derived constants and template helpers. Treat it as read-only once the app is serving traffic. ## Sub-apps and locals Mounting a whole Express app inside another, with `app.use('/billing', billingApp)`, changes one half of the picture: - the sub-app has its **own** `app.locals`, created when it was constructed, so values set on the parent's `app.locals` are not visible as the sub-app's locals; - inside the sub-app, `req.app` refers to the sub-app, so `req.app.locals` reads the sub-app's locals there and the parent's again once the request leaves it; - `res.locals` is **shared**, because Express only creates it when the response does not already have one, so a user set by the parent's middleware is still visible inside the sub-app. That asymmetry is a reason to keep request-scoped data on `res.locals` or `req`: it travels with the request through every mount, while `app.locals` belongs to whichever app is handling it at that moment. ## The security note in the docs Both reference entries carry the same warning: the locals object is used by view engines to render, so its **keys** may be sensitive and should not contain user-controlled input, because that may affect the view engine's operation or open a path to cross-site scripting. Never spread a request object such as `req.query` or `req.body` into `res.locals`; copy the specific fields a template needs under keys you chose.
- In what order does `res.render` combine `app.locals`, `res.locals` and its own options?It spreads `app.locals` first, then `res.locals`, then the options object, so on a key clash the render options win over `res.locals`, which wins over `app.locals`. That lets an app set defaults once, a middleware override them per request, and one handler override both for a single page.
- Why do the Express docs warn against user-controlled keys in `res.locals`?Express passes the locals to the view engine as its rendering options, and some engines read option keys to configure themselves. The reference warns that such keys may affect the engine's operation or provide a path to cross-site scripting, so copy chosen fields into fixed keys rather than spreading `req.query` or `req.body` into locals.
res.locals is the ticket clipped to one table's order in a restaurant kitchen, and app.locals is the whiteboard every cook reads. Write one diner's allergy on the whiteboard and every plate leaving the kitchen is prepared as if it were theirs.
- app.locals is reset at the start of every request.
- Values on res.locals carry over to the same user's next request.
- Storing the current user on app.locals is safe because Node.js is single-threaded.
- res.locals is only usable when the app renders templates.
- In res.render, app.locals overrides res.locals when both set the same key.