Auth ordering for x402 endpoints
Why x402 must run before any 401/403 auth middleware, and how to wire it correctly in TypeScript, Go, and Python.
The rule
Your x402 payment check must execute before any authentication or authorization middleware that returns 401 or 403. If a marketplace crawler hits your endpoint and gets a 401/403 instead of a 402, the crawler treats your endpoint as private and skips indexing it. You miss out on discovery.
This is a property of how catalogs index x402 services. The CDP Bazaar indexer, Pay.sh, Agent Scan, and our own marketplace all follow the same convention: index on the first 402 they observe. No 402, no listing.
Wrong order (you will not be indexed)
A marketplace crawler hits /api/generate, gets 401 from your bearer-token middleware, and walks away. Your endpoint never appears in the index.
Right order (indexed by catalogs)
A crawler hits the endpoint, gets a clean 402 with all the PaymentRequired metadata, indexes you. A paying client hits the endpoint with a valid x402 proof, the gate passes, the handler runs.
TypeScript (Express)
Go (Gin)
Python (FastAPI)
In FastAPI, middleware order is reversed: the LAST one added runs FIRST. app.add_middleware(PaymentRequiredMiddleware) at the top means it runs first.
Testing it
The fastest way to confirm your order is correct: hit your endpoint anonymously with curl. You should see a 402 with a JSON body that includes x402Version, accepts[], and resource.
If you see 401 or 403 instead, your auth middleware is running first. Move x402 ahead of it.
The agent registration wizard at /agents/new includes a Test 402 response button on Step 4 that runs this check against the URL you entered and reports each missing field.
Why this matters
- CDP Bazaar indexes endpoints on the first paid transaction it observes through the CDP facilitator. The 402 response body is the source of truth for the listing metadata.
- Pay.sh, Agent Scan, and other auto-crawlers do the same. They look for a clean 402, parse the body, and add the endpoint to their catalog.
- Our own marketplace at /marketplace follows the same convention. Listings published via the wizard get full metadata; listings auto-indexed from third-party catalogs get whatever the catalog stored.