{"id":11475,"library":"oauth2-mock-server","title":"OAuth2 Mock Server","description":"oauth2-mock-server is a JavaScript/TypeScript library designed to provide a configurable OAuth2/OpenID Connect server for automated testing and development purposes. It allows developers to simulate an OAuth2 provider to issue verifiable access tokens without needing a full-fledged identity provider, making it ideal for unit and integration tests. The library supports various OAuth2 grant types, including Client Credentials, Resource Owner Password Credentials, Authorization Code (with PKCE), and Refresh Token grants. It also supports multiple JWK formats for signing tokens (RSA, EC, EdDSA). The current stable version is 8.2.2, with recent releases indicating an active maintenance and development cadence focused on dependency updates, minor feature additions, and bug fixes. A key differentiator is its programmatic control via event emitters for customizing server behavior, allowing for specific test scenarios, such as modifying token expiration or adding custom claims. It is explicitly not intended for production use due to a lack of full feature parity and security hardening.","status":"active","version":"8.2.2","language":"javascript","source_language":"en","source_url":"https://github.com/axa-group/oauth2-mock-server","tags":["javascript","oauth","oauth2","oauth 2","mock","fake","stub","server","cli","typescript"],"install":[{"cmd":"npm install oauth2-mock-server","lang":"bash","label":"npm"},{"cmd":"yarn add oauth2-mock-server","lang":"bash","label":"yarn"},{"cmd":"pnpm add oauth2-mock-server","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library switched to 'Universal' ESM in v8.0.0. While CommonJS `require()` is supported for specific Node.js versions (>=20.19, >=22.12), using `import` is the recommended and more robust approach for modern projects. Avoid `import OAuth2Server from '...'`. ","wrong":"const { OAuth2Server } = require('oauth2-mock-server');","symbol":"OAuth2Server","correct":"import { OAuth2Server } from 'oauth2-mock-server';"},{"note":"These classes were exported starting from v8.1.0. Adhere to ESM import rules since v8.0.0. The CommonJS `require()` pattern is subject to the same compatibility constraints as `OAuth2Server`.","wrong":"const { HttpServer } = require('oauth2-mock-server');","symbol":"HttpServer, OAuth2Service","correct":"import { HttpServer, OAuth2Service } from 'oauth2-mock-server';"},{"note":"This is a TypeScript type, use `import type` for proper type-only imports to prevent bundling issues and ensure type stripping. This type was exported starting from v8.2.0.","wrong":"import { TokenRequestIncomingMessage } from 'oauth2-mock-server';","symbol":"TokenRequestIncomingMessage","correct":"import type { TokenRequestIncomingMessage } from 'oauth2-mock-server';"}],"quickstart":{"code":"import { OAuth2Server } from 'oauth2-mock-server';\nimport axios from 'axios';\n\nasync function runMockServerExample() {\n  let server = new OAuth2Server();\n\n  // Generate a new RSA key and add it to the keystore\n  await server.issuer.keys.generate('RS256');\n\n  // Start the server on a free port, typically a high port for testing\n  // using 0 lets the OS pick a free port, then get the port from server.port\n  await server.start(0, 'localhost');\n  const port = server.port;\n  console.log('Mock OAuth2 Server started on port:', port);\n  console.log('Issuer URL:', server.issuer.url); // -> http://localhost:PORT\n\n  // --- Example: Build a token and use it ---\n  try {\n    let token = await server.issuer.buildToken();\n    console.log('Generated JWT:', token);\n\n    // Call a remote API with the token (this part won't actually work without a real API)\n    // For demonstration, let's just log what would happen\n    const exampleApiUrl = 'https://api.example.com/secure-data';\n    console.log(`Attempting to call ${exampleApiUrl} with Bearer token...`);\n    // In a real test, you'd point this to your application's protected endpoint\n    // and your application would validate this token against the mock server's JWKS endpoint.\n\n    // const response = await axios.get(exampleApiUrl, {\n    //   headers: {\n    //     authorization: `Bearer ${token}`,\n    //   },\n    // });\n    // console.log('API Response (simulated):', response.data);\n\n    // --- Example: Customize next token signing ---\n    server.once('beforeTokenSigning', (modifiedToken) => {\n      console.log('Modifying next token: Adding custom claim \"test_claim\".');\n      modifiedToken.payload.test_claim = 'custom_value';\n      modifiedToken.payload.exp = Math.floor(Date.now() / 1000) + 60; // Make it expire in 60s\n    });\n\n    let customToken = await server.issuer.buildToken();\n    console.log('Generated custom JWT:', customToken);\n    // You would typically decode and assert properties of customToken here in a test.\n\n  } catch (error) {\n    console.error('Error during mock server operation:', error);\n  } finally {\n    // Stop the server\n    console.log('Stopping mock server...');\n    await server.stop();\n    console.log('Mock server stopped.');\n  }\n}\n\nrunMockServerExample();","lang":"typescript","description":"This quickstart demonstrates how to initialize, configure, and operate the `oauth2-mock-server`. It shows how to generate cryptographic keys, start the server on a dynamic port, build JWTs programmatically, and apply customization hooks to modify token claims before signing, simulating an OAuth2 flow for testing purposes."},"warnings":[{"fix":"Upgrade your Node.js environment to a supported version (20.19+, 22.12+, or 24+).","message":"Node.js 18 is no longer supported since v8.0.0. The package now requires Node.js ^20.19 || ^22.12 || ^24.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Ensure your project is configured for ES modules (e.g., `'type': 'module'` in `package.json` and using `import` statements), or confirm your Node.js version is within the range that supports the CJS fallback.","message":"Version 8.0.0 switched to 'Universal' ESM. While CommonJS `require()` is technically supported for specific Node.js versions (20.19+, 22.12+), it is generally recommended to migrate your project to use ES modules (`import` statements) to avoid potential compatibility issues and leverage modern JavaScript module loading.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Do not deploy `oauth2-mock-server` in production environments. Use a robust, production-ready OAuth2/OIDC provider instead.","message":"This tool is explicitly *not* intended to be used as a production-grade OAuth 2 server. It lacks many features and security hardening required for a proper implementation and should only be used for development or testing purposes.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Call `await server.issuer.keys.generate('RS256')` (or another supported algorithm) or `await server.issuer.keys.add(yourJwk)` after initializing `OAuth2Server` and before starting the server or building tokens.","message":"Before the mock server can issue tokens, you must explicitly generate or add cryptographic keys to its keystore. Failing to do so will result in runtime errors when attempting to build or sign tokens.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Update your Node.js version to ^20.19 || ^22.12 || ^24, or configure your project to use ES Modules by adding `'type': 'module'` to your `package.json` and using `import` statements.","cause":"Attempting to `require()` the `oauth2-mock-server` package in a CommonJS context on an unsupported Node.js version or when the project's module configuration conflicts with its 'Universal' ESM design.","error":"ERR_REQUIRE_ESM: require() of ES Module ... not supported."},{"fix":"Choose an alternative port for `server.start(port, 'localhost')`, or set the port to `0` to have the operating system automatically assign a free port (e.g., `await server.start(0, 'localhost')`). Ensure previous instances of the server are properly stopped.","cause":"The specified port (e.g., 8080) that you are trying to start the `OAuth2Server` on is already being used by another process on your system.","error":"Error: listen EADDRINUSE: address already in use :::8080"},{"fix":"Before making requests to token endpoints or programmatically building tokens, ensure you call `await server.issuer.keys.generate('RS256')` or `await server.issuer.keys.add(yourJwk)` to populate the server's keystore.","cause":"The `OAuth2Server` instance requires at least one cryptographic key (JWK) to sign tokens, but no keys have been provided or generated.","error":"Error: No signing keys available. Generate one with server.issuer.keys.generate() or add one with server.issuer.keys.add()."}],"ecosystem":"npm"}