Axios Middleware Layer
raw JSON →middleware-axios is a JavaScript and TypeScript library that extends the popular Axios HTTP client, providing an Express or Koa-like middleware interface for intercepting and modifying HTTP requests and responses. The current stable version is 3.0.0, which introduced dual CommonJS and ESM support and updated its peer dependency to Axios `^1.7.4`. The project demonstrates an active release cadence, with major versions addressing significant architectural changes like module system compatibility and dependency updates, while patch releases focus on type fixes and minor improvements. Its key differentiator lies in abstracting the native Axios interceptor pattern into a more structured, sequential middleware pipeline, allowing developers to easily add global or instance-specific pre-request and post-response logic, access `axios.defaults`, and control the flow with a `next()` function call, making request handling more modular and maintainable.
Common errors
error TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for .../node_modules/middleware-axios/dist/index.js ↓
type: "module" is set in your package.json if using ESM import statements, or explicitly use dynamic import() for ESM modules in a CJS context. For middleware-axios v3, ensure you are using import { create } from 'middleware-axios';. error ERR_PACKAGE_PATH_NOT_EXPORTED (or similar import errors) from 'middleware-axios/some/path' ↓
import { create } from 'middleware-axios';. Do not attempt to import from internal paths. error Peer dependency 'axios@^1.7.4' must be installed ↓
axios to a compatible version: npm install axios@^1.7.4 or yarn add axios@^1.7.4. Warnings
breaking Version 3.0.0 introduced significant changes, including dual ESM/CJS support, which may require updating import statements in your project. The `exports` field was added to `package.json`, and the `src` folder is no longer included in the distributed package. ↓
breaking The `axios` peer dependency was updated to `^1.7.4` in version 3.0.0. Older versions of `axios` might lead to compatibility issues or unresolved peer dependency warnings. ↓
gotcha It is critical to call `await next(config)` within your middleware function. Failing to do so will halt the request chain, preventing the actual Axios request from being sent or subsequent middleware from executing. ↓
deprecated In version 2.1.6, the `instanceConfig` type was aligned with `CreateAxiosDefaults` from Axios. While not a strict breaking change, TypeScript projects might need to update their type definitions if they were explicitly typing this parameter. ↓
breaking Minimum Axios version requirements have frequently changed across 2.x releases. Notably, versions 2.1.2 required `^0.24.0`, 2.1.3 required `^1.1.3`, and 2.1.4 required `^1.2.0-alpha.1` due to bug fixes in Axios itself. Using an older Axios version with these `middleware-axios` releases can lead to runtime issues. ↓
Install
npm install middleware-axios yarn add middleware-axios pnpm add middleware-axios Imports
- create wrong
const { create } = require('middleware-axios');correctimport { create } from 'middleware-axios'; - MiddlewareAxiosInstance
import type { MiddlewareAxiosInstance } from 'middleware-axios'; - AxiosMiddleware
import type { AxiosMiddleware } from 'middleware-axios';
Quickstart
import { create } from 'middleware-axios';
import type { AxiosResponse } from 'axios';
// Create a wrapped Axios instance, similar to a normal axios.create()
const api = create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000,
});
// Add a middleware to log requests and responses
api.use(async (config, next, defaults) => {
console.log(`[REQUEST] ${config.method?.toUpperCase()} ${config.url}`);
console.log(' Base URL from defaults:', defaults.baseURL);
// Crucially, await next(config) passes control to the next middleware or Axios itself
await next(config);
// This code runs after the response is received
const response: AxiosResponse = await config.axiosData; // Access the response data from the config
console.log(`[RESPONSE] ${config.method?.toUpperCase()} ${config.url} - Status: ${response.status}`);
// console.log(' Response Data:', response.data);
});
// Use the wrapped instance like a normal Axios instance
api.get('/todos/1')
.then(response => {
console.log('\n--- API Call Successful ---');
console.log('Todo Title:', response.data.title);
console.log('Response Status:', response.status);
})
.catch(error => {
console.error('\n--- API Call Failed ---');
if (error.response) {
console.error('Error Status:', error.response.status);
console.error('Error Data:', error.response.data);
} else if (error.request) {
console.error('No response received:', error.request);
} else {
console.error('Error message:', error.message);
}
});
// You can also access the pure Axios instance if needed
// console.log(api.axiosInstance);