View authentication context
Add authenticated-user details and authorization flags in middleware before rendering a page.
Express.js · Pipe
res.locals stores values that templates rendered with res.render can use. Its values exist only for the current request-response cycle, making it suitable for request-specific data.
res.locals is a response-scoped object for values that templates can read when res.render creates a view. Middleware can populate it during a request, and its contents disappear after that request-response cycle; use app.locals for values shared across requests.
res.localsObject used for response-local template variables.
const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.use((req, res, next) => {
res.locals.requestPath = req.path;
next();
});
app.get('/', (req, res) => res.render('index'));
app.listen(3000);Middleware adds request-specific data to res.locals, making requestPath available when the route renders the index view.
Add authenticated-user details and authorization flags in middleware before rendering a page.
Expose the current path or other request metadata to a template.
Pass computed, per-request settings from middleware to a view.
res.locals is an object attached to the response. Values placed on it become available to templates rendered with res.render during the current request.
Follow-up: How would you expose authenticated-user information to every view? Add it in application middleware before the routes that render those views, such as res.locals.user = req.user.
Its values are limited to one request-response cycle and are not shared with another request. This makes it appropriate for request-level data such as a path, user, or settings.
Follow-up: Where would you put a site-wide application name? Use app.locals rather than res.locals because the documentation directs persistent template locals to app.locals.
A middleware function can assign properties to res.locals and call next(), after which a later route can call res.render and the view can consume those properties. The documented pattern assigns user and authentication values before rendering.
Follow-up: What security review is needed for dynamically chosen local names? Reject or constrain user-controlled keys, because view-engine handling of sensitive keys can create security issues.
res.renderapp.localsapp.usereq.user