Angular HTTP Interceptors

Learn Angular HTTP Interceptors with authentication, JWT tokens, logging, error handling, retry logic, request modification, response transformation, functional interceptors, architecture diagrams, enterprise examples, and interview questions.

HTTP Interceptors allow Angular applications to intercept, inspect, and modify HTTP requests and responses before they reach the backend or the application.

They provide a centralized way to implement cross-cutting concerns without duplicating code across multiple services.

HTTP Interceptors are widely used in enterprise applications for:

  • JWT Authentication
  • Authorization
  • Logging
  • Global Error Handling
  • Request Timing
  • Retry Logic
  • API Versioning
  • Response Transformation

HTTP Interceptors are one of the most frequently asked Angular interview topics.


Table of Contents

  • What are HTTP Interceptors?
  • Why Use Interceptors?
  • Interceptor Lifecycle
  • Functional vs Class-Based Interceptors
  • Creating an Interceptor
  • Authentication Interceptor
  • Logging Interceptor
  • Error Handling Interceptor
  • Retry Strategy
  • Multiple Interceptors
  • Enterprise Banking Example
  • Performance Best Practices
  • Common Mistakes
  • Top 10 Interview Questions
  • Summary

What are HTTP Interceptors?

An HTTP Interceptor is middleware that executes between HttpClient and the backend server.

It can:

  • Inspect requests
  • Modify requests
  • Add headers
  • Attach JWT tokens
  • Log requests
  • Transform responses
  • Handle errors
  • Retry failed requests

Example

Component

↓

HttpClient

↓

Interceptor

↓

REST API

↓

Interceptor

↓

Component

HTTP Interceptor Architecture

flowchart LR

Component

Component --> Service

Service --> HttpClient

HttpClient --> Interceptor

Interceptor --> RESTAPI

RESTAPI --> Response

Response --> Interceptor

Interceptor --> Component

Why Use HTTP Interceptors?

Without Interceptors

  • Duplicate authentication code
  • Repeated error handling
  • Logging scattered everywhere
  • Difficult maintenance

With Interceptors

  • Centralized authentication
  • Global error handling
  • Cleaner services
  • Better maintainability
  • Reusable logic

Interceptor Lifecycle

HTTP Request

↓

Interceptor

↓

REST API

↓

HTTP Response

↓

Interceptor

↓

Application

Interceptors can modify both requests and responses.


Request-Response Flow

sequenceDiagram

participant Component

participant HttpClient

participant Interceptor

participant API

Component->>HttpClient: HTTP Request

HttpClient->>Interceptor: Request

Interceptor->>API: Modified Request

API-->>Interceptor: Response

Interceptor-->>HttpClient: Modified Response

HttpClient-->>Component: Observable

Functional vs Class-Based Interceptors

Angular supports both approaches.

Functional Interceptor Class-Based Interceptor
Introduced in Angular 15 Traditional approach
Uses HttpInterceptorFn Implements HttpInterceptor
Uses inject() Constructor Injection
Recommended for standalone apps Common in NgModule apps
Less boilerplate More verbose

Functional Interceptor

import {
  HttpInterceptorFn
} from '@angular/common/http';

export const authInterceptor:
HttpInterceptorFn = (

req,
next

) => {

const token =
localStorage.getItem('token');

const request = req.clone({

setHeaders: {

Authorization:
`Bearer ${token}`

}

});

return next(request);

};

Register

import {
provideHttpClient,
withInterceptors
} from '@angular/common/http';

bootstrapApplication(AppComponent, {

providers:[

provideHttpClient(

withInterceptors([

authInterceptor

])

)

]

});

Functional Interceptor Architecture

flowchart LR

HttpClient

HttpClient --> FunctionalInterceptor

FunctionalInterceptor --> API

Class-Based Interceptor

import {
Injectable
} from '@angular/core';

import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';

import {
Observable
} from 'rxjs';

@Injectable()
export class AuthInterceptor
implements HttpInterceptor{

intercept(

req:HttpRequest<any>,

next:HttpHandler

):Observable<HttpEvent<any>>{

const cloned=req.clone({

setHeaders:{

Authorization:'Bearer TOKEN'

}

});

return next.handle(cloned);

}

}

Registration

providers:[

{

provide:HTTP_INTERCEPTORS,

useClass:AuthInterceptor,

multi:true

}

]

Authentication Architecture

flowchart TD

Login

Login --> JWT

JWT --> Interceptor

Interceptor --> HttpClient

HttpClient --> RESTAPI

RESTAPI --> Response

Authentication Interceptor

Typical responsibilities

  • Attach JWT token
  • Refresh expired tokens
  • Add Authorization header
  • Skip public APIs
  • Handle authentication failures

Example

const authReq=req.clone({

setHeaders:{

Authorization:

`Bearer ${token}`

}

});

Logging Interceptor

return next(req)

.pipe(

tap(event=>{

console.log(

event

);

})

);

Common logging information

  • URL
  • Method
  • Response Time
  • Status Code
  • Errors

Logging Flow

flowchart LR

Request

Request --> Logger

Logger --> API

API --> Logger

Logger --> Console

Global Error Handling Interceptor

return next(req)

.pipe(

catchError(error=>{

console.error(error);

return throwError(

()=>error

);

})

);

Common status codes

Code Meaning
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
500 Internal Server Error

Error Handling Architecture

flowchart TD

Request

Request --> API

API --> Error

Error --> Interceptor

Interceptor --> UI

Retry Failed Requests

Retry temporary failures.

return next(req)

.pipe(

retry(2)

);

Retry is appropriate for transient issues such as network interruptions or temporary server failures. It should generally not retry client errors like 400 Bad Request.


Retry Flow

flowchart LR

Request

Request --> Failure

Failure --> Retry

Retry --> API

API --> Success

Response Transformation

Interceptors can modify responses before components receive them.

return next(req)

.pipe(

map(event=>{

return event;

})

);

Typical use cases

  • Standardize response format
  • Convert date strings
  • Remove wrapper objects
  • Normalize API responses

Response Transformation Architecture

flowchart TD

RESTAPI

RESTAPI --> RawResponse

RawResponse --> Interceptor

Interceptor --> TransformedResponse

TransformedResponse --> Component

Multiple Interceptors

Enterprise applications often register several interceptors.

Execution Order

Request

↓

Authentication

↓

Logging

↓

Caching

↓

REST API

↓

Caching

↓

Logging

↓

Authentication

↓

Component

Request interceptors execute in registration order, while responses flow back in the reverse order.


Multiple Interceptor Architecture

flowchart LR

Component

Component --> AuthInterceptor

AuthInterceptor --> LoggingInterceptor

LoggingInterceptor --> CacheInterceptor

CacheInterceptor --> RESTAPI

Enterprise Banking Example

Mobile Banking Application

Interceptors

  • Authentication
  • Token Refresh
  • Logging
  • Global Error Handling
  • Retry
  • Correlation ID
  • Security Headers

Architecture

flowchart TD

AngularApp

AngularApp --> HttpClient

HttpClient --> AuthInterceptor

AuthInterceptor --> LoggingInterceptor

LoggingInterceptor --> RetryInterceptor

RetryInterceptor --> ErrorInterceptor

ErrorInterceptor --> BankingAPI

BankingAPI --> Microservices

Microservices --> Database

Benefits

  • Centralized security
  • Better observability
  • Cleaner services
  • Easier maintenance
  • Enterprise scalability

Interceptor Lifecycle

flowchart TD

Component

Component --> HttpClient

HttpClient --> RequestInterceptor

RequestInterceptor --> RESTAPI

RESTAPI --> ResponseInterceptor

ResponseInterceptor --> Component

Performance Best Practices

Practice Benefit
Keep interceptors lightweight Better performance
Register only required interceptors Less overhead
Use functional interceptors for standalone apps Cleaner code
Skip authentication for public endpoints Avoid unnecessary work
Retry only transient failures Better reliability
Keep business logic out of interceptors Better separation of concerns

Common Mistakes

Adding Authentication Headers Manually

Avoid

this.http.get(

url,

{

headers

}

);

for every request.

Use an Authentication Interceptor instead.


Performing Business Logic

Interceptors should focus on HTTP concerns only.

Avoid putting domain-specific business rules inside them.


Retrying Every Error

Do not retry

  • 400
  • 401
  • 403
  • 404

Retry only temporary failures where appropriate.


Modifying the Original Request

HttpRequest objects are immutable.

Always use

req.clone(...)

before modifying a request.


Registering Interceptors in the Wrong Order

Authentication should usually execute before logging or caching if later interceptors depend on authentication headers.


Best Practices

  • Use functional interceptors for modern standalone Angular applications.
  • Centralize authentication.
  • Handle errors globally.
  • Clone immutable requests.
  • Keep interceptors focused on HTTP concerns.
  • Retry only transient failures.
  • Add correlation IDs for distributed tracing.
  • Unit test interceptor behavior.

Advantages

Feature Benefit
Authentication Centralized security
Logging Better observability
Error Handling Consistent behavior
Retry Improved reliability
Response Transformation Cleaner components
Enterprise Ready Scalable architecture

Top 10 Angular HTTP Interceptors Interview Questions

1. What are HTTP Interceptors?

Answer

HTTP Interceptors are middleware components that intercept and optionally modify HTTP requests and responses before they reach the backend or the application.


2. Why use HTTP Interceptors?

Answer

They centralize authentication, logging, error handling, retry logic, and other cross-cutting concerns, reducing duplicate code.


3. What is the difference between Functional and Class-Based Interceptors?

Answer

Functional Interceptors use HttpInterceptorFn and are recommended for standalone Angular applications, while Class-Based Interceptors implement the HttpInterceptor interface and are commonly used in NgModule-based applications.


4. Why is req.clone() required?

Answer

HttpRequest objects are immutable. To modify a request, you must create a cloned copy using req.clone().


5. How are JWT tokens added to requests?

Answer

Authentication Interceptors clone outgoing requests and add an Authorization: Bearer <token> header.


6. What is the execution order of multiple interceptors?

Answer

Requests pass through interceptors in the order they are registered, while responses travel back in the reverse order.


7. What are common Interceptor use cases?

Answer

  • Authentication
  • Logging
  • Error handling
  • Retry logic
  • Request timing
  • Response transformation
  • Correlation IDs

8. Can Interceptors modify responses?

Answer

Yes.

They can inspect, transform, or standardize responses before they are delivered to the application.


9. Should business logic be placed inside Interceptors?

Answer

No.

Interceptors should focus only on HTTP-related concerns such as authentication, logging, retries, and error handling.


10. What are HTTP Interceptor best practices?

Answer

  • Keep interceptors lightweight.
  • Clone requests before modification.
  • Use functional interceptors in standalone applications.
  • Retry only transient failures.
  • Centralize authentication.
  • Unit test interceptor logic.

Interview Cheat Sheet

Topic Remember
Modern API HttpInterceptorFn
Legacy API HttpInterceptor
Immutable Request req.clone()
Authentication JWT Bearer Token
Logging tap()
Error Handling catchError()
Retry retry()
Response Order Reverse interceptor order
Registration withInterceptors() / HTTP_INTERCEPTORS
Best Practice Keep interceptors focused on HTTP concerns

Summary

Angular HTTP Interceptors provide a powerful mechanism for centralizing cross-cutting HTTP concerns such as authentication, logging, error handling, retries, and response transformation. By leveraging functional interceptors in modern standalone applications or class-based interceptors in NgModule applications, developers can eliminate duplicate code, improve maintainability, and build secure, scalable, and enterprise-ready Angular applications.


Key Takeaways

  • ✔ HTTP Interceptors intercept both requests and responses.
  • ✔ Functional Interceptors are recommended for standalone Angular applications.
  • ✔ Class-Based Interceptors remain common in NgModule applications.
  • ✔ Always clone immutable requests before modification.
  • ✔ Use Interceptors for authentication, logging, retries, and error handling.
  • ✔ Responses travel through interceptors in reverse order.
  • ✔ Keep interceptors lightweight and focused on HTTP concerns.
  • ✔ Retry only transient failures.
  • ✔ Centralize authentication instead of duplicating code.
  • ✔ HTTP Interceptors are one of the most important Angular interview topics.

Next Article

➡️ 64-RxJS-Observables-QA.md