Fr4ncis
Fr4ncis

Reputation: 1387

Express.js middleware that modifies response

I would like to express with middleware functions to modify the response.

app.use(function(request, response, next) {
    .. do something ..
    next(); // moves to next middleware
});

I can modify the request and response objects that will be passed on to the following middleware functions. Is there a convention or best-practice to modify these objects?

In my particular case I am setting res.body because by using res.write() it would actually send already the response payload. Is there some property where I can store the payload and it will be sent later by next middleware functions?

Upvotes: 1

Views: 1366

Answers (1)

Dan Kohn
Dan Kohn

Reputation: 34327

You can model your middleware on other middleware that modifies the body, such as Connect's compress. You'll see that you need to hook into the response stream, since Express and Connect are dealing with streams not static objects.

Upvotes: 1

Related Questions