Skip to main content
@faremeter/middleware adds x402 payment walls to your HTTP server. When a request hits a protected route, the middleware checks for a valid X-PAYMENT header. If missing, it returns a 402 response with payment requirements. If present, it verifies the payment through a facilitator and allows the request to proceed.
pnpm add @faremeter/middleware

How it works

  1. A request arrives at a protected endpoint.
  2. The middleware checks for an X-PAYMENT header.
  3. If missing: returns 402 Payment Required with the configured requirements.
  4. If present: sends the payment to the facilitator for verification and settlement.
  5. If the facilitator confirms: the request continues to your handler.
  6. If the facilitator rejects: returns an error response.

Framework support

FrameworkImport path
Express@faremeter/middleware/express
Hono@faremeter/middleware/hono
Custom@faremeter/middleware/common
The common module provides the core payment verification logic without framework bindings. Use it to integrate with any HTTP server.

Configuration

All middleware variants accept the same configuration:
import type { CommonMiddlewareArgs } from "@faremeter/middleware/common"

const config: CommonMiddlewareArgs = {
  facilitatorURL: "https://facilitator.corbits.dev",
  accepts: [
    // Payment requirements
  ],
  cacheConfig: {
    // Optional LRU cache settings
  },
}
OptionTypeDescription
facilitatorURLstringURL of the facilitator server.
acceptsx402PaymentRequirements[]Payment methods this endpoint accepts.
cacheConfigAgedLRUCacheOptsOptional cache configuration for facilitator responses.

Defining payment requirements

Use @faremeter/info to construct payment requirements:
import { xSolanaSettlement } from "@faremeter/info/solana"

const requirements = xSolanaSettlement({
  network: "devnet",
  payTo: "7xKXwxRPMo2sUAT5...",
  asset: "USDC",
  amount: "10000",
})
You can accept multiple payment methods by passing an array:
import { xSolanaSettlement } from "@faremeter/info/solana"
import { x402Exact } from "@faremeter/info/evm"

const accepts = [
  xSolanaSettlement({ network: "devnet", payTo: "7xKX...", asset: "USDC", amount: "10000" }),
  x402Exact({ network: "base-sepolia", payTo: "0x1234...", asset: "USDC", amount: "10000" }),
]

Caching

The middleware caches facilitator /accepts responses using an LRU cache with TTL. This reduces the number of requests to the facilitator. Cache configuration is optional.

Framework-specific guides

  • Express — Express middleware setup.
  • Hono — Hono middleware setup.
  • Facilitator — Running your own facilitator.