Thuta Learning
Angular
AdvancedWeb DevelopmentIntermediate

HTTP Interceptors

AngularLesson 3925 min

What you'll walk away with

  • Explain the core concept and Angular data flow of HTTP Interceptors
  • Run the example, predict its state and UI, and test edge and error cases
  • Apply a typed safe pattern in a real project and recognize common pitfalls

Explain it simply

HTTP Interceptors, in plain language

HTTP Interceptors intercept HTTP requests/responses, letting you modify them, log them, or handle errors.

Problem → Why → Solution

The problem — why this concept matters

Logging full request bodies or tokens in an interceptor can leak sensitive data.

A common mistake

One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Core concept — understand how it works

HTTP interceptors form a cross-cutting request and response pipeline suitable for auth headers, correlation IDs, logging, and centralized error normalization. Requests are immutable and must be cloned; interceptor order and retry behavior matter. Token refresh logic must handle concurrent failures, prevent loops, and exclude appropriate endpoints.

Mental model
  1. input and state
  2. component and template
  3. rendered Angular UI

Explain the core concept and Angular data flow of HTTP Interceptors

Core syntax or pattern

typescript
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Add auth token to request
    const token = localStorage.getItem('auth_token');
    
    if (token) {
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    
    return next.handle(req);
  }
}

// logging.interceptor.ts
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    console.log('Request:', req.url);
    const started = Date.now();
    
    return next.handle(req).pipe(
      tap(() => {
        const elapsed = Date.now() - started;
        console.log(`Response took ${elapsed}ms`);
      })
    );
  }
}

// app.module.ts
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
  ]
})

HTTP interceptors form a cross-cutting request and response pipeline suitable for auth headers, correlation IDs, logging, and centralized error normalization. Requests are immutable and must be cloned; interceptor order and retry behavior matter. Token refresh logic must handle concurrent failures, prevent loops, and exclude appropriate endpoints.

Read the code step by step

  1. input and state// auth.interceptor.ts

    HTTP Interceptors intercept HTTP requests/responses, letting you modify them, log them, or handle errors.

  2. component and templateexport class LoggingInterceptor implements HttpInterc...

    HTTP interceptors form a cross-cutting request and response pipeline suitable for auth headers, correlation IDs, logging, and centralized error normalization. Requests are immutable and must be cloned; interceptor order and retry behavior matter. Token refresh logic must handle concurrent failures, prevent loops, and exclude appropriate endpoints.

  3. rendered Angular UI})

    Build auth-header and timing interceptors, testing public-endpoint exclusion, 401 handling, retries, concurrent requests, and sensitive-log redaction.

Execution flow
  1. input and state
  2. component and template
  3. rendered Angular UI

Success

Explain the core concept and Angular data flow of HTTP Interceptors

Failure

Logging full request bodies or tokens in an interceptor can leak sensitive data.

HTTP Interceptors intercept HTTP requests/responses, letting you modify them, log them, or handle errors.

typescript
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Add auth token to request
    const token = localStorage.getItem('auth_token');
    
    if (token) {
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    
    return next.handle(req);
  }
}

// logging.interceptor.ts
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    console.log('Request:', req.url);
    const started = Date.now();
    
    return next.handle(req).pipe(
      tap(() => {
        const elapsed = Date.now() - started;
        console.log(`Response took ${elapsed}ms`);
      })
    );
  }
}

// app.module.ts
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
  ]
})
You should see
(Every HTTP request passes through the interceptors, which can handle things like auto-adding tokens and logging)

Real-world usage

How to apply it in a real project

Build auth-header and timing interceptors, testing public-endpoint exclusion, 401 handling, retries, concurrent requests, and sensitive-log redaction.

Mini challenge

Build it yourself

Rebuild the HTTP Interceptors example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
typescript
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Add auth token to request
    const token = localStorage.getItem('auth_token');
    
    if (token) {
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    
    return next.handle(req);
  }
}

// logging.interceptor.ts
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    console.log('Request:', req.url);
    const started = Date.now();
    
    return next.handle(req).pipe(
      tap(() => {
        const elapsed = Date.now() - started;
        console.log(`Response took ${elapsed}ms`);
      })
    );
  }
}

// app.module.ts
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
  ]
})

Expected: Explain the core concept and Angular data flow of HTTP Interceptors

Show hint

Build auth-header and timing interceptors, testing public-endpoint exclusion, 401 handling, retries, concurrent requests, and sensitive-log redaction.

Quick quiz 1 / 3

What best describes the core idea of HTTP Interceptors?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • input and state → component and template → rendered Angular UI
  • HTTP interceptors form a cross-cutting request and response pipeline suitable for auth headers, correlation IDs, logging, and centralized error normalization. Requests are immutable and must be cloned; interceptor order and retry behavior matter. Token refresh logic must handle concurrent failures, prevent loops, and exclude appropriate endpoints.
  • Logging full request bodies or tokens in an interceptor can leak sensitive data.
  • Build auth-header and timing interceptors, testing public-endpoint exclusion, 401 handling, retries, concurrent requests, and sensitive-log redaction.

Angular — HTTP Client — Angular

Easy traps

  • Logging full request bodies or tokens in an interceptor can leak sensitive data.
  • One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Hands-on Exercise

Rebuild the HTTP Interceptors example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

You'll know it worked when: (Every HTTP request passes through the interceptors, which can handle things like auto-adding tokens and logging)

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

HTTP Interceptors | Thuta Learning