Angular HttpInterceptor for Logging




    Angular snippets for TypeScript

    To intercept a request, we need to provide the interceptor with a handler and a next. The handler will be invoked for every request that passes through the interceptor and the next provides the hook into the routing system.

    We then pipe the incoming request into our tap function, which takes an Observable as its input and returns an Observable that emits events of the same type as the input Observable. In our case, that's HttpEvents.

    The tap function will keep track of the current time and if the event that it's receiving is an HttpEvent of type HttpResponse, it will also print out the elapsed time for the request.

    Library: angular

    Shortcut: a_http_interceptor_logging

    import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';
    export class LogInterceptor implements HttpInterceptor {
      constructor() {}
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started =;
        return next.handle(req).pipe(
          tap(event => {
            if (event instanceof HttpResponse) {
              const elapsed = - started;
              console.log(`Request for \${req.urlWithParams} took \${elapsed} ms.`);
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.