Overview
An agent that calls a paid API can’t fill a signup form or enter a card. x402 gives it another way: the API answers402 Payment Required, the agent signs a USDC payment, and retries.
Raw x402 settles one on-chain payment per call. That is fine for a $1 report and ruinous for a $0.002 search: every call pays a settlement and waits for one, and nothing ties the calls to a customer, a plan or an invoice.
Lago puts prepaid credits between the two. The agent pays once to top up, then makes thousands of calls against its credits, off chain. Each call is metered as a usage event and priced by your Lago plan. When the credits run out, the next call gets a 402 again.
lago-x402 is the middleware that runs this in front of your API, for Express, Hono and Next.js. Payments settle through the Coinbase (x402) integration.
Premium feature, on request. x402 needs a premium license and the
x402_payments feature flag. Contact us to enable it.How it works
- No credits. The agent calls a gated route. The middleware asks Lago for a gate check, and Lago answers with a challenge. The agent gets a
402whosePAYMENT-REQUIREDheader offers a top-up in USDC on each network of your connection, plus a sign-in-with-x challenge. - Top-up. The agent signs the payment and retries with
PAYMENT-SIGNATURE. The middleware runs a fresh gate check, then forwards the payment to Lago, which verifies and settles it through the facilitator, creates the agent’s customer, subscription and wallet on its first purchase, and grants the credits. The call is served. - Served from credits. On later calls the agent signs in with
SIGN-IN-WITH-X, which proves it holds the address that paid. The official client signs in only after a402, so a call served from credits is a402then a200, with two gate checks. Lago passes the call while the wallet covers one more call. No chain activity. - Metered. After every served call, the middleware sends Lago one usage event with what the call consumed. Lago draws it from the agent’s wallet at your plan’s price.
- Empty again. When the credits no longer cover a call, the gate challenges, and the agent tops up again.
402 is a top-up request, not a price. It asks for your route’s top-up amount. What a call costs is set by your plan, and applied to the usage event after the call.
Every agent is a regular Lago customer. Its usage, wallet, invoices and payments show up in the app, the API and your webhooks like any other customer’s.
Set up Lago
1. Connect Coinbase
Create an x402 connection in Settings > Integrations > Coinbase. See Coinbase (x402) for the fields. For the middleware, two matter most:- Allowed origins must contain the public origin your API is called on, port included. Without it every sign-in is refused, and the middleware answers
503. - Auto-create customers must be on for agents Lago has never seen to top up. Off, an unknown paying address gets
403 buyer_not_recognized.
2. Create a billable metric per route
Asum aggregation on the field value, with no expression, not recurring. Each usage event carries the call’s units in properties.value: tokens, rows, searches.
3. Create a plan per route
The plan an agent is subscribed to on its first top-up. It must be:- Usage-only: no subscription fee, no fixed charges, no minimum commitment, no charge minimums. Lago refuses these with a
plan_*error. Charge minimums too: they come back asplan_not_usage_only, not as acharge_*code. - In USD.
- Invoiceable: a pay-in-advance charge must be invoiceable, or Lago refuses it with
charge_not_invoiceable. - Targeted: the charge on the route’s metric must accept target wallets, so usage drains the route’s wallet and nothing else.
4. Create an API key
If your organization restricts API keys with permissions, the key needsx402 write, event write and billable_metric read.
You don’t create customers, wallets or subscriptions. Lago creates them on an agent’s first top-up.
Install the middleware
>=22.12, with one of: Express 4.21+ or 5, Hono 4.6+ on @hono/node-server, or Next.js 16 on the Node runtime. The package is ESM, typed, and has one runtime dependency, @x402/core.
Configure your routes
One config for the whole app. Each route has a name and the Lago objects that bill it.lago.ts
createLagoX402 validates the config, then checks every route against Lago at boot: the metric’s shape and a gate check. It refuses to start on a route Lago can’t bill, with a LagoX402ConfigError naming every refused route. An unreachable Lago is not a refusal: that route answers 503 and its check retries in the background.
Attach the gate to a route
The middleware never matches paths. You attach it to each paid route through your framework’s router.- Express
- Hono
- Next.js
server.ts
Report usage
The handler reports how many units of the route’s metric the call consumed:
The middleware sends one
POST /events per served call, after the response has gone out, never batched:
- A response with a status of 400 or more sends no event.
transaction_idandtimestampare fixed when the call is served and reused on every retry, so Lago counts the event once.- A missing, negative or non-numeric usage bills
fallbackUsageand reportsusage.extract. So doNaN,Infinity, a usage read that throws, and a numeric string such as"5": only numbers count.0is valid and sends"0". Alert on it: a handler that forgets to report usage bills every call at the fallback, and nothing else looks wrong.
The gate check
Every request to a gated route costs one gate check against Lago, before your handler runs. Lago serves a signed-in agent when:LAGO_WALLET_ONGOING_BALANCE_REFRESH_INTERVAL_SECONDS). Between two refreshes, a per-wallet counter reserves estimatedCallCostCents for each call it checks, this one included, so concurrent calls can’t all spend the same balance. With 900 free and an estimate of 300, the third concurrent call is refused even though 300 is still free. Each refresh replaces the reservations with the metered usage.
The gate is a guardrail, not a ledger. A wallet can go slightly negative:
- The estimate is exact only when every call costs the same. With a token metric, a large call can cost more than the estimate.
- Calls in flight when a refresh runs are counted late.
- Credits offset the whole invoice, including anything outside the gated route.
estimatedCallCostCents close to the real cost of a typical call. Too low, and agents overdraw more. Too high, and the gate refuses agents that still have credits for one call.
What the agent gets
Refusals are JSON,{"error": "<code>"}, with Cache-Control: no-store.
The gate fails closed. When the middleware can’t get a clear answer from Lago, the call is not served. It never answers
402 after a payment may have settled, so an agent is never asked to pay twice for the same call.
Replay protection
Everything in a settled payment can be read from the chain, so a payment alone can’t prove who sent it. The middleware sends Lago a randomidempotency_key with each paid request, and Lago answers a recorded payment only under that key. A settled payment presented again, by the agent or anyone else, gets 409 payment_already_settled. A payment serves exactly one request. Its credits serve the rest, through sign-in.
Errors and observability
Every failure goes toonError(err, where) and to console.warn, so nothing fails silently:
Messages carry route names, endpoint names, statuses and Lago error codes only. Never the API key, a payment or sign-in header, or a response body.
For agent builders
An API behindlago-x402 speaks standard x402 v2 with the sign-in-with-x extension. With the official TypeScript client:
agent.ts
- Sign in. Without the sign-in-with-x extension, every call is a new top-up.
- Raise the spend cap when the top-up is above $1.
- Allow about 45 seconds, plus the handler’s time, on the request that carries the payment.
- Never resend a payment after
503 payment_pending. WaitRetry-After, then call again and sign in. Once Lago confirms the payment, the call is served from its credits. - Python agents need
httpx. The syncrequestsclient can’t run the extension’s hooks.
Bazaar discovery
The x402 Bazaar is the Coinbase facilitator’s catalogue of paid resources. Agents search it to find APIs. A route can be listed:serviceName over 32 characters, more than 5 tags, a description over 500 characters, an invalid iconUrl.
Limits
- Node only. Express, Hono on
@hono/node-server, and the Next.js Node runtime. No edge runtimes. A Python middleware is not available yet. - x402 v2 only. USDC on Base and Solana, through the Coinbase facilitator.
- No streaming metering. One usage value per call, read once the response has gone out.
- Every request costs a gate check. Nothing is cached, by design. A call served from credits usually costs two, since the client signs in only after a
402, and a paid retry runs one before the credit purchase. Put a rate limiter per client in front of the gate: a flood of anonymous requests costs a gate check each, and on Solana connections it can exhaust the facilitator’s rate limit. - Paid requests take about 45 seconds plus your handler’s time. A 5-second gate check runs first, then the credit purchase with its own 45-second budget, then your handler. Agents’ HTTP clients, proxies, load balancers and platform timeouts must allow it.
- Usage events live in memory. Events still queued are lost if the process crashes, is killed, or
close()times out. Those calls stay unbilled. Awaitx402.close()on shutdown. - Long paths break sign-in. A path that pushes the sign-in URI past 512 characters makes sign-in fail with
401. - Next.js bills clients that left.
after()runs even when the client disconnected first. Express and Hono bill only once the headers were sent. - Keep clocks in sync. Lago dates each call by your server’s clock. Keep it NTP-synced.