MyInternships.in

Services, DI & Communication

Angular HTTP Interceptors

An interceptor sits between the application and the network, seeing every outgoing request and incoming response. It is where you attach auth tokens, add headers, log timings, show a global loader and handle 401 responses in one place.


What is HTTP Interceptors in Angular?

An interceptor sits between the application and the network, seeing every outgoing request and incoming response. It is where you attach auth tokens, add headers, log timings, show a global loader and handle 401 responses in one place.

HTTP Interceptors example

A functional auth interceptor
TypeScript
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token;

  const authorised = token
    ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
    : req;

  return next(authorised).pipe(
    catchError(err => {
      if (err.status === 401) inject(AuthService).logout();
      return throwError(() => err);
    })
  );
};

// app.config.ts
provideHttpClient(withInterceptors([authInterceptor]))

How this works

Requests are immutable, so you clone with the extra header rather than mutating. Functional interceptors replaced the older class-based HTTP_INTERCEPTORS approach.

Key points to remember

  • Interceptors run in the order they are registered.
  • Common uses: auth headers, base URL prefixing, loading indicators, retry, logging.
  • Skip specific requests by checking the URL before modifying.

Common mistakes with HTTP Interceptors

  • Mutating the request instead of cloning, which throws.
  • An interceptor that refreshes a token and triggers itself recursively.

Angular HTTP Interceptors— Interview Questions & FAQs

How do I add an auth token to every Angular request?+

Write an HttpInterceptorFn that clones each request with an Authorization header and register it with provideHttpClient(withInterceptors([...])). No service or component needs to know about the token.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships