{"id":16444,"library":"mocker-api","title":"Mocker API for RESTful Development","description":"mocker-api is a development utility designed for mocking RESTful APIs, facilitating frontend development by enabling work independent of a live backend. It supports flexible integration as middleware with common development servers like Express.js and webpack-dev-server. The current stable version is 4.0.0, which has updated its Node.js requirement to `>=16.0.0`. The library features hot module replacement for mock files, allows quick API configuration via JSON or JavaScript files, and provides simple mock API proxying. It also offers first-class TypeScript type definitions for an enhanced developer experience. Unlike some other mocking solutions, `mocker-api` can be used independently without relying on a full webpack setup, making it versatile for various project types, including Create React App. It helps streamline development workflows by providing predictable API responses during the early stages of a project.","status":"active","version":"4.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/jaywcjlove/mocker-api","tags":["javascript","express","webpack-dev-server","webpack-api-mocker","webpack","mocker-api","mock","mocker","api","typescript"],"install":[{"cmd":"npm install mocker-api","lang":"bash","label":"npm"},{"cmd":"yarn add mocker-api","lang":"bash","label":"yarn"},{"cmd":"pnpm add mocker-api","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Commonly used as middleware for Express.js applications to serve mock APIs.","package":"express","optional":true},{"reason":"Often integrated into webpack configurations to provide API mocking during development.","package":"webpack-dev-server","optional":true}],"imports":[{"note":"Since v3, `mocker-api` primarily uses ESM imports. While `require` might work with transpilation, direct ESM import is recommended. CommonJS usage can lead to errors like 'default is not a function' in certain environments.","wrong":"const apiMocker = require('mocker-api');","symbol":"apiMocker","correct":"import apiMocker from 'mocker-api';"},{"note":"Imports for type definitions, such as the options object passed to the main `apiMocker` function, should use `import type` to ensure they are stripped at compile time.","symbol":"MockerAPIOptions","correct":"import type { MockerAPIOptions } from 'mocker-api';"},{"note":"Mock definitions are typically objects or functions exported from user-defined files, which are then loaded by `mocker-api`. The library expects a specific structure for these definitions (e.g., path strings mapped to data or handler functions).","symbol":"MockDefinition","correct":"// In mocker/index.ts:\ninterface User { id: number; name: string; }\nconst mocks: Record<string, User | User[]> = {\n  'GET /api/users': [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }],\n  'GET /api/user/:id': (req, res) => {\n    const id = parseInt(req.params.id, 10);\n    if (id === 1) return res.json({ id: 1, name: 'Alice' });\n    if (id === 2) return res.json({ id: 2, name: 'Bob' });\n    res.status(404).json({ message: 'User not found' });\n  },\n};\nexport default mocks;"}],"quickstart":{"code":"import express from 'express';\nimport path from 'path';\nimport apiMocker from 'mocker-api';\n\ninterface User { id: number; name: string; email: string; }\n\n// --- Create 'mocker/index.ts' file in your project root or source directory ---\n// const mocks = {\n//   'GET /api/users': [\n//     { id: 1, name: 'Alice', email: 'alice@example.com' },\n//     { id: 2, name: 'Bob', email: 'bob@example.com' },\n//   ],\n//   'POST /api/users': (req, res) => {\n//     const newUser: User = { id: Date.now(), ...req.body };\n//     console.log('New user created:', newUser);\n//     res.status(201).json(newUser);\n//   },\n//   'GET /api/user/:id': (req, res) => {\n//     const userId = parseInt(req.params.id, 10);\n//     const users: User[] = [\n//       { id: 1, name: 'Alice', email: 'alice@example.com' },\n//       { id: 2, name: 'Bob', email: 'bob@example.com' },\n//     ];\n//     const user = users.find(u => u.id === userId);\n//     if (user) {\n//       res.json(user);\n//     } else {\n//       res.status(404).json({ message: `User with ID ${userId} not found` });\n//     }\n//   },\n//   'GET /api/posts': [\n//     { id: 101, title: 'First Post' },\n//     { id: 102, title: 'Second Post' },\n//   ],\n//   // Example of proxying specific requests: anything starting with /github/\n//   'GET /github/*': 'https://api.github.com/',\n// };\n// export default mocks;\n// -----------------------------------------------------------------------------\n\nconst app = express();\nconst port = process.env.PORT ?? 8080; // Use process.env.PORT or default to 8080\n\n// Enable JSON body parsing for POST/PUT requests (essential for 'POST /api/users' mock)\napp.use(express.json());\n\n// Resolve the path to your mock definition file.\n// Ensure 'mocker/index.js' or 'mocker/index.ts' exists and exports the mock definitions.\nconst mockDirectory = path.resolve(__dirname, 'mocker/index.js'); // Adjust for your build output\n\napiMocker(app, mockDirectory, {\n  // Optional: Enable proxying for unmocked routes. Requests matching '/api/(.*)'\n  // that are not explicitly mocked will be forwarded to JSONPlaceholder.\n  proxy: {\n    '/api/(.*)': 'https://jsonplaceholder.typicode.com/', \n  },\n  // Set changeHost to true when proxying to external hosts like GitHub API to avoid CORS issues.\n  changeHost: true,\n  // Optional: Simulate network delay for all mock responses in milliseconds.\n  delay: 500,\n});\n\napp.listen(port, () => {\n  console.log(`Mock API Server is running at http://localhost:${port}`);\n  console.log('Try visiting:');\n  console.log(`- http://localhost:${port}/api/users (mocked data from 'mocker/index.ts')`);\n  console.log(`- http://localhost:${port}/api/user/1 (mocked data from 'mocker/index.ts')`);\n  console.log(`- http://localhost:${port}/api/todos/1 (proxied to JSONPlaceholder)`);\n  console.log(`- http://localhost:${port}/github/users/jaywcjlove (proxied to GitHub API)`);\n});","lang":"typescript","description":"This quickstart sets up a basic Express server and integrates `mocker-api` as middleware. It demonstrates defining mock API routes in a separate file (e.g., `mocker/index.ts`), handling both static JSON responses and dynamic request/response logic, and includes an example of proxying unmocked requests to a real API like JSONPlaceholder or GitHub for a seamless development experience."},"warnings":[{"fix":"Upgrade your Node.js environment to version 16.0.0 or higher. For NVM users, use `nvm install 16` and `nvm use 16`.","message":"Version 4.0.0 introduces a stricter Node.js engine requirement. Projects running on Node.js versions older than 16.0.0 will encounter compatibility issues due to updated runtime dependencies and features.","severity":"breaking","affected_versions":"4.0.0"},{"fix":"Review the official changelog for specific breaking changes related to API signatures, configuration options, and mock definition formats. Update your mock files and `apiMocker` configuration accordingly. Consider a staged upgrade via v3.x latest to identify deprecation warnings first.","message":"Upgrading from `mocker-api` v2.x or v3.x to v4.0.0 may involve significant breaking changes due to potential API refactorings, option removals, or changes in internal concepts. Many libraries use major versions to remove deprecated 'legacy' APIs introduced in previous minors.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Place `apiMocker` middleware early in your Express application's middleware chain, typically before your application's main route definitions, but after any body parsers like `express.json()` or `express.urlencoded()`.","message":"When using `mocker-api` with Express, the order of middleware is crucial. If `mocker-api` middleware is placed after other route handlers, those handlers might intercept requests before the mocker has a chance to respond, leading to unexpected behavior or unmocked responses. Conversely, if proxying is enabled, ensure `mocker-api` is positioned correctly to allow proxies to function without conflicting with other static file servers.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"For complex scenarios, consider breaking down mock definitions into smaller, focused files or using external utility functions within your mock handlers. Utilize `path.resolve` for robust file path resolution. Keep mock logic concise and readable, prioritizing clarity of API responses.","message":"Defining complex mock logic directly within a single large mock file can become unmanageable. While `mocker-api` supports dynamic functions as mock responses, over-complicating these can obscure the API contract and make debugging difficult. Also, ensure mock file paths are correctly resolved, especially in different build environments.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure you are using ESM `import apiMocker from 'mocker-api';` syntax. If using CommonJS, check your `tsconfig.json` (for TypeScript) or Babel configuration to ensure correct module resolution and transpilation for ESM packages. For Node.js, ensure your environment supports ESM or use a tool like `ts-node` with appropriate settings.","cause":"This error typically occurs when attempting to import an ESM module using a CommonJS `require()` syntax, or when a bundler incorrectly transpiles ESM to CJS, expecting a `.default` property on the imported module.","error":"TypeError: (0 , _mockerApi.default) is not a function"},{"fix":"Install `express` as a dependency in your project: `npm install express` or `yarn add express`.","cause":"The `express` package is a common dependency for `mocker-api` usage, especially when integrating it into an Express.js application, but it might be a peer dependency or simply an assumed external dependency, not automatically installed by `mocker-api` itself.","error":"Error: Cannot find module 'express'"},{"fix":"Verify that the path provided to `apiMocker` (e.g., `path.resolve(__dirname, 'mocker/index.js')`) correctly points to an existing file, and that the file exports either an object of mock definitions or a function that returns such an object. Ensure the file is accessible and free of syntax errors.","cause":"The `apiMocker` function expects a valid path to a JavaScript/TypeScript file that exports an object or a function containing your mock definitions, or it expects a direct mock object. This error indicates the file was not found, or its export was not in the expected format.","error":"Error: Mock file path '/path/to/nonexistent/mocker/index.js' is invalid or mock data is not an an object or function."},{"fix":"Change the `port` variable in your `app.listen()` call to an available port (e.g., 3000, 8000, 9000). You can also use tools like `lsof -i :8080` (macOS/Linux) or `netstat -ano | findstr :8080` (Windows) to identify and terminate the process using the port, if appropriate.","cause":"This error occurs when the port specified for the Express server (e.g., 8080) is already being used by another application or process on your system.","error":"Error: EADDRINUSE: address already in use :::8080"}],"ecosystem":"npm"}