In AngularJS, $http
interceptors allow us to modify API requests and responses globally before they reach the application or server. They are useful for:
✔ Adding authentication tokens to every request
✔ Logging or modifying API responses
✔ Handling global errors (e.g., 401 Unauthorized)
✔ Transforming request/response data
1. What is an $http
Interceptor?
An $http
interceptor is a middleware function that sits between the AngularJS application and the backend API. It intercepts every request and response and allows you to modify them.
2. Creating an $http
Interceptor in AngularJS
AngularJS interceptors are created using the $httpProvider.interceptors
array.
Example: Adding an Authorization Token to Every Request
var app = angular.module("myApp", []);
app.factory("AuthInterceptor", function ($q) {
return {
request: function (config) {
var token = localStorage.getItem("authToken"); // Fetch token from storage
if (token) {
config.headers.Authorization = "Bearer " + token;
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
console.error("Unauthorized request - Redirecting to login.");
window.location.href = "/login";
}
return $q.reject(rejection);
}
};
});
// Register the interceptor
app.config(function ($httpProvider) {
$httpProvider.interceptors.push("AuthInterceptor");
});
🔹 How It Works:
request
: Modifies every outgoing API call by adding an Authorization header.responseError
: If the API returns 401 Unauthorized, the user is redirected to the login page.- Registered in
$httpProvider.interceptors
during the app configuration phase.
3. Modifying Response Data Using Interceptors
Sometimes, we need to format response data before using it in the application.
Example: Formatting API Response Data
app.factory("ResponseInterceptor", function ($q) {
return {
response: function (response) {
if (response.data && response.data.results) {
response.data = response.data.results; // Extract 'results' array from response
}
return response;
}
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push("ResponseInterceptor");
});
🔹 Why Use This?
- Suppose an API response is
{ results: [...] }
, but we only needresults
. - This interceptor automatically transforms all responses, so controllers/services get cleaner data.
4. Logging Requests and Responses for Debugging
Logging all API requests and responses can help troubleshoot API calls.
Example: Logging API Calls
app.factory("LoggingInterceptor", function () {
return {
request: function (config) {
console.log("API Request:", config.method, config.url);
return config;
},
response: function (response) {
console.log("API Response:", response.status, response.data);
return response;
}
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push("LoggingInterceptor");
});
🔹 Why Use This?
- Logs every API call (method, URL, and response data).
- Helps in debugging API failures.
5. Handling Global Errors (500, 404, etc.)
We can catch all API errors globally instead of handling them in every $http
call.
Example: Global Error Handling
app.factory("ErrorInterceptor", function ($q) {
return {
responseError: function (rejection) {
switch (rejection.status) {
case 400:
console.error("Bad Request: Check request parameters.");
break;
case 404:
console.error("Not Found: The requested resource does not exist.");
break;
case 500:
console.error("Server Error: Something went wrong on the server.");
break;
default:
console.error("HTTP Error:", rejection.status, rejection.statusText);
}
return $q.reject(rejection);
}
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push("ErrorInterceptor");
});
🔹 Why Use This?
- Centralized error handling: No need to check
error.status
in every$http.get()
. - Improves user experience by showing proper error messages.
6. Combining Multiple Interceptors
We can register multiple interceptors to handle different concerns:
app.config(function ($httpProvider) {
$httpProvider.interceptors.push("AuthInterceptor");
$httpProvider.interceptors.push("ResponseInterceptor");
$httpProvider.interceptors.push("LoggingInterceptor");
$httpProvider.interceptors.push("ErrorInterceptor");
});
Execution Order:
1️⃣ Request Interceptors run before the request is sent.
2️⃣ Response Interceptors run after the API returns data.
3️⃣ If an error occurs, responseError handlers run.
7. When to Use $http
Interceptors?
Use Case | Interceptor Method |
---|---|
Add Authorization headers | request |
Modify response data format | response |
Log API calls | request , response |
Handle authentication errors (401) | responseError |
Handle global API errors (404, 500) | responseError |