Backend Integration - HTTP Interceptors 🚀

HTTP Interceptors in Angular are a powerful feature that allows you to intercept and modify HTTP requests and responses globally. In this project, HTTP Interceptors are used for handling authentication tokens and error responses, ensuring a seamless and secure interaction between the frontend and backend APIs.

🛠️ Implemented Interceptors

1. JwtInterceptor

The JwtInterceptor is responsible for attaching the JWT (JSON Web Token) to the headers of outgoing HTTP requests. This ensures that the backend can authenticate the user for every API call.

Key Responsibilities:

  • Automatically appends the Authorization header with the JWT token.
  • Ensures secure communication with the backend.

Code Snippet:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../services/authentication.service';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Add authorization header with jwt token if available
    const currentUser = this.authenticationService.currentUserValue;
    if (currentUser && currentUser.token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentUser.token}`
        }
      });
    }
    return next.handle(request);
  }
}

2. ErrorInterceptor

The ErrorInterceptor is designed to handle HTTP errors globally. It catches error responses from the backend and provides a unified way to handle them in the application.

Key Responsibilities:

  • Captures and processes HTTP errors.
  • Handles 401 Unauthorized errors by logging the user out.
  • Displays error messages using services like Toastr for better user feedback.

Code Snippet:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthenticationService } from '../services/authentication.service';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((err: HttpErrorResponse) => {
        if (err.status === 401) {
          // Auto logout if 401 response returned from api
          this.authenticationService.logout();
          location.reload();
        }
        const error = err.error.message || err.statusText;
        return throwError(error);
      })
    );
  }
}

🎯 Integration in the Application

Both interceptors are registered in the AppModule under the providers array. This ensures they are applied globally to all HTTP requests.

Configuration in AppModule:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './_helpers/jwt.interceptor';
import { ErrorInterceptor } from './_helpers/error.interceptor';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
  ]
})
export class AppModule { }

📂 File Location:

  • src/app/_helpers/jwt.interceptor.ts
  • src/app/_helpers/error.interceptor.ts

🌟 Benefits of Using Interceptors

  • Centralized Request Handling: Modify or inspect requests and responses in one place.
  • Authentication: Automatically attach tokens to requests.
  • Error Management: Handle errors globally, reducing redundancy in components.
  • Clean Code: Simplifies service and component logic by moving cross-cutting concerns to interceptors.

🛡️ Security and Usability

By leveraging the JwtInterceptor and ErrorInterceptor, this Angular application ensures:

  • Secure API communication by attaching tokens to requests.
  • Improved user experience with consistent error handling and feedback.

This setup is essential for applications requiring secure and efficient backend communication.