x402 HTTPtslive · you pay per call

Protect an Express agent with x402

A minimal Express server whose /ask endpoint is gated by the Nevermined payment middleware — one line per route.

http-simple-agent-ts/
1 What you'll learn

The smallest possible paid HTTP agent: add a paywall to one route.

  • Protect an Express endpoint with paymentMiddleware from @nevermined-io/payments/express
  • Return 402 with the payment-required envelope, verify the payment-signature, settle on success
  • Generate an x402 access token on the client with the SDK and retry the call
  • Optionally track OpenAI cost per call with Nevermined observability
2 How it works

The client calls /ask with no token and gets 402 Payment Required, carrying the payment-required header. It mints an x402 token with the SDK, retries with the payment-signature header, and the agent verifies, runs, and settles (burns credits) before returning 200 with a payment-response receipt.

POST /askno token
402payment-required
sign + retrypayment-signature
200payment-response
3 Under the hood
ExpressTypeScript@nevermined-io/payments/expressOpenAI
# one line gates the route
import { paymentMiddleware } from '@nevermined-io/payments/express'

app.use(paymentMiddleware(payments, {
  'POST /ask': { planId: PLAN_ID, credits: 1 }
}))
src/agent.tsExpress server with a payment-protected /ask endpoint
src/agent-observability.tssame agent, with Nevermined observability tracking OpenAI cost
src/client.tsdemo client showing the full x402 payment flow
4 See it run
Protect an Express agent with x402

Sandbox agent — real payment round-trips (402 → authorize → settle) with a per-session credit balance, no external service and no real money. The buyer mints an x402 access token via the SDK and sends it as `payment-signature`; the sandbox runs that round-trip locally. See the README to point this at a hosted instance of the agent.