Hono Integration
This guide walks you through adding x402 payment requirements to a Hono server. Hono is a lightweight, ultrafast web framework that runs on multiple runtimes. By the end, you will have a running API that charges $0.001 per request on a protected route.
Installation
bash
npm install x402-hono hono @hono/node-server dotenvEnvironment Setup
Create a .env file in your project root:
bash
ADDRESS=<your-solana-wallet-address>
FACILITATOR_URL=https://facilitator.svmacc.tech
NETWORK=solana-devnet| Variable | Description |
|---|---|
ADDRESS | The Solana wallet address where you want to receive payments. |
FACILITATOR_URL | The URL of the x402 facilitator service that verifies and settles payments. |
NETWORK | The Solana network to use. Use solana-devnet for testing or solana-mainnet for production. |
Server Code
Create a file called server.ts:
typescript
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { paymentMiddleware } from "x402-hono";
import dotenv from "dotenv";
dotenv.config();
const app = new Hono();
const { ADDRESS, FACILITATOR_URL, NETWORK } = process.env;
app.use(
"/weather",
paymentMiddleware(ADDRESS, {
"GET /weather": {
price: "$0.001",
network: NETWORK,
description: "Get weather data",
},
}, { url: FACILITATOR_URL })
);
app.get("/weather", (c) => {
return c.json({ report: { weather: "sunny", temperature: 70 } });
});
serve({ fetch: app.fetch, port: 4021 });
console.log("Server running on http://localhost:4021");How It Works
paymentMiddleware()is applied to the/weatherpath using Hono'sapp.use()method. The middleware intercepts requests to that path and checks for a valid payment header.- The route-price map defines which HTTP method and path combinations require payment, along with the price, network, and a human-readable description.
- The facilitator configuration is passed as the third argument with
{ url: FACILITATOR_URL }. The facilitator athttps://facilitator.svmacc.techhandles verification and settlement of payments. - If a request lacks a valid
X-PAYMENTheader, the middleware returns a402 Payment Requiredresponse. If the payment is valid, the request proceeds to the route handler.
Running the Server
bash
npx ts-node server.tsOr with plain JavaScript:
bash
node server.jsThe server will start on http://localhost:4021. Requests to GET /weather without payment will receive a 402 response with payment instructions.
Protecting Multiple Routes
To protect additional routes, apply the middleware to each path:
typescript
app.use(
"/weather",
paymentMiddleware(ADDRESS, {
"GET /weather": {
price: "$0.001",
network: NETWORK,
description: "Get weather data",
},
}, { url: FACILITATOR_URL })
);
app.use(
"/forecast",
paymentMiddleware(ADDRESS, {
"GET /forecast": {
price: "$0.005",
network: NETWORK,
description: "Get 7-day forecast",
},
}, { url: FACILITATOR_URL })
);Routes without middleware remain free and accessible without payment.