DEV Community

Cover image for Using NestInterceptor to capture requests and responses
Visakh Vijayan
Visakh Vijayan

Posted on • Edited on

7 2

Using NestInterceptor to capture requests and responses

We needed a provision to capture API requests and responses. This was so that our mobile team could get a summary of what the app was sending and receiving. Once captured we wrote them in a file in the last-in-first-seen order.

We eventually started off by implementing the Nest Middleware but then we realized a middleware can only receive requests. So we switched to Interceptors.

An interceptor has access to both requests and responses.

Here is the code.

class LoggerInterceptor implements NestInterceptor
{
    intercept(context: ExecutionContext, next: CallHandler): Observable<any>
    {
        let logFile = process.env.LOGGER_APP + ".log";
        let logPath = process.cwd() + "<path>" + logFile;

        let { url, method, headers, body } = context.switchToHttp().getRequest();

        if (url != "/logs/dev.log")
        {
            let logMessage = "\n\n=======================================\n\nTIME: " + Date().toString() + "\nMETHOD: " + JSON.stringify(method) + "\nURL: " + JSON.stringify(url) + "\nHEADERS: " + JSON.stringify(headers) + "\nBODY: " + JSON.stringify(body) + "\nRESPONSE: ";

            return next.handle().pipe(tap((data) => 
            {
                let responseBody = JSON.stringify(data);

                logMessage += responseBody;

                // Reading old data.
                logMessage += fs.readFileSync(logPath);

                fs.writeFile(logPath, logMessage, function (err, file) { });
            }));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

A couple of points worth mentioning -

  1. is the path to where your log files should be stored. We wanted the app team to have access to the logs so we kept them in a public folder.
  2. We put up a check (!= "/logs/dev.log") to prevent logging access to the log file into the log file :D Lol!

Happy Programming!!!

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (1)

Collapse
 
vbao profile image
csvobao

Thanks a lot, this work for me!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay