..
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00
2026-05-17 20:24:58 +03:00

x402-express Example Server

This is an example Express.js server that demonstrates how to use the x402-express middleware to implement paywall functionality in your API endpoints.

Prerequisites

Setup

  1. Copy .env-local to .env and add your Ethereum address to receive payments:
cp .env-local .env
  1. Install and build all packages from the typescript examples root:
cd ../../
pnpm install
pnpm build
cd servers/express
  1. Run the server
pnpm install
pnpm dev

Testing the Server

You can test the server using one of the example clients:

Using the Fetch Client

cd ../clients/fetch
# Ensure .env is setup
pnpm install
pnpm dev

Using the Axios Client

cd ../clients/axios
# Ensure .env is setup
pnpm install
pnpm dev

These clients will demonstrate how to:

  1. Make an initial request to get payment requirements
  2. Process the payment requirements
  3. Make a second request with the payment token

Example Endpoint

The server includes a single example endpoint at /weather that requires a payment of $0.001 to access. The endpoint returns a simple weather report.

Response Format

Payment Required (402)

{
  "error": "X-PAYMENT header is required",
  "paymentRequirements": {
    "scheme": "exact",
    "network": "base",
    "maxAmountRequired": "1000",
    "resource": "http://localhost:4021/weather",
    "description": "",
    "mimeType": "",
    "payTo": "0xYourAddress",
    "maxTimeoutSeconds": 60,
    "asset": "0x...",
    "outputSchema": null,
    "extra": null
  }
}

Successful Response

// Body
{
  "report": {
    "weather": "sunny",
    "temperature": 70
  }
}
// Headers
{
  "X-PAYMENT-RESPONSE": "..." // Encoded response object
}

Extending the Example

To add more paid endpoints, follow this pattern:

// First, configure the payment middleware with your routes
app.use(
  paymentMiddleware(
    payTo,
    {
      // Define your routes and their payment requirements
      "GET /your-endpoint": {
        price: "$0.10",
        network: "base-sepolia",
      },
      "/premium/*": {
        price: {
          amount: "100000",
          asset: {
            address: "0xabc",
            decimals: 18,
            eip712: {
              name: "WETH",
              version: "1",
            },
          },
        },
        network: "base-sepolia",
      },
    },
  ),
);

// Then define your routes as normal
app.get("/your-endpoint", (req, res) => {
  res.json({
    // Your response data
  });
});

app.get("/premium/content", (req, res) => {
  res.json({
    content: "This is premium content",
  });
});