@faremeter/fetch wraps the global fetch with automatic 402 payment handling. Unlike @faremeter/rides, you configure handlers and options explicitly.
Basic usage
wrap
fetch function that intercepts 402 responses and handles payment automatically.
WrapOpts
| Option | Type | Default | Description |
|---|---|---|---|
handlers | PaymentHandler[] | Required | Payment handlers to use for 402 responses. |
payerChooser | (execers: PaymentExecer[]) => Promise<PaymentExecer> | chooseFirstAvailable | Selects which payer to use when multiple can fulfill a requirement. |
phase1Fetch | typeof fetch | Same as phase2Fetch | Fetch function for the initial request (before payment). |
retryCount | number | 2 | Number of retries after payment (3 total attempts). |
initialRetryDelay | number | 100 | Starting backoff delay in milliseconds. |
returnPaymentFailure | boolean | false | Return the 402 response instead of throwing on payment failure. |
Phase 1 and Phase 2 fetch
The wrapper uses two fetch calls per payment:- Phase 1: The initial request that discovers the 402 response.
- Phase 2: The retry with the
X-PAYMENTheader attached.
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, thepayerChooser 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:
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
Usephase1Fetch to mock each phase independently:
Using fetch-like functions
Instead of staticResponse objects, pass functions for dynamic responses:
Further reading
- Rides SDK — The simpler high-level alternative.
- Payment Handlers — Setting up handlers for specific chains.
- Payment Handlers concept — How the handler plugin interface works.