Skip to main content
This guide shows how to create paid APIs using the x402-hono middleware for Base Sepolia testnet. You’ll learn to add payment requirements to Hono routes with USD-based pricing and automatic service discovery.

Prerequisites

Ensure you have Node.js and npm installed on your machine and a funded wallet with USDC on Base Sepolia testnet.
  • Install Node.js (npm comes with Node.js)
  • A wallet address with USDC tokens on Base Sepolia testnet
  • Get test USDC from the Circle Faucet (select Base Sepolia)

Step 1: Create a New Project

Initialize a new project using the official Hono template:
npm create hono@latest x402-hono-seller
Select the nodejs template when prompted. Then navigate to your project:
cd x402-hono-seller
npm install
Install the x402-hono middleware:
npm install x402-hono

Step 2: Configure Your Receiving Address

Create a .env file with your wallet address:
RECEIVING_ADDRESS=0x_your_wallet_address_here

Step 3: Create Your Paid API

Replace the contents of src/index.ts with a simple string reversal service:
import { Hono } from 'hono';
import { paymentMiddleware } from 'x402-hono';

const app = new Hono();
const RECEIVING_ADDRESS = process.env.RECEIVING_ADDRESS;

if (!RECEIVING_ADDRESS) {
  throw new Error("RECEIVING_ADDRESS environment variable is required");
}

// Free health check endpoint
app.get("/health", (c) => c.json({ status: "healthy" }));

// Free info endpoint
app.get("/info", (c) => c.json({
  name: "Simple String Reverser API (x402-hono)",
  description: "Testnet string utilities with x402-hono on Base Sepolia",
  endpoints: ["/tools/paid/reverse-string"]
}));

// Base Sepolia testnet paid endpoint with x402-hono middleware
app.post("/tools/paid/reverse-string",
  paymentMiddleware(
    RECEIVING_ADDRESS,
    {
      "/tools/paid/reverse-string": {
        price: "$0.001",
        network: "base-sepolia",
        config: {
          discoverable: true,
          description: "reverse string (paid)"
        }
      }
    },
    { url: "https://x402.org/facilitator" },
    {
      appLogo: "https://dirtroad.dev/logo.svg",
      appName: "Dirt Road Dev"
    }
  ),
  async (c) => {
    const { str } = await c.req.json();

    if (!str || typeof str !== 'string') {
      return c.json({ error: "str parameter is required and must be a string" }, 400);
    }

    const result = str.split('').reverse().join('');
    return c.json({
      original: str,
      result,
      network: "base-sepolia"
    });
  }
);

export default app;

Step 4: Start the Server

The Hono template creates a ready-to-run server. Start your server:
npm run dev
Expected output:
🚀 x402-hono String Reverser API running on http://localhost:3000
💰 Receiving payments at: 0x_your_wallet_address_here

Step 5: Test Your Paid API

Test the free endpoints first:
curl http://localhost:3000/info
Expected output:
{
  "name": "Simple String Reverser API (x402-hono)",
  "description": "Testnet string utilities with x402-hono on Base Sepolia",
  "endpoints": ["/tools/paid/reverse-string"]
}
Test the paid endpoint (this will return 402 Payment Required):
curl -X POST http://localhost:3000/tools/paid/reverse-string \
  -H "Content-Type: application/json" \
  -d '{"str": "Hello World"}'
Expected output:
{
  "error": "402 Payment Required",
  "payment": {
    "price": "$0.001",
    "network": "base-sepolia",
    "config": {
      "discoverable": true,
      "description": "reverse string (paid)"
    }
  }
}

How It Works

x402-hono integrates x402 payment functionality directly into Hono applications:
  1. Middleware Integration: Each route gets individual payment middleware
  2. USD Pricing: Prices are specified in USD (converted to appropriate token amounts)
  3. Service Discovery: Services with discoverable: true appear in x402 directories
  4. Base Sepolia Testnet: Optimized for testing on Base Sepolia with USDC

Key Features

  • Individual Route Protection: Middleware applied per route, not globally
  • Automatic Discovery: Services appear in x402 service directories
  • USD-Based Pricing: Human-readable pricing in dollars
  • Testnet Ready: Designed for Base Sepolia testnet deployment

Configuration Options

Middleware Parameters

paymentMiddleware(
  receivingAddress: string,        // Your wallet address
  routeConfigs: RouteConfigMap,   // Per-route configurations
  facilitatorConfig: { url: string }, // Facilitator endpoint
  branding: { appLogo: string, appName: string } // App branding
)

Route Configuration

Each route specifies pricing and network:
{
  "/api/endpoint": {
    price: "$0.001",           // Price in USD
    network: "base-sepolia",  // Target network (Base Sepolia testnet)
    config: {
      discoverable: true,     // Enable service discovery
      description: "Service description"
    }
  }
}

Error Handling

Common issues and solutions:
  1. “RECEIVING_ADDRESS not configured”
    • Ensure your .env file contains the RECEIVING_ADDRESS variable
    • Restart your server after adding the environment variable
  2. “Facilitator connection failed”
    • Verify the facilitator URL is accessible (x402.org/facilitator)
    • Check your internet connection
  3. “Payment validation failed”
    • Ensure your receiving address has sufficient USDC balance on Base Sepolia
    • Verify the address format is correct
  4. “Invalid string parameter”
    • Ensure you’re sending a JSON object with a “str” field
    • The str field must be a string value

Testnet Deployment

For Base Sepolia testnet deployment:
  1. Environment Setup:
    RECEIVING_ADDRESS=0x_your_testnet_wallet
    NODE_ENV=development
    
  2. Token Setup:
    • Get test USDC from Circle Faucet (select Base Sepolia)
    • The x402.org facilitator handles payment processing
  3. Testing: Use the x402.org public testnet facilitator for development

Next Steps

Once your Base Sepolia x402-hono service is running: