---
title: Hono Integration
description: Start accepting x402 payments in your Hono server in 2 minutes
keywords:
  [x402, Hono, Node.js, TypeScript, blockchain payments, API monetization]
last_updated: 2026-08-19
---

# Getting Started with Hono

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

:::info Example Code
You can find the full code for this example on [GitHub](https://github.com/BlockEdenHQ/x402-examples/tree/main/typescript/servers/hono).
:::

## Step 1: Install Dependencies

Install the required packages for your Hono server:

```bash
npm install x402 hono dotenv @hono/node-server
```

## Step 2: Set Your Environment Variables

Create a `.env` file in your project root:

```bash
echo "ADDRESS=0x...\nFACILITATOR_URL=https://x402.bex.co\nNETWORK=sui\nBEX_API_KEY=your_api_key_here" > .env
```

Your `.env` file should look like this:

```env
ADDRESS=0x... # wallet public address you want to receive payments to
FACILITATOR_URL=https://x402.bex.co
NETWORK=sui # recommended for fastest settlement
BEX_API_KEY=your_api_key_here # get from https://bex.co/dash/
```

:::tip Network Options
bex.co 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:

```typescript
import { config } from "dotenv";
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { paymentMiddleware, Network, Resource } from "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.BEX_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:

```bash
npx tsx index.ts
```

<div style={{padding: '1rem', background: '#d1fae5', borderRadius: '0.5rem', color: '#065f46', marginTop: '1rem', marginBottom: '1rem'}}>
  <ion-icon name="checkmark-circle" style={{fontSize: '1.5rem', verticalAlign: 'middle', marginRight: '0.5rem'}}></ion-icon>
  <strong>Your Hono server is now accepting x402 payments!</strong>
</div>

## 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.

:::note 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

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

### Route Wildcards

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

### Multiple Routes

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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

```typescript
import { config } from "dotenv";
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { cors } from "hono/cors";
import { paymentMiddleware } from "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.bex.co",
      apiKey: process.env.BEX_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 `BEX_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:

- <ion-icon name="flash"></ion-icon> **Ultra-fast**: Hono is one of the fastest web frameworks for Node.js
- <ion-icon name="cube"></ion-icon> **Small footprint**: Lightweight with minimal dependencies
- <ion-icon name="code-slash"></ion-icon> **TypeScript-first**: Excellent type safety and developer experience
- <ion-icon name="rocket"></ion-icon> **Edge-ready**: Deploy to Cloudflare Workers, Deno, Bun, and more
- <ion-icon name="git-branch"></ion-icon> **Express-like API**: Easy migration if you're familiar with Express

## Next Steps

- <ion-icon name="arrow-forward-circle"></ion-icon> [Implement a crypto paywall](./implement-a-crypto-paywall-with-x402.md)
- <ion-icon name="arrow-forward-circle"></ion-icon> [View the merchant introduction](./x402-for-merchants.md)
- <ion-icon name="arrow-forward-circle"></ion-icon> [Read the Quick Start Guide](./quickstart.md)

## Need Help?

<div style={{padding: '1.5rem', background: '#f3f4f6', borderRadius: '0.5rem', marginTop: '2rem'}}>
  <div style={{display: 'flex', alignItems: 'flex-start', marginBottom: '1rem'}}>
    <ion-icon name="people" style={{fontSize: '1.5rem', marginRight: '0.5rem', color: '#374151'}}></ion-icon>
    <div>
      <h4 style={{margin: 0, fontSize: '1.125rem', fontWeight: 600, color: '#111827'}}>Join Our Community</h4>
      <p style={{margin: '0.25rem 0 0 0', color: '#6b7280'}}>Have questions or want to connect with other developers?</p>
    </div>
  </div>
  <a
    href="https://discord.gg/4Yfvs2HWey"
    target="_blank"
    rel="noopener noreferrer"
    style={{
      display: 'inline-flex',
      alignItems: 'center',
      gap: '0.5rem',
      padding: '0.625rem 1.25rem',
      background: '#5865F2',
      color: 'white',
      borderRadius: '0.5rem',
      textDecoration: 'none',
      fontWeight: 600,
      fontSize: '0.9375rem',
      transition: 'background 0.2s',
      border: 'none'
    }}
    onMouseOver={(e) => e.currentTarget.style.background = '#4752C4'}
    onMouseOut={(e) => e.currentTarget.style.background = '#5865F2'}
  >
    <ion-icon name="logo-discord" style={{fontSize: '1.25rem'}}></ion-icon>
    <span>Join Discord</span>
  </a>
</div>
