devnotes.

res.locals Property

res.locals is an object for storing variables scoped to the current request/response cycle — commonly used to pass data to views rendered during that request.

Syntax

res.locals

Example

const express = require("express");
const app = express();
const PORT = 4800;

app.use((req, res, next) => {
    res.locals.requestTime = new Date().toISOString();
    next();
});

app.get("/", (req, res) => {
    console.log(res.locals);
    res.send(`Request received at ${res.locals.requestTime}`);
});

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

Use cases

  • Passing per-request data from middleware to route handlers.
  • Sharing values with templates during server-side rendering.
  • Storing request-scoped data that should not leak between requests.
res.locals Property | DevNotes