Skip to main content
@faremeter/fetch wraps the global fetch with automatic 402 payment handling. Unlike @faremeter/rides, you configure handlers and options explicitly.

Basic usage

wrap

Returns a new fetch function that intercepts 402 responses and handles payment automatically.

WrapOpts

Phase 1 and Phase 2 fetch

The wrapper uses two fetch calls per payment:
  1. Phase 1: The initial request that discovers the 402 response.
  2. Phase 2: The retry with the X-PAYMENT header attached.
By default, both use the same fetch function. You can provide a separate phase1Fetch if the initial request needs different configuration (e.g., different headers or timeouts).

Payer selection

When multiple handlers can fulfill a payment requirement, the payerChooser function selects one.
chooseFirstAvailable is the default. It picks the first handler that returns a PaymentExecer.

Custom payer chooser

Error handling

If all payment attempts fail, wrap throws a WrappedFetchError:
Alternatively, set returnPaymentFailure: true to receive the 402 response instead of throwing:

Retry behavior

Failed payment attempts are retried with exponential backoff:
  • Default: 2 retries (3 total attempts)
  • Backoff starts at 100ms and doubles each retry
  • Only retries when the 402 payment flow fails, not on other HTTP errors

Testing with mocks

@faremeter/fetch exports a mock namespace for testing payment flows without real network calls.

responseFeeder

responseFeeder(responses) takes an array of Response objects or fetch-like functions and returns a mock fetch. Each call to the returned function consumes the next item in the array.

Basic test pattern

Queue a 402 response followed by a success response to simulate a full payment flow:

Separate phase 1 and phase 2 mocks

Use phase1Fetch to mock each phase independently:

Using fetch-like functions

Instead of static Response objects, pass functions for dynamic responses:

Further reading