Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

519
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda