Angular version 4.3 introduced the most long-awaited feature: the HttpInterceptor interface. Until this version, there was no way to modify or to intercept http request globally.

Why HTTP interceptors are useful? HTTP Interceptors are used for adding custom logic for logging, modifying response, error handling, but one common case is to automatically attach authentication informations to request and to refresh token in order to maintain user session active.

Create an Interceptor

This tutorial assumes you already have an authentication service in your application and that you are storing JWT token in local storage.

The first step is to create an interceptor. To do this, let’s create an Injectable class which implements HttpInterceptor and catch errors that might occur.

// src/app/services/token-interceptor.service.ts



import { Injectable } from '@angular/core';

import { HttpRequest, HttpHandler,HttpEvent, HttpInterceptor } from '@angular/common/http';

import { AuthenticationService } from '../authentication.service';

import { Observable } from 'rxjs/Observable';



@Injectable()

export class RefreshTokenInterceptor implements HttpInterceptor {



constructor(public auth: AuthenticationService) {}



intercept(request: HttpRequest<any>, next: HttpHandler):

Observable<HttpEvent<any>> {



return next.handle(request)

.catch(error => {

return Observable.throw(error);

}); }

}

I want to mention that you must use the new HttpClient imported from @angular/common/http because the older http client does not trigger the HttpInterceptor.

Looking for Unauthorized Responses

When access token expire generally server send a 401 Unauthorized response. In this case we need to log in again the user, in order to continue to use the application with a new access token.

It is important to check if failed request it’s not the refresh token request itself, to avoid recursion. Also, we need to check if refresh token request is in progress or not because we don’t want other calls to come in and call refreshToken again. Another important steps are commented in code :

Conclusion

The new HttpInterceptor it is a powerful and useful feature and it’s the better place where we can intercept and/or mutate outgoing requests or incoming responses.