{"id":12859,"library":"axios-mock-server","title":"Axios Mock Server","description":"axios-mock-server is a development dependency designed to provide a RESTful mock server that integrates directly with Axios, removing the need for a separate backend server during client-side development and testing. It enables developers to define API endpoints as JavaScript or TypeScript files, utilizing an auto-routing mechanism that mirrors Nuxt.js's file-system-based routing. This library facilitates mocking HTTP requests made via Axios in both browser (SPA) and Node.js environments. The current stable version is 0.19.1, with a consistent cadence of patch and minor releases focusing on bug fixes, dependency updates, and feature enhancements. Its key differentiators include its serverless nature, intuitive file-based routing for mock definitions, and robust TypeScript support, making it an efficient tool for API mocking.","status":"active","version":"0.19.1","language":"javascript","source_language":"en","source_url":"https://github.com/solufa/axios-mock-server","tags":["javascript","axios","test","mock"],"install":[{"cmd":"npm install axios-mock-server","lang":"bash","label":"npm"},{"cmd":"yarn add axios-mock-server","lang":"bash","label":"yarn"},{"cmd":"pnpm add axios-mock-server","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This library mocks requests made by axios; it's a peer dependency for the consuming application.","package":"axios","optional":false}],"imports":[{"note":"Used to create a mock instance and connect it to a specific Axios instance.","wrong":"const { factory } = require('axios-mock-server');","symbol":"factory","correct":"import { factory } from 'axios-mock-server';"},{"note":"Main entry point for connecting a compiled API definition to an Axios instance, as demonstrated in the official tutorial. This is a named export.","wrong":"import connectToAxios from 'axios-mock-server';","symbol":"connectToAxios","correct":"import { connectToAxios } from 'axios-mock-server';"},{"note":"Used for global request interception in Node.js environments. A separate '/browser' entry point exists for browser-specific usage. This is similar to Mock Service Worker (MSW) setup for global intercepts. Ensure you import from the correct environment subpath.","wrong":"import { setupWorker } from 'axios-mock-server';","symbol":"setupWorker","correct":"import { setupWorker } from 'axios-mock-server/node';"}],"quickstart":{"code":"// 1. Install dependencies (in your project root)\n// npm install axios axios-mock-server --save-dev\n\n// 2. Create a mock directory and define your API endpoint\n// file: mocks/users/_userId.js\nconst users = [{ id: 0, name: 'foo' }, { id: 1, name: 'bar' }];\n\nmodule.exports = {\n  get({ values }) {\n    // values.userId is dynamically parsed from the URL, e.g., /users/0\n    const userId = Number(values.userId);\n    const user = users.find(u => u.id === userId);\n    if (user) {\n      return [200, user];\n    }\n    return [404, { message: 'User not found' }];\n  },\n  post({ data }) {\n    // Simulate adding a new user\n    if (!data || !data.name) return [400, { message: 'Name is required' }];\n    const newUser = { id: users.length, name: data.name };\n    users.push(newUser);\n    return [201, newUser];\n  }\n};\n\n// 3. Build the mock API (run this command in your terminal)\n// npx axios-mock-server build --input mocks --output dist/mock.js\n\n// 4. In your application file (e.g., src/main.js), import and use the mock\nimport axios from 'axios';\nimport { connectToAxios } from 'axios-mock-server';\nimport api from '../dist/mock'; // Adjust path based on your project structure\n\n// Create an Axios instance\nconst client = axios.create({ baseURL: 'http://localhost:8080' }); // Example base URL\n\n// Connect the mock API to the Axios instance\nconnectToAxios(api, client);\n\nasync function fetchData() {\n  console.log('Attempting to fetch user 0...');\n  try {\n    const response = await client.get('/users/0');\n    console.log('GET /users/0 response:', response.data); // Expected: { id: 0, name: 'foo' }\n  } catch (error) {\n    console.error('Error fetching user 0:', error.response?.data || error.message);\n  }\n\n  console.log('\\nAttempting to post a new user...');\n  try {\n    const response = await client.post('/users', { name: 'baz' });\n    console.log('POST /users response:', response.data); // Expected: { id: 2, name: 'baz' }\n  } catch (error) {\n    console.error('Error posting new user:', error.response?.data || error.message);\n  }\n\n  console.log('\\nAttempting to fetch a non-existent user 99...');\n  try {\n    const response = await client.get('/users/99');\n    console.log('GET /users/99 response:', response.data);\n  } catch (error) {\n    console.error('Error fetching user 99 (expected 404):', error.response?.data || error.message);\n  }\n}\n\nfetchData();","lang":"javascript","description":"This quickstart demonstrates how to define a mock API endpoint, build it using the CLI, and then connect it to an Axios instance in your application to intercept and respond to HTTP requests."},"warnings":[{"fix":"Always return `[statusCode, data]` from your mock methods. For TypeScript, use `return [200, data] as MockResponse;`","message":"When defining mock API endpoints, ensure you return responses as `[statusCode, data]` arrays. Directly returning `data` or other formats without the status code will lead to unexpected behavior. For TypeScript, explicitly asserting the `MockResponse` type for asynchronous responses is often necessary.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Immediately audit your `node_modules` and lock files for `axios@1.14.1` or `axios@0.30.4` and the `plain-crypto-js` dependency. Pin `axios` to safe versions (`axios@1.14.0` or `axios@0.30.3`), update all credentials, and rebuild from a known-good state. Use `npm ci --ignore-scripts` in CI/CD.","message":"The `axios` package itself experienced a critical supply chain attack on March 31, 2026, where malicious versions `axios@1.14.1` and `axios@0.30.4` were published. These versions contained a Remote Access Trojan. While `axios-mock-server` is a distinct package, any project using affected `axios` versions is at risk.","severity":"breaking","affected_versions":"axios@1.14.1, axios@0.30.4"},{"fix":"Follow the tutorial's `build` step: `npx axios-mock-server build --input mocks --output dist/mock.js` and then `import api from '../dist/mock';` in your application.","message":"The mock definition files (e.g., `mocks/users/_userId.js`) typically use CommonJS `module.exports`, while client-side application code usually uses ESM `import` statements. This requires a build step for the mock definitions (e.g., `npx axios-mock-server build`) to generate a compatible module that can be imported by your application.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Upgrade `axios-mock-server` to version `0.19.1` or newer to ensure these transitive dependencies are patched.","message":"Security vulnerability detected in `ini` dependency (from 1.3.5 to 1.3.7) and `acorn` (from 6.4.0 to 6.4.1) in older versions of `axios-mock-server`. While these are dev dependencies for the mock server itself, keeping dependencies up-to-date is crucial for overall project security.","severity":"deprecated","affected_versions":"<0.19.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Assert the response as `MockResponse` or ensure the response is an object. Example: `return [200, data] as MockResponse;` or if returning an object, ensure it's compatible with `MockResponse`.","cause":"In TypeScript, when returning asynchronous responses from mock methods, the inferred type may not match the `MockMethods` expectation if you return an array directly.","error":"The expected type comes from property 'get' which is declared here on type 'MockMethods' error in TypeScript"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":null}