{"id":17649,"library":"fetch-mw-oauth2","title":"Fetch Middleware for OAuth2","description":"fetch-mw-oauth2 is a JavaScript library designed to simplify OAuth2 integration with the standard `fetch` API, handling automatic token acquisition and refreshing. Currently at v3.3.1, it supports `authorization_code`, `password`, and `client_credentials` grant types, offers robust error handling, OpenID Connect `id_token` exposure, and includes support for token revocation (RFC 7009) and the `resource` parameter (RFC 8707). Since its v3.0.0 release, the library is ESM-only and has ceased support for Node.js 14 and 16. It primarily functions as a `fetch` wrapper or middleware. This package is in maintenance mode, as development has shifted to its successor, `@badgateway/oauth2-client`, which offers enhanced features and similar functionality.","status":"maintenance","version":"1.0.2","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/badgateway/fetch-mw-oauth2","tags":["javascript","fetch","oauth2","typescript"],"install":[{"cmd":"npm install fetch-mw-oauth2","lang":"bash","label":"npm"},{"cmd":"yarn add fetch-mw-oauth2","lang":"bash","label":"yarn"},{"cmd":"pnpm add fetch-mw-oauth2","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Since v3.0.0, this library is ESM-only. CommonJS `require()` is not supported.","wrong":"const { OAuth2 } = require('fetch-mw-oauth2')","symbol":"OAuth2","correct":"import { OAuth2 } from 'fetch-mw-oauth2'"},{"note":"TypeScript types are shipped with the package for improved development experience.","symbol":"OAuth2 types","correct":"import type { OAuth2Options, OAuth2Token } from 'fetch-mw-oauth2'"},{"note":"The primary interaction is creating an OAuth2 instance and then using its `fetch` method, which transparently handles token management.","symbol":"OAuth2 instance creation and usage","correct":"import { OAuth2 } from 'fetch-mw-oauth2';\n\nconst oauth2 = new OAuth2({\n  clientId: 'your-client-id',\n  clientSecret: process.env.OAUTH_CLIENT_SECRET ?? '', // Optional in some cases\n  tokenEndpoint: 'https://auth.example.org/token',\n}, {\n  accessToken: 'initial-access-token',\n  refreshToken: 'initial-refresh-token',\n});\n\nconst response = await oauth2.fetch('https://api.example.org/data');"}],"quickstart":{"code":"import { OAuth2 } from 'fetch-mw-oauth2';\n\nasync function authenticateAndFetch() {\n  // Configure OAuth2 for the client_credentials grant type\n  const oauth2 = new OAuth2({\n    grantType: 'client_credentials',\n    clientId: 'your-client-id',\n    clientSecret: process.env.OAUTH_CLIENT_SECRET ?? '', // Ensure this is loaded from environment variables\n    tokenEndpoint: 'https://auth.example.com/token',\n    scope: 'api:read api:write'\n  });\n\n  try {\n    // Use the wrapped fetch function which automatically handles Authorization headers and token refreshes\n    const response = await oauth2.fetch('https://api.example.com/protected-resource', {\n      method: 'GET',\n      headers: {\n        'Accept': 'application/json'\n      }\n    });\n\n    if (!response.ok) {\n      throw new Error(`HTTP error! status: ${response.status}`);\n    }\n\n    const data = await response.json();\n    console.log('Fetched data:', data);\n\n  } catch (error) {\n    console.error('Failed to fetch data with OAuth2:', error);\n  }\n}\n\nauthenticateAndFetch();","lang":"typescript","description":"This example demonstrates how to set up `fetch-mw-oauth2` using the client_credentials grant to automatically handle OAuth2 authentication and fetch a protected resource. It utilizes environment variables for sensitive data."},"warnings":[{"fix":"Migrate your project to use ES Modules `import` syntax and ensure you are running Node.js 18 or newer. Update your `package.json` to include `\"type\": \"module\"`.","message":"Version 3.0.0 introduced a full conversion to ES Modules (ESM) and dropped support for Node.js versions 14 and 16. Projects using CommonJS `require()` syntax or older Node.js runtimes will break.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"If experiencing issues, update to v3.1.0 or newer and consider setting `authorizationMethod` or switching to `client_secret_post` if your server has compatibility problems with strict Basic auth encoding.","message":"In v3.0.0, `client_id` and `client_secret` were changed to be strictly percent-encoded as per RFC 6749. This was a breaking change if your server was not strictly compliant with the OAuth2 spec and used special characters in secrets.","severity":"breaking","affected_versions":"3.0.0"},{"fix":"Review `README.md` for `authorizationMethod` options if your server requires strict Basic encoding. Otherwise, consider `client_secret_post` for better compatibility.","message":"Version 3.1.0 reverted the strict percent-encoding for the `Authorization: Basic` header due to interoperability problems with many real-world OAuth2 servers. The library now defaults to less strict encoding. If strict encoding is required, you must explicitly opt-in using the `authorizationMethod` option.","severity":"gotcha","affected_versions":">=3.1.0"},{"fix":"Migrate your application to use `@badgateway/oauth2-client` for continued feature development and support.","message":"This `fetch-mw-oauth2` package is in maintenance mode. The project has been renamed and superseded by `@badgateway/oauth2-client`, which offers a more full-featured and actively developed OAuth2 client. Users are strongly recommended to upgrade.","severity":"deprecated","affected_versions":"all"},{"fix":"Ensure you are using `fetch-mw-oauth2` v3.2.0 or newer for better browser compatibility with modern bundlers.","message":"Early v3 releases (v3.0.0, v3.1.0) had issues with browser builds, particularly for Vite and Next.js users, due to the ESM conversion. This was addressed in v3.2.0.","severity":"gotcha","affected_versions":"3.0.0 - 3.1.0"},{"fix":"Upgrade to v3.3.1 or newer to avoid potential issues with concurrent endpoint discovery requests.","message":"Version 3.3.1 fixed a race condition when multiple function calls were attempting OAuth2 endpoint discovery simultaneously.","severity":"gotcha","affected_versions":"<3.3.1"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Change `const { OAuth2 } = require('fetch-mw-oauth2');` to `import { OAuth2 } from 'fetch-mw-oauth2';` and ensure your `package.json` specifies `\"type\": \"module\"` if running in Node.js.","cause":"Attempting to use CommonJS `require()` syntax with `fetch-mw-oauth2` v3.0.0 or later in an ES Modules environment.","error":"ReferenceError: require is not defined"},{"fix":"If on v3.0.0, your server might not handle strict encoding; upgrade to v3.1.0+. If on v3.1.0+, your server might require strict encoding; explicitly set the `authorizationMethod` option, or prefer the `client_secret_post` method if your server supports it.","cause":"Interoperability issues with OAuth2 servers related to client_id/client_secret encoding in the `Authorization: Basic` header, particularly after the strict encoding change in v3.0.0 or the subsequent revert in v3.1.0.","error":"HTTP 400 Bad Request - Client Authentication Failed"},{"fix":"Update your `fetch-mw-oauth2` dependency to version 3.2.0 or newer to resolve browser build issues with modern bundlers.","cause":"Compatibility issues with browser bundling introduced during the ESM migration in `fetch-mw-oauth2` v3.x releases prior to v3.2.0.","error":"Build error (e.g., 'window is not defined', module resolution) when using Vite/Next.js"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}