Axios Middleware Layer

raw JSON →
3.0.0 verified Thu Apr 23 auth: no javascript

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.

error TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for .../node_modules/middleware-axios/dist/index.js
cause Attempting to import `middleware-axios` in a CommonJS environment without proper configuration, or when Node.js incorrectly interprets the module as TypeScript due to file structure (less common with v3's `exports` field).
fix
For Node.js projects, ensure 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'
cause Version 3.0.0 added an `exports` field to `package.json` and removed the `src` folder from the distributed package. Direct imports from sub-paths like `middleware-axios/dist/index.js` or `middleware-axios/src/` are no longer supported or resolved.
fix
Always import symbols directly from the main package entry point: import { create } from 'middleware-axios';. Do not attempt to import from internal paths.
error Peer dependency 'axios@^1.7.4' must be installed
cause Your project's `axios` version does not satisfy the peer dependency requirement of `middleware-axios` v3.0.0, or `axios` is not installed at all.
fix
Install or upgrade axios to a compatible version: npm install axios@^1.7.4 or yarn add axios@^1.7.4.
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.
fix Ensure your build tools and Node.js environment are configured for ESM imports (e.g., using `import { create } from 'middleware-axios';`). If using CommonJS, explicit `require` might still work, but ESM is the recommended modern approach. Review your `package.json` for `type: 'module'`.
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.
fix Upgrade your `axios` installation to version `^1.7.4` or higher using `npm install axios@^1.7.4` or `yarn add axios@^1.7.4`.
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.
fix Always include `await next(config);` at the appropriate point in your middleware to ensure the request proceeds through the chain.
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.
fix For TypeScript users, ensure `instanceConfig` parameters are typed as `CreateAxiosDefaults` for compatibility with Axios v1.x types.
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.
fix Always ensure your installed `axios` version meets or exceeds the minimum peer dependency specified by your `middleware-axios` version. For `middleware-axios@2.1.x`, refer to its specific `package.json` for the exact `axios` peer dependency.
npm install middleware-axios
yarn add middleware-axios
pnpm add middleware-axios

This quickstart demonstrates how to create a `middleware-axios` instance, add a basic logging middleware that intercepts requests and responses, and then make a GET request using the wrapped instance.

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);