0

I have multiple middlewares on my Express server. I want to set the same custom headers to all res.renders. However, I don't want them to be sent with the res.sends.

I found this answer. However, doing this will set headers to all responses sent by the server including both res.renders and res.sends.

Is there a way to affect all res.renders without affecting res.sends ?

Thank you!

Emilio
  • 1,314
  • 2
  • 15
  • 39
  • The only way I see this working is if you specify a middleware like in the answer above, but you conditionally check whether or not to set stuff. What is your use case? – Cisco Jan 25 '18 at 17:18
  • @FranciscoMateo yeah, the conditionally part is the part I'm trying to avoid; I currently have about 40 `res.render`s and 40 `res.send`s . I was trying to avoid the risk of maybe making a mistake when going trough them one by one. :/ – Emilio Jan 25 '18 at 17:27

2 Answers2

2

Another way will be overriding the res.render method in a top middleware and when called you set your desired headers and call the original render method like this:

// top middleware
app.use(function overrideRender(req, res, next) {
    const originalRender = res.render;

    res.render = function customRender() {
        // set your headers here

        originalRender.apply(res, arguments);
    };

    next();
});
milsosa
  • 109
  • 7
  • Sorry, but what is this part `originalRender.apply(res, arguments);` doing? `originalRender` is `res.render`, so what is `res.render.apply` ? Thanks – Emilio Jan 25 '18 at 18:15
  • 1
    `originalRender.apply(res, arguments);` is doing the following: - The `res` argument is being passed to as the `this` context to not break the original implementation. - The `arguments` argument is just to pass-through all the provided arguments when `res.render(arg1, arg2, argn)` was called. Take a look at the official documentation for apply here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply – milsosa Jan 25 '18 at 18:20
  • I think your last comment is missing some text – Emilio Jan 25 '18 at 18:23
1

The app.use() method can accept an array of end points as argument, You could group all routes (that contain res.render method) inside an array and call a specified middleware when the users reach one of them:

var routes = [
    '/route/1/',
    '/route/2/',
    '/route/3/',
];

app.use( routes, function (req, res, next) {

    res.setHeader('header' , 'value' );

    next();

});
YouneL
  • 8,152
  • 2
  • 28
  • 50