Skip to main content

Getting Started with Hono

Start accepting x402 payments in your Hono server in 2 minutes.

Example Code

You can find the full code for this example on GitHub.

Step 1: Install Dependencies

Install the required packages for your Hono server:

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

Step 2: Set Your Environment Variables

Create a .env file in your project root:

echo "ADDRESS=0x...\nFACILITATOR_URL=https://x402.blockeden.xyz\nNETWORK=sui\nBLOCKEDEN_API_KEY=your_api_key_here" > .env

Your .env file should look like this:

ADDRESS=0x... # wallet public address you want to receive payments to
FACILITATOR_URL=https://x402.blockeden.xyz
NETWORK=sui # recommended for fastest settlement
BLOCKEDEN_API_KEY=your_api_key_here # get from https://blockeden.xyz/dash/
Network Options

BlockEden.xyz supports multiple networks:

  • sui (recommended for fastest settlement)
  • ethereum
  • base
  • polygon
  • avalanche

Step 3: Create a New Hono App

Create an index.ts file with the following code:

import { config } from "dotenv";
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { paymentMiddleware, Network, Resource } from "@blockeden/x402-hono";

config();

const facilitatorUrl = process.env.FACILITATOR_URL as Resource;
const payTo = process.env.ADDRESS as `0x${string}`;
const network = process.env.NETWORK as Network;
const apiKey = process.env.BLOCKEDEN_API_KEY;

if (!facilitatorUrl || !payTo || !network || !apiKey) {
console.error("Missing required environment variables");
process.exit(1);
}

const app = new Hono();

console.log("Hono server is running on http://localhost:4021");

app.use(
paymentMiddleware(
payTo,
{
"/weather": {
price: "$0.001",
network,
},
"/premium/*": {
price: "$0.01",
network,
},
},
{
url: facilitatorUrl,
apiKey: apiKey,
},
),
);

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

app.get("/premium/content", (c) => {
return c.json({
content: "This is premium content",
timestamp: new Date().toISOString(),
});
});

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

Step 4: Run the Server

Start your Hono server:

npx tsx index.ts
Your Hono server is now accepting x402 payments!

Step 5: Test the Server

You can test payments against your server locally using HTTP clients like curl, Postman, or by building a client application.

Coming Soon

Client implementation guides for fetch API and axios will be available soon.

Payment Configuration Options

The paymentMiddleware accepts flexible payment configurations:

Simple Dollar Amount

"/weather": {
price: "$0.001",
network: "sui",
}

Route Wildcards

"/premium/*": {
price: "$0.01",
network: "sui",
}

Multiple Routes

app.use(
paymentMiddleware(
payTo,
{
"/weather": {
price: "$0.001",
network: "sui",
},
"/premium/*": {
price: "$0.05",
network: "sui",
},
"/api/analytics": {
price: "$0.10",
network: "sui",
},
},
{
url: facilitatorUrl,
apiKey: apiKey,
},
),
);

Advanced Features

Custom Payment Verification

Add custom logic when payments are verified:

app.use(
paymentMiddleware(
payTo,
paymentConfig,
{
url: facilitatorUrl,
apiKey: apiKey,
onPaymentVerified: (c, paymentData) => {
console.log('Payment verified:', paymentData.txHash);
// Custom logging, analytics, or business logic
},
},
),
);

Error Handling

Add custom error handling middleware:

app.onError((err, c) => {
if (err.name === 'X402PaymentError') {
return c.json(
{
error: 'Payment required',
details: err.message,
},
402
);
}
return c.json({ error: 'Internal server error' }, 500);
});

CORS Configuration

Enable CORS for cross-origin requests:

import { cors } from 'hono/cors';

app.use('/*', cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3000'],
credentials: true,
}));

Production Deployment

Before deploying to production:

  1. Switch to production network (e.g., sui instead of sui-testnet)
  2. Use environment variables for all sensitive data
  3. Enable HTTPS for your server
  4. Set up proper error logging
  5. Configure CORS for your production domains

Production Example

import { config } from "dotenv";
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { cors } from 'hono/cors';
import { paymentMiddleware } from "@blockeden/x402-hono";

config();

const app = new Hono();

// Enable CORS for production
app.use('/*', cors({
origin: process.env.ALLOWED_ORIGINS?.split(','),
credentials: true,
}));

// Apply payment middleware
app.use(
paymentMiddleware(
process.env.ADDRESS as `0x${string}`,
{
"/api/weather": {
price: "$0.01",
network: "sui", // Production Sui network
},
},
{
url: "https://x402.blockeden.xyz",
apiKey: process.env.BLOCKEDEN_API_KEY,
},
),
);

// Protected endpoint
app.get("/api/weather", (c) => {
return c.json({
report: { weather: "sunny", temperature: 70 },
});
});

serve({
fetch: app.fetch,
port: parseInt(process.env.PORT || "4021"),
});

Troubleshooting

Common Issues

Payment verification fails

  • Verify your BLOCKEDEN_API_KEY is correct
  • Check that the wallet address format matches the network
  • Ensure the facilitator URL is accessible

CORS errors

  • Add CORS middleware before payment middleware
  • Configure allowed origins properly

Network mismatch

  • Ensure client and server use the same network
  • Check that the token address is valid for the network

Port already in use

  • Change the port in serve() configuration
  • Kill any existing processes using the port

Why Choose Hono?

Hono is an excellent choice for x402 payment servers:

  • Ultra-fast: Hono is one of the fastest web frameworks for Node.js
  • Small footprint: Lightweight with minimal dependencies
  • TypeScript-first: Excellent type safety and developer experience
  • Edge-ready: Deploy to Cloudflare Workers, Deno, Bun, and more
  • Express-like API: Easy migration if you're familiar with Express

Next Steps

Need Help?

Join Our Community

Have questions or want to connect with other developers?

Join Discord