Skip to content

Instantly share code, notes, and snippets.

@myesn
Created December 22, 2022 01:52
Show Gist options
  • Save myesn/ec9fbb3a1e91c210a4dcb833da9d44ad to your computer and use it in GitHub Desktop.
Save myesn/ec9fbb3a1e91c210a4dcb833da9d44ad to your computer and use it in GitHub Desktop.
NestJS Middleware
// logging.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class LoggingMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`start [${req.method}] ${req.url}`);
const oldSend = res.send;
res.send = (body: any): any => {
console.log(body);
oldSend.call(res, body);
};
next();
console.log(`end [${req.method}] ${req.url}`);
}
}
// main.ts
async function bootstrap() {
app.use(new LoggingMiddleware().use);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment