Axios Middleware Service
axios-middleware is a utility library designed to simplify the creation and management of HTTP middleware for Axios, aiming to offer more flexibility and testability compared to native Axios interceptors. It allows developers to register middleware objects with methods like `onRequest`, `onResponse`, and `onResponseError` to hook into different stages of a request lifecycle. The current stable version is 0.4.0, which was released as an 'End of life' version. The package is now abandoned, with the maintainer recommending alternatives due to breaking changes in newer Axios versions and a shift in recommended HTTP client practices. It supports Node.js environments and had a peer dependency on Axios versions `>=0.17.1 <1.2.0`.
Common errors
-
TypeError: Class extends value undefined is not a constructor or null
cause Attempting to extend the `HttpMiddleware` base class after upgrading to `axios-middleware` v0.3.0 or later, where this class was removed.fixRemove the `extends HttpMiddleware` clause from your middleware class definition. Implement handler methods directly or use plain objects for middleware. -
Property 'handleRequestError' does not exist on type '...' or 'middleware.use' expects a different type of handler.
cause Using old `handle` prefixed method names (e.g., `handleRequestError`) after upgrading to `axios-middleware` v0.1.3 or later.fixUpdate method names from `handleX` to `onX` (e.g., `handleRequestError` becomes `onRequestError`, `handleResponse` becomes `onResponse`). -
TypeError: Cannot read properties of undefined (reading 'interceptors') or TypeError: axiosInstance.interceptors is undefined
cause Incorrectly initializing `axios-middleware` with a non-Axios instance or a misconfigured Axios instance.fixEnsure `axiosMiddleware` is instantiated with a valid `axios` instance created using `axios.create()` or the global `axios` object.
Warnings
- breaking The `HttpMiddleware` base class was removed in v0.3.0. Projects inheriting from this class will break.
- breaking Method prefixes for middleware handlers changed from `handle` to `on` in v0.1.3. For example, `handleRequestError` became `onRequestError`.
- gotcha This package has reached its End of Life (EOL) with version 0.4.0. The maintainer explicitly states it will no longer be maintained due to breaking changes in Axios and general shifts in recommended HTTP client practices.
- gotcha The package's peer dependency for `axios` is `>=0.17.1 <1.2.0`. Using `axios-middleware` with Axios v1.2.0 or newer versions (e.g., Axios v2.x) will likely lead to incompatibility issues and unexpected behavior.
Install
-
npm install axios-middleware -
yarn add axios-middleware -
pnpm add axios-middleware
Imports
- default
import { axiosMiddleware } from 'axios-middleware';import axiosMiddleware from 'axios-middleware';
- AxiosMiddleware
import { AxiosMiddleware } from 'axios-middleware';import axiosMiddleware from 'axios-middleware'; const middleware = new axiosMiddleware(client);
- Middleware Handler Object
middleware.use({ onRequest(config) { /* ... */ }, onResponse(response) { /* ... */ } });
Quickstart
import axios from 'axios';
import axiosMiddleware from 'axios-middleware';
const client = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000
});
const middleware = new axiosMiddleware(client);
middleware.use({
onRequest(config) {
console.log('[Middleware] Request sent:', config.method?.toUpperCase(), config.url);
// Example: Add an authorization header
config.headers['X-Custom-Auth'] = 'my-secret-token';
return config;
},
onResponse(response) {
console.log('[Middleware] Response received for', response.config.url, 'Status:', response.status);
return response;
},
onRequestError(error) {
console.error('[Middleware] Request error:', error.message);
return Promise.reject(error);
},
onResponseError(error) {
console.error('[Middleware] Response error for', error.config.url, 'Status:', error.response?.status, error.message);
return Promise.reject(error);
}
});
// Make a request using the configured Axios instance
client.get('/posts/1')
.then(response => {
console.log('API Response Data:', response.data);
})
.catch(error => {
console.error('API Call Failed:', error.message);
});
// Example of a request that might trigger an error (e.g., non-existent endpoint)
client.get('/nonexistent-path')
.catch(error => {
console.error('Non-existent path call failed, caught by application:', error.message);
});