Axios Middleware Service

0.4.0 · abandoned · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `axios-middleware` with an Axios instance, register request and response interceptors, and then make API calls, showcasing both success and error handling.

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

view raw JSON →