4

In my Express application, I'm able to set app.locals and use them directly in my templates (rendered using express-handlebars). However, when I set res.locals in middleware, they are not available unless I pass them in. Am I doing something wrong?

Server

app.locals.foo = "foo";
app.use(function(req, res, next) {
  res.locals.bar = "bar";
  next();
});

Template

{{foo}} {{bar}}

Test 1

app.get("/", function(req, res) {
  app.render("template.html", {}, function(error, html) {
    res.send(html);
  });
});

Result

foo

Test 2

app.get("/", function(req, res) {
  app.render("template.html", {bar: res.locals.bar}, function(error, html) {
    res.send(html);
  });
});

Result

foo bar
David Jones
  • 10,117
  • 28
  • 91
  • 139

2 Answers2

8

res.locals is available in res.render. I suspect you are calling app.render by mistake, and should be calling res.render.

bolav
  • 6,938
  • 2
  • 18
  • 42
0

The app.locals are available in the entire application as long as the application is up. The res.locals only exists during the request.

tomtom
  • 642
  • 7
  • 12