Skip to main content

Overview

The authInterceptor is an Angular HTTP interceptor that automatically adds JWT authentication tokens to outgoing HTTP requests. It retrieves the token from local storage via the TokenStorageService and injects it into the Authorization header of each request.
This interceptor uses Angular’s functional interceptor API (HttpInterceptorFn) introduced in Angular 15+, which is simpler and more tree-shakeable than the class-based approach.

Signature

Type Definition

Parameters:
  • req - The outgoing HTTP request to be intercepted
  • next - The next handler in the interceptor chain
Returns: An Observable of the HTTP event stream

Implementation

How It Works

  1. Inject TokenStorageService: Uses Angular’s inject() function to get the token storage service instance
  2. Retrieve Token: Calls getToken() to fetch the JWT token from local storage
  3. Check Token Existence: If no token exists, passes the original request unchanged to the next handler
  4. Clone Request: Creates a cloned request with the Authorization header added
  5. Forward Request: Passes the modified request to the next handler in the chain
The interceptor clones the request rather than modifying it directly because HTTP requests are immutable in Angular. This ensures the original request object remains unchanged.

Dependencies

TokenStorageService

The interceptor depends on the TokenStorageService to retrieve the authentication token:
The getToken() method returns the JWT token stored in localStorage under the key 'auth-token', or null if no token exists.

Registration

The interceptor must be registered in your application configuration using the provideHttpClient() function with the withInterceptors() feature.

app.config.ts

The withInterceptors() function accepts an array of interceptors that will be applied in the order they are provided. The authInterceptor is applied to all HTTP requests made through Angular’s HttpClient.

Usage Examples

Basic Usage

Once registered, the interceptor automatically applies to all HTTP requests:

Request Transformation

Before Interceptor:
After Interceptor:

Authentication Flow

After calling tokenStorage.saveToken(), all subsequent HTTP requests will automatically include the Authorization header. After calling tokenStorage.signOut(), the header will no longer be added.

Skipping the Interceptor

If you need to make requests without the authentication token (e.g., public endpoints), you can check the token before the request or use a different HTTP client instance. However, the current implementation safely handles missing tokens by passing the request unchanged.

Testing

The interceptor can be tested using Angular’s TestBed:

Source Code

Location: src/app/core/interceptors/auth-interceptor.ts View the complete implementation in the source repository.