Error: When attempting to overwrite res.render, a TypeError occurs because the property 'app' is being read from an undefined source

I am working on a project where I need to modify the behavior of the res.render method in order to consistently include an additional option, regardless of any other options present. However, when attempting to implement this modification, I encounter the error described above. Here is the current implementation of my 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();
});

Answer №1

It appears that the goal of this code is to consistently provide a specific value to templates without requiring each res.render() caller to include it in the data passed to the template.

A common solution to this issue is to utilize a property in res.locals. The template system will check there, along with the data provided to res.render(), making it an easy way to pass data to all templates:

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

If using this in an arrow function is causing problems for you, the issue may lie in the fact that the value of this in

oldRender.call(this, view, options, callback);
refers to the lexical value, not res as needed. A possible fix could be changing:

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

to:

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

By passing res directly instead of relying on this, and returning the result (which will be res), you can replicate the original behavior.


For more information on res.locals, check out the documentation link.

Additional resources on res.locals:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

Preserving the most recent choice made in a dropdown menu

Just started with angular and facing an issue saving the select option tag - the language is saved successfully, but the select option always displays English by default even if I select Arabic. The page refreshes and goes back to English. Any assistance o ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...

Use router.get in order to pass both JSON data and an image from the Node.js back end to the React frontend

Having trouble sending both an image and JSON data to the front end from my node.js back end. I can successfully send them separately using router.get, but struggling to send them together in a single request. To send just the image, I used the code below ...

I prefer to disable the toggle feature if the target remains unchanged

My goal is to create a step-by-step ordering system using the data-id="x" attribute to determine which content should be visible when selected. I want to make sure that if two elements have the same data-id, clicking on one will deselect the other. Any su ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

Ways to disable the ability to close a bootstrap modal by pressing the backspace key

How can I enable the backspace button in a Bootstrap Modal form for textboxes and textareas? $('body').keydown(function (e) { if ($('#myModal').is(':visible')) { if (e.keyCode == 8) { retu ...

Navigating through various route chains in Express

I recently came across a useful feature in Express that allows you to jump to a new chain of middleware dynamically. Consider the following example: router.post('/', function(req,res,next){ next(); }, function(req,res,next){ next(&apos ...

Having trouble with the functionality of the jQuery `has()` method?

Consider the following HTML code snippet: <div class="comment"> <span class="test">some content here</span> <p>Lorem ipsum</p> </div> <div class="comment"> <p>Lorem ipsum</p> </div> The ob ...

Utilizing API calls to sort data by specific columns in Mongoose, NodeJS, and Express

Currently in the process of developing an API for a cooking application. I have created a model called Recipe and now want to incorporate sorting functionality based on the specified parameter in the request. I am looking to sort the data by any column pr ...

When attempting to use dynamic imports with `react-icons`, NextJS will import all necessary components and dependencies

My current task involves incorporating an Icon from the react-icons package into my project. However, when I attempt to do so using an import statement, the resulting bundle size looks like this: Route (pages) Size First Lo ...

Ways to specify the encoding for a text iframe embedded in a webpage

Can anyone help me with document embedding in HTML? In my current project, I am directly embedding my update logs as text files into the webpage, along with a selection menu to view all the updates. However, I ran into a minor issue where the Firefox cons ...

The Chrome Extension is unable to recognize a portion of the URL following the # symbol in the contentscript.js code

I am currently developing an extension for a specific website that I don't have ownership of. The URLs on this site only change after a /#/. For instance, starting from the URL .../#/PF/charts/patients/419d3081-5e20-4347-a852-52b2c333ce85/summary W ...

Ways to retrieve and contrast the border style of an image utilizing javascript

I'm currently attempting to identify images on my webpage that have the style border: 1px #c6c6c6 solid; let images = document.getElementsByTagName('img'); for (let i = 0; i < images.length; i++) { if (images[i].style.border === "1px ...

To search for specific data in a Mongoose schema by specifying an attribute of type ObjectId

Here are the schemas I am working with: UserLike const UserLikeSchema = Schema({ user: { type: Schema.Types.ObjectId, ref: "User", required: [true, "User is required"], }, game: { type: Schema.Types.ObjectId, ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

What is the best way to load a database URL asynchronously and establish a database connection prior to the initialization of an Express

My express.js app is set up to run on AWS lambda, with the database URL stored and encrypted in Amazon KMS. To access the URL, decryption using the AWS KMS service is required. // imports import mongoose from 'mongoose'; import serverless from & ...

Make sure to include the environment variable in the package.json file before running Cypress in headless mode

I am trying to determine whether Cypress is running or not within a NextJS application. My goal is to prevent certain http requests in the NextJS application when Cypress tests are running. Currently, I am able to detect if Cypress is running by using the ...

Step-by-step guide to uploading files using cucumber-js

Is there a way to write a script that can successfully fill out a form and upload a file using cucumber-js, selenium, and protractor? I am encountering an issue where there is no xpath/id available to click on when trying to upload a file. How have you d ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...