Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
Back to tool/Back to issues
#3564·x402

[Bug]: Axios skips onPaymentResponse hooks when paid requests return HTTP 400/500

Author: sunruize93-cmykCreated Sep 23, 2026Updated Sep 24, 2026

What happened

With wrapAxiosWithPayment and Axios's default status validation, a paid follow-up request returning HTTP 400 or 500 rejects without invoking the registered onPaymentResponse hook, even when the response includes a decodable PAYMENT-RESPONSE header.

The same client configuration using wrapFetchWithPayment invokes the hook for these responses.

Paid follow-up HTTP status Axios hook calls Fetch hook calls
200 1 1
402 1 1
400 0 1
500 0 1

This prevents hook-based response logging/state handling from observing these completed payment-bearing requests. Axios rejecting an HTTP error is expected; skipping the registered lifecycle hook is the issue.

What I expected

The existing onPaymentResponse hook should receive completed paid HTTP error responses and their payment response context, consistently with the Fetch wrapper and the lifecycle hook documentation.

When the hook does not request recovery, Axios should still reject HTTP 400/500 according to its configured status validation. This is not a request to silently convert HTTP errors into success or retry them automatically.

Steps to reproduce

  1. In an empty directory, install:
    bash
    npm install @x402/[email protected] @x402/[email protected] @x402/[email protected] [email protected]
  2. Save the following script as repro.mjs and run node repro.mjs.
  3. Observe the table above and the final failing assertion. For Axios 400/500, the response status is available on the error, but the hook was never called.
Self-contained reproduction (local HTTP only, no wallet or real payments)
javascript
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createServer } from 'node:http';
import axios from 'axios';
import { x402Client } from '@x402/core/client';
import { wrapAxiosWithPayment } from '@x402/axios';
import { wrapFetchWithPayment } from '@x402/fetch';

const encode = value => Buffer.from(JSON.stringify(value)).toString('base64');
const requirements = { scheme: 'exact', network: 'eip155:84532', amount: '1', asset: '0x0000000000000000000000000000000000000001', payTo: '0x0000000000000000000000000000000000000002', maxTimeoutSeconds: 60, extra: {} };
const server = createServer((req, res) => {
  req.resume();
  const paidStatus = Number(req.url.slice(1));
  if (!req.headers['payment-signature']) {
    const declaration = { x402Version: 2, resource: { url: `http://${req.headers.host}${req.url}`, description: 'local test', mimeType: 'application/json' }, accepts: [requirements] };
    res.writeHead(402, { 'PAYMENT-REQUIRED': encode(declaration) });
  } else {
    res.writeHead(paidStatus, { 'PAYMENT-RESPONSE': encode({ success: false, errorReason: 'local_test_failure', network: requirements.network, transaction: '' }) });
  }
  res.end('{}');
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const base = `http://127.0.0.1:${server.address().port}`;
const results = [];
try {
  for (const transport of ['axios', 'fetch']) {
    for (const status of [200, 402, 400, 500]) {
      const observed = [];
      const client = new x402Client().register(requirements.network, {
        scheme: 'exact',
        createPaymentPayload: async x402Version => ({ x402Version, payload: { testOnly: true } }),
      });
      client.setSpendControls({ allowedAssets: [{ network: requirements.network, asset: requirements.asset, maxAmountPerPayment: '1' }] });
      client.onPaymentResponse(async ctx => { observed.push(ctx.settleResponse?.errorReason); });
      let actualStatus;
      try {
        const response = transport === 'axios'
          ? await wrapAxiosWithPayment(axios.create({ proxy: false }), client).get(`${base}/${status}`)
          : await wrapFetchWithPayment(fetch, client)(`${base}/${status}`);
        actualStatus = response.status;
        if (transport === 'fetch') await response.text();
      } catch (error) {
        console.log(transport, status, error.message);
        actualStatus = error.response?.status;
      }
      results.push({ transport, status: actualStatus, hookCalls: observed.length, reason: observed[0] });
    }
  }
} finally {
  server.closeAllConnections();
  await new Promise(resolve => server.close(resolve));
}
console.table(results);
assert.ok(results.every(row => row.hookCalls === 1 && row.reason === 'local_test_failure'), 'every completed paid HTTP response should reach onPaymentResponse');

Additional context

  • Tested on Node.js 22.22.3, macOS, with the published versions above.
  • The server and payment payload are fixtures. No facilitator, chain RPC, or funds are involved. The fixture's settlement error is intentional; this checks response-hook delivery, not actual settlement.
  • Runtime results above are from published packages. I also checked current main at 80c2fa49ef92af6f36c30e4df866f2ddd1e90e91; the relevant behavior remains present.
  • This reproduction checks hook invocation and settlement-response context; it does not independently test hook-driven recovery.
  • I would be happy to contribute a focused fix and regression tests if this behavior is confirmed.
  • Investigation and reproduction were AI-assisted; the script was executed locally.

Source: x402-foundation/x402

View original on GitHubView discussion on GitHub