Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

511
Views
TypeError: Cannot read property 'app' of undefined when overwriting res.render

In my project I want to overwrite the res.render method to always add an option, no matter what other options there are. When I try to do it I get the error mentioned above. Here's my current middleware code:

app.use((_, res, next) => {
    const oldRender = res.render;

    res.render = (view, options, callback) => {
        if (typeof options === "function") {
            callback = options;
            options = {};
        }

        options.stops = stops?.data || {};

        oldRender.call(this, view, options, callback);
    };

    next();
});
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It looks to me like the point of this code is to always pass a particular value to your templates without requiring every caller of res.render() to add that to the data they pass to the template.

The general-purpose way to solve this type of problem is to put a property in res.locals. The template system looks there in addition to the data passed to res.render() and this is the easy way to pass data to all your templates:

app.use((_, res, next) => {
    res.locals.stops = stops?.data || {};
    next();
});

If there's some reason that won't work for you, then the apparent problem to the solution you're trying is that you're using arrow function so the value of this you're using in oldRender.call(this, view, options, callback); is the lexical value of this, not res which is what you need it to be. You can change this:

oldRender.call(this, view, options, callback);

to this:

return oldRender.call(res, view, options, callback);

You can directly pass res instead of trying to use this and you should also return the return value (which will be res) to duplicate the original behavior.


Doc link on res.locals.

A few other answers about res.locals:

Difference between assigning to res and res.locals in node.js (Express)

Is this bad practice for res.locals? (Node.js, express)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!