Merchants 8 min read

Hono / Express / Next.js

TypeScript integration examples for popular frameworks

Hono

Hono is a lightweight, fast web framework that works great with x402.

Installation

npm install hono @hono/node-server x402-hono

Basic Setup

import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { paymentMiddleware } from "x402-hono";

const app = new Hono();

// Configure the payment middleware
app.use(paymentMiddleware(
  "0xYourAddress", // your receiving wallet address
  {  // Route configurations for protected endpoints
    "/weather": {
      price: "$0.001",
      network: "base-sepolia",
      config: {
        description: "Access to weather data",
      }
    }
  },
  {
    url: "https://x402.org/facilitator", // Facilitator URL for Base Sepolia testnet
  }
));

// Implement your route
app.get("/weather", (c) => {
  return c.json({
    report: {
      weather: "sunny",
      temperature: 70,
    }
  });
});

serve({
  fetch: app.fetch,
  port: 3000
});

Dynamic Pricing

x402 v2Limited Dynamic Pricing in v1

The current x402 v1 Coinbase SDK does not provide a convenient developer experience for truly dynamic pricing (e.g., pricing based on request parameters or real-time calculations). Full dynamic pricing support with improved DX is coming in the imminent x402 v2 release.

Multiple Networks

x402 v2Enhanced Multi-Network Support in v2

x402 v1 has limited multi-network support. The upcoming x402 v2 release introduces CAIP-2 network identifiers (e.g., eip155:8453 instead of base), expanded asset support including ISO 4217 fiat currency codes, and better tooling for accepting payments across multiple networks and assets simultaneously.

Express

For existing Express applications, you can use the x402 middleware.

Installation

npm install express x402-express

Basic Setup

import express from "express";
import { paymentMiddleware, Network } from "x402-express";

const app = express();

app.use(paymentMiddleware(
  "0xYourAddress", // your receiving wallet address
  {  // Route configurations for protected endpoints
    "GET /weather": {
      // USDC amount in dollars
      price: "$0.001",
      network: "base-sepolia",
    },
  },
  {
    url: "https://x402.org/facilitator", // Facilitator URL for Base Sepolia testnet
  }
));

// Implement your route
app.get("/weather", (req, res) => {
  res.send({
    report: {
      weather: "sunny",
      temperature: 70,
    },
  });
});

app.listen(4021, () => {
  console.log(`Server listening at http://localhost:4021`);
});

Next.js

For Next.js applications, use the x402-next middleware package.

Installation

npm install x402-next

Middleware Setup

Create a middleware.ts file in your project root:

// middleware.ts
import { paymentMiddleware } from 'x402-next';

// Configure the payment middleware
export const middleware = paymentMiddleware(
  "0xYourAddress", // your receiving wallet address
  {  // Route configurations for protected endpoints
    '/protected': {
      price: '$0.01',
      network: "base-sepolia",
      config: {
        description: 'Access to protected content'
      }
    },
  },
  {
    url: "https://x402.org/facilitator", // Facilitator URL for Base Sepolia testnet
  }
);

// Configure which paths the middleware should run on
export const config = {
  matcher: [
    '/protected/:path*',
  ]
};

Route Handler

// app/protected/route.ts
import { NextResponse } from "next/server";

export async function GET() {
  // This route is protected by the middleware
  // Payment verification happens automatically
  return NextResponse.json({
    data: "Protected content",
    timestamp: new Date().toISOString(),
  });
}

Configuration Options

The payment middleware accepts a configuration object with the following options:

interface PaymentMiddlewareConfig {
  description?: string;               // Description of the payment
  mimeType?: string;                  // MIME type of the resource
  maxTimeoutSeconds?: number;         // Maximum time for payment (default: 60)
  outputSchema?: Record<string, any>; // JSON schema for the response
  customPaywallHtml?: string;         // Custom HTML for the paywall
  resource?: string;                  // Resource URL (defaults to request URL)
}

Testing Your Integration

  1. Make a request to your endpoint (e.g., curl http://localhost:3000/weather)
  2. The server responds with a 402 Payment Required, including payment instructions in the body
  3. Complete the payment using a compatible client, wallet, or automated agent
  4. Retry the request with the X-PAYMENT header containing the payment payload
  5. The server verifies the payment via the facilitator and returns your API response

Next Steps