Miguel Mesquita Alfaiate
Miguel Mesquita Alfaiate

Reputation: 2968

Add header to all responses after processing but before sending to client

I have two endpoints in a node js app:

app.get('search', myGetController);
app.post('add', myPostController);

For simplicity, let's assume both services have only the following code:

exports.myGetController = function(req, res) {
    res.status(404).json({ error: "not found" });
};

I want to have a middleware that is executed after the processing of the controllers, but before they are sent to the browser, so I can add a header based on the body of the response.

// process all responses to add ed25519
app.use(function(req, res, next) {
    res.setHeader('CharCount', [How To get Body content]);
    next();
});

I have two questions:

First of all, I would like to have all my controllers pass by that middleware after processing.

Second, I would like to access the body content so I can generate a header based on its content.

UPDATE

I have tried the suggested answer someone posted, and it is not working, or I am missing something.

This is what I have (before setting up my routes):

app.use(function(req, res, next) {
    const oldResJson = res.json;

    res.json = function(body) {
        res.setHeader('myToken', generateHeaderBasedOnBody(oldResJson));
        oldResJson.call(res, body);
    }

    next();
});

The response that is being passed to my method is an empty string, even though the response sent by the service is not empty. Am I doing this in the wrong place, or what am I missing?

Upvotes: 0

Views: 1499

Answers (1)

Telokis
Telokis

Reputation: 3389

One solution for this issue would be to override the res.json function like so:

// process all responses to add ed25519
app.use(function(req, res, next) {
    const oldResJson = res.json;

    res.json = function(body) {
        res.setHeader('CharCount', /* Use body here */);
        oldResJson.call(res, body);
    }

    next();
});

By doing this, you don't even need to change your controllers.

Upvotes: 2

Related Questions