What does res.locals.path = req.path; in node.js?


I try to figure out what this code does:

const app = express();
app.use((req, res, next) => {
  res.locals.path = req.path;


res.locals is typically used to surface variables from middleware to a template engine being used to render the page with res.render() in a subsequent request handler (later in the request handler chain). You can read the doc here.

So, this particular middleware is making req.path available to the template engine (by putting that value into res.locals.path so that it can be used in rendering the page as just path (not sure what the template wants to do with the path – that’s up to it).

Note that the actual route that is calling res.render() can pass data directly to the template engine as an argument to res.render(), but this can’t be done by middleware because the middleware itself isn’t calling res.render(), so its alternative is to put the data into res.locals where the template engine can pick it up from there.

res.locals starts out each request as empty so it contains nothing until your middleware or request handlers puts something in it for purposes of rendering a page for that specific request.

Answered By – jfriend00

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.