Injecting auth-headers into angular.js application using http.config vz using interceptors.
We have been building a client app in Angular.js
and decided on using token auth with JWTs, pretty much the normal choice.
We got everything set up on the server side and am receiving the token on the client side, but now we just need to send the token with every request.
At this point, our front-end developer bought an interesting point to debate. Should we be using an interceptor or should we add headers using $httpProvider config
Most resources out there say to use an $http interceptor to transform every outgoing request, but doesn't specify the reason as to why the approach is better than the other. I thought of writing it to give some insight on the internals of the same:
default headers vz $http interceptors.
The big difference between the two is that the providers are only executed once, during the config phase of the module ( .config() )
Interceptors are called on the fly and are much more flexible with what you can do with them.
When to use providers
Use providers to set global config options where these options are static, never changing during the lifecycle of your app.
An example use case would be in a situation where you could use $httpProvider to set a token header, say for example if you're using a third-party API and they require an API_KEY on every request.
Generally, API_KEY's don't change, so it would make sense that your application config phase would set the API_KEY in the provider, again abiding by the "static only settings" idea.
When to use interceptors
Use interceptors, to apply values that may dynamically change through the life cycle of your application.
The best illustration of interceptors would be to use and set Authentication headers or tokens that need to be sent along with each request. These tokens can change, and also might expire after a certain time.
An example code for injecting an interceptor for sending an authentication token along with each request is as follows:
module.factory('authInjector', ['AuthService', function(AuthService) {
var authInjector = {
request: function(config) {
if (!AuthService.isAnonymus) {
config.headers['Authentication-token'] = AuthService.token;
}
return config;
}
};
return authInjector;
}]);
module.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('authInjector');
}]);
TL;DR
The best way to do it is through the interceptor. Doing the setup in the .config()
or .run()
should be preferred for values that don't change over the lifecycle of the app.