I am developing logging middleware, and want to log response body in 500 responses. In middleware im setting a callback for “finish” event on request, that emits after the response was sent, but no response body in Response
object is present.
I assume there is no body because nest js with express under the hood sends response by chanks, and does not saves it in Request
or Response
objects.
But I hope there is a workaround to get response body from Response
object in middleware that someone found. The example of middleware class im working on:
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(request: Request, response: Response, next: NextFunction): void {
const { ip, method, originalUrl } = request;
const userAgent = request.get("user-agent") || "";
response.on("finish", () => {
const { statusCode } = response;
const contentLength = response.get("content-length");
const basicRequestMetaInfo = {
method,
originalUrl,
statusCode,
... // other data
};
if (this.isErroneousStatusCode(statusCode)) {
const additionalRequestMetaInfo = {
body: response.body, // The place i want to reach Response body
};
this.winstonLoggerErrorLevel.error({
...basicRequestMetaInfo,
...additionalRequestMetaInfo,
});
return;
}
this.winstonLoggerInfoLevel.info(basicRequestMetaInfo);
});
next();
}
}