{"id":17801,"library":"middleware-axios","title":"Axios Middleware Layer","description":"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.","status":"active","version":"3.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/krutoo/middleware-axios","tags":["javascript","axios","fetch","api","typescript","middleware"],"install":[{"cmd":"npm install middleware-axios","lang":"bash","label":"npm"},{"cmd":"yarn add middleware-axios","lang":"bash","label":"yarn"},{"cmd":"pnpm add middleware-axios","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core HTTP client library extended by this package; required for all functionality.","package":"axios","optional":false}],"imports":[{"note":"Since v3.0.0, `middleware-axios` is a dual ESM/CJS package. While CommonJS `require` might work in some Node.js environments, explicit ESM `import` is recommended for modern applications, especially when `type: 'module'` is set in `package.json`.","wrong":"const { create } = require('middleware-axios');","symbol":"create","correct":"import { create } from 'middleware-axios';"},{"note":"TypeScript type for instances created by `create()`.","symbol":"MiddlewareAxiosInstance","correct":"import type { MiddlewareAxiosInstance } from 'middleware-axios';"},{"note":"TypeScript type for the middleware function itself, defining its signature: `(config, next, defaults) => Promise<void>`.","symbol":"AxiosMiddleware","correct":"import type { AxiosMiddleware } from 'middleware-axios';"}],"quickstart":{"code":"import { create } from 'middleware-axios';\nimport type { AxiosResponse } from 'axios';\n\n// Create a wrapped Axios instance, similar to a normal axios.create()\nconst api = create({\n  baseURL: 'https://jsonplaceholder.typicode.com',\n  timeout: 5000,\n});\n\n// Add a middleware to log requests and responses\napi.use(async (config, next, defaults) => {\n  console.log(`[REQUEST] ${config.method?.toUpperCase()} ${config.url}`);\n  console.log('  Base URL from defaults:', defaults.baseURL);\n\n  // Crucially, await next(config) passes control to the next middleware or Axios itself\n  await next(config);\n\n  // This code runs after the response is received\n  const response: AxiosResponse = await config.axiosData; // Access the response data from the config\n  console.log(`[RESPONSE] ${config.method?.toUpperCase()} ${config.url} - Status: ${response.status}`);\n  // console.log('  Response Data:', response.data);\n});\n\n// Use the wrapped instance like a normal Axios instance\napi.get('/todos/1')\n  .then(response => {\n    console.log('\\n--- API Call Successful ---');\n    console.log('Todo Title:', response.data.title);\n    console.log('Response Status:', response.status);\n  })\n  .catch(error => {\n    console.error('\\n--- API Call Failed ---');\n    if (error.response) {\n      console.error('Error Status:', error.response.status);\n      console.error('Error Data:', error.response.data);\n    } else if (error.request) {\n      console.error('No response received:', error.request);\n    } else {\n      console.error('Error message:', error.message);\n    }\n  });\n\n// You can also access the pure Axios instance if needed\n// console.log(api.axiosInstance);","lang":"typescript","description":"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."},"warnings":[{"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'`.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"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`.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always include `await next(config);` at the appropriate point in your middleware to ensure the request proceeds through the chain.","message":"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.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"For TypeScript users, ensure `instanceConfig` parameters are typed as `CreateAxiosDefaults` for compatibility with Axios v1.x types.","message":"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.","severity":"deprecated","affected_versions":">=2.1.6"},{"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.","message":"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.","severity":"breaking","affected_versions":">=2.1.2 <3.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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';`.","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).","error":"TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension \".ts\" for .../node_modules/middleware-axios/dist/index.js"},{"fix":"Always import symbols directly from the main package entry point: `import { create } from 'middleware-axios';`. Do not attempt to import from internal paths.","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.","error":"ERR_PACKAGE_PATH_NOT_EXPORTED (or similar import errors) from 'middleware-axios/some/path'"},{"fix":"Install or upgrade `axios` to a compatible version: `npm install axios@^1.7.4` or `yarn add axios@^1.7.4`.","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.","error":"Peer dependency 'axios@^1.7.4' must be installed"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}