0
0
Angularframework~5 mins

Interceptors for request modification in Angular

Choose your learning style9 modes available
Introduction

Interceptors let you change or add information to every request before it is sent. This helps keep your code clean and consistent.

Add an authorization token to every request automatically.
Log or track outgoing requests for debugging.
Modify headers or parameters for all requests in one place.
Handle errors globally before they reach components.
Syntax
Angular
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const modifiedReq = req.clone({
      // modify request here, e.g. add headers
    });
    return next.handle(modifiedReq);
  }
}

The intercept method runs for every HTTP request.

Use req.clone() to create a changed copy without altering the original request.

Examples
Adds an Authorization header with a token to every request.
Angular
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const token = 'my-token';
  const modifiedReq = req.clone({
    setHeaders: { Authorization: `Bearer ${token}` }
  });
  return next.handle(modifiedReq);
}
Logs the URL of each outgoing request without modifying it.
Angular
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  console.log('Request URL:', req.url);
  return next.handle(req);
}
Sample Program

This interceptor adds a bearer token to every HTTP request's headers automatically. You register it in your app module so Angular uses it for all requests.

Angular
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 token = '12345';
    const authReq = req.clone({
      setHeaders: { Authorization: `Bearer ${token}` }
    });
    return next.handle(authReq);
  }
}

// Usage in app.module.ts providers array:
// { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
OutputSuccess
Important Notes

Always return next.handle() with the (possibly modified) request to continue the request chain.

Register interceptors in the providers array with multi: true to allow multiple interceptors.

Summary

Interceptors let you change HTTP requests before sending.

Use req.clone() to safely modify requests.

Register interceptors globally to apply changes everywhere.