Do you need control over all http requests of your app at once? Use an Angular http interceptor for incoming or outgoing http! In this post we will add a api-key header to all outgoing http requests and navigate to the login page for all 401 responses.

We are using plain Angular by implementing the HttpInterceptor interface (documentation here).

We are going to extend a simple application created in a previous post on ng-apimock. This application has already an http call with appropriate mocks. The complete code for the angular http interceptor is found on github here.

Outgoing http

Suppose our app is calling api’s via an api portal, for example an azure api portal. To gain access to the api we have to send our subscription key in a custom header. Here we implement HttpInterceptor so every outgoing http request gets the appropriate headers.

export class SubscriptionKeyInterceptor implements HttpInterceptor {

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const newHeaders = request.headers
            .set('Az-Subscription-Key', environment.subscriptionKey)
            .set('Az-Trace', String('true'));

        return next.handle(request.clone({ headers: newHeaders }));

Note that we clone the request and append the headers onto the existing headers. If we now run the app we see the headers being set.

developer console with 200 call 1024x525 - ANGULAR HTTP INTERCEPTOR

Incoming http

Let’s say the api returns specific information for the currently logged in user. This means the api returns a 401 for other users. We should navigate the user to the login page on such an event.

export class AuthenticateHttpInterceptor implements HttpInterceptor {

        private router: Router
    ) { }

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).pipe(
            catchError((error: HttpErrorResponse) => {
                if (error.status === 401) {

                    return EMPTY;

                return throwError(error);

Here we see the same setup as for outgoing http requests. But the mutation is not on the request but instead on the handled request here. The 401 error is caught and we navigate to the login page. For other errors we propagate the error. Now test your interceptor.

developer console with 401 call 1024x525 - ANGULAR HTTP INTERCEPTOR

Hopefully you can now implement your own Angular http interceptor and control the http flow. Happy intercepting!