We use cookies to enhance your experience on the site
CodeWorlds

Interceptors - Communication Guards

Interceptors are like guards standing at every castle gate - they intercept and process every message.

Functional Interceptors (Angular 15+)

1import { HttpInterceptorFn, HttpHandlerFn, HttpRequest } from '@angular/common/http';
2import { inject } from '@angular/core';
3
4// Auth Interceptor - adds token
5export const authInterceptor: HttpInterceptorFn = (req, next) => {
6  const authService = inject(AuthService);
7  const token = authService.getToken();
8
9  if (token) {
10    const clonedReq = req.clone({
11      headers: req.headers.set('Authorization', \`Bearer \${token}\`)
12    });
13    return next(clonedReq);
14  }
15
16  return next(req);
17};
18
19// Logging Interceptor
20export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
21  const started = Date.now();
22
23  return next(req).pipe(
24    tap({
25      next: (event) => {
26        if (event.type === HttpEventType.Response) {
27          const elapsed = Date.now() - started;
28          console.log(\`\${req.method} \${req.url} - \${elapsed}ms\`);
29        }
30      }
31    })
32  );
33};
34
35// Error Interceptor with retry
36export const errorInterceptor: HttpInterceptorFn = (req, next) => {
37  return next(req).pipe(
38    retry({
39      count: 2,
40      delay: (error, retryCount) => {
41        if (error.status === 503) {
42          return timer(1000 * retryCount);  // Exponential backoff
43        }
44        throw error;  // Don't retry other errors
45      }
46    }),
47    catchError((error: HttpErrorResponse) => {
48      if (error.status === 401) {
49        inject(AuthService).logout();
50        inject(Router).navigate(['/login']);
51      }
52      return throwError(() => error);
53    })
54  );
55};

Registering Interceptors

1// app.config.ts
2export const appConfig: ApplicationConfig = {
3  providers: [
4    provideHttpClient(
5      withInterceptors([
6        authInterceptor,
7        loggingInterceptor,
8        errorInterceptor
9      ])
10    )
11  ]
12};

Skip Interceptor for Selected Requests

1export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
2
3export const authInterceptor: HttpInterceptorFn = (req, next) => {
4  // Check context token
5  if (req.context.get(SKIP_AUTH)) {
6    return next(req);
7  }
8
9  // ... add token
10};
11
12// Usage - skip auth for public endpoints
13this.http.get('/api/public', {
14  context: new HttpContext().set(SKIP_AUTH, true)
15});
Go to CodeWorlds