Skip to main content
Protect your HTTP endpoints with x402 payments using middleware. The middleware enforces the x402 handshake, forwards payment requirements to a facilitator, inspects payment headers from clients, and handles settlement before allowing requests to proceed.

Prerequisites

  • Node.js and npm installed
  • A SKALE Chain endpoint
  • Understanding of x402 protocol
  • A facilitator service (see Run a Facilitator)

Overview

When a client reaches a paywalled endpoint, the middleware:
  1. Returns a 402 Payment Required response with payment requirements if the incoming request lacks a valid payment header
  2. When a payment header is present, forwards it to the facilitator’s /verify and /settle endpoints
  3. If settlement succeeds, the request continues; otherwise another 402 is returned

Environment Setup

Create a .env file with the following variables:

Implementation

Step 1: Install Dependencies

Step 2: Create the Server

Step 3: Run the Server

Multiple Protected Routes

Add multiple routes with different pricing:

Testing Your Server

Once your server is running, you can test it:
The protected endpoint will return a 402 Payment Required response with payment requirements that a client can use to make a payment.

Error Handling

  • Invalid facilitator responses throw an exception (HTTP 500)
  • When settlement fails, the middleware returns a 402 status with error details
  • Missing configuration returns a 503 Service Unavailable

Resources