Angular 4 (and Ionic 3): intercept http requests and add custom headers

Christian Benseler
Tableless
Published in
1 min readJul 31, 2017

The new HTTP Client from Angular (4.3), among a lot of new features, has one of the most important (for me): the possibility to intercept all http requests in an easier way and change them, adding some custom header (an usual need for those who use web token auth pattern).

I’m currently using this module below. You can place it in a file called interceptor.module.

import { Injectable, NgModule} from ‘@angular/core’;
import { Observable } from ‘rxjs/Observable’;
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ‘@angular/common/http’;

import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;

@Injectable()
export class HttpsRequestInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

const dupReq = req.clone({ headers: req.headers.set(‘Consumer-Secret’, ‘some sample key’) });

return next.handle(dupReq);
}
};

@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpsRequestInterceptor, multi: true }
]
})
export class InterceptorModule { }

Then, you just need to import in the the app.module.ts and add it to the imports from NgModule

import { InterceptorModule } from ‘./modules/interceptor.module’;
//
imports: [ …, InterceptorModule, …]

voilà: all your http requests will have a Consumer-Secret header with ‘some sample key’ being sent.

This other story has a full explanation of all new features and you can, of course, check the official doc: the guide has all information of how to use, features, explanation of the interceptor and how it works, how to intercept the responses too, and how to upgrade to this version.

--

--