> This page location: Functions > Templates > Paid API with x402 and Hono
> Full Neon documentation index: https://neon.com/docs/llms.txt

# Paid API with x402 and Hono

Charge per request in testnet USDC on Base Sepolia with x402, and keep a payment ledger in Lakebase Postgres.

- First Party: maintained by Neon
- Built by: Neon
- Categories: First Party, APIs, Payments
- Built with: [Lakebase Postgres](https://neon.com/docs/postgres/overview.md)

## Install

```bash
neon functions new x402-paid-api
```

## About this template

This template is a pay-per-request JSON API that runs as a [Neon Function](https://neon.com/docs/compute/functions/overview). [x402](https://x402.org/) protects `GET /premium`. Callers pay a small amount of testnet USDC on Base Sepolia, and the function writes every settlement to [Lakebase Postgres](https://neon.com/lakebase).

- [Hono](https://hono.dev/) handles routing and JSON responses.
- [`@x402/hono`](https://www.npmjs.com/package/@x402/hono) returns `402 Payment Required` and verifies payments through an x402 facilitator. [`@x402/evm`](https://www.npmjs.com/package/@x402/evm) provides the `exact` EVM payment scheme.
- [`pg`](https://node-postgres.com/) stores the payment ledger. Neon injects `DATABASE_URL` from the linked branch.

The template is API-only. API clients get a JSON `402` with the payment requirements. A browser gets the x402 middleware's HTML payment page instead. The middleware treats a request as a browser when it sends `Accept: text/html` and a `Mozilla` user agent.

### Scaffold it

Install the latest Neon CLI, then create the function from the registry:

```bash
npm install -g neon@latest
neon login
neon link
neon functions new x402-paid-api --slug paidapi
```

The CLI writes `functions/paidapi/index.ts`, declares `paidapi` in `neon.ts`, and adds `X402_EVM_ADDRESS` to `.env.example`.

`neon.ts` passes the address through as a function env variable:

```ts
import { defineConfig } from "@neon/config/v1";

export default defineConfig({
  functions: {
    paidapi: {
      name: "Paid API with x402 and Hono",
      source: "./functions/paidapi/index.ts",
      env: { X402_EVM_ADDRESS: process.env.X402_EVM_ADDRESS! },
    },
  },
});
```

### Set the receiving address

| Variable | Description | Required |
| --- | --- | --- |
| `X402_EVM_ADDRESS` | An EVM wallet address (0x...) on Base Sepolia that receives payments. The buyer needs Base Sepolia USDC. | Yes |

Add an EVM address you control to `.env.local`:

```bash
printf 'X402_EVM_ADDRESS=%s\n' "0xYourAddress" >> .env.local
```

The buyer needs Base Sepolia USDC from a [faucet](https://faucet.circle.com/). On mainnet, use a real receiving address.

### Run locally

```bash
neon dev
```

Call the URL that `neon dev` prints, which defaults to `http://localhost:8787/`:

```bash
# Describe the API
curl http://localhost:8787/

# Get the payment requirements
curl -i http://localhost:8787/premium
```

The second request returns `402 Payment Required` with a `PAYMENT-REQUIRED` header. The first `/premium` request also fetches the facilitator's `/supported` endpoint. If the facilitator is unreachable, the route returns `503`.

The ledger is empty until a payment settles:

```bash
curl http://localhost:8787/stats
# {"count":0,"totalUsd":"0","lastSettlementAt":null}
```

`/stats` returns the number of settled payments, the total in USD, and the latest settlement time. `GET /stats` or the first settled payment creates the `x402_payments` table in the linked Postgres branch, so there is no migration step.

To complete a payment, use an x402 buyer client with a funded Base Sepolia wallet. See the [x402 buyer quickstart](https://docs.x402.org/getting-started/quickstart-for-buyers). After a successful paid request, `/stats` includes the settlement.

### Routes

| Method | Path       | Result                                                                |
| ------ | ---------- | --------------------------------------------------------------------- |
| `GET`  | `/`        | API name, network, price, route list, and buyer setup links           |
| `GET`  | `/premium` | The paid JSON response, or `402` with payment instructions            |
| `GET`  | `/stats`   | Number of settled payments, total USD, and the latest settlement time |

Non-`GET` requests to `/premium` return `405`. The function treats `/premium/`, with a single trailing slash, as `/premium`. Paths with duplicate slashes and any other path return `404`.

### Customize

The defaults are constants at the top of `functions/paidapi/index.ts`:

```ts
const NETWORK = "eip155:84532"; // Base Sepolia
const PRICE = "$0.001";
const FACILITATOR_URL = "https://x402.org/facilitator";
```

- **Network.** For mainnet, change `NETWORK` to `eip155:8453`, use a mainnet receiving address, and use a mainnet facilitator. `https://x402.org/facilitator` is testnet-only. The CDP facilitator at `https://api.cdp.coinbase.com/platform/v2/x402` requires CDP API credentials and returns `401` without them. Use `createCdpFacilitatorClient` from `@coinbase/cdp-sdk`, which signs a JWT from `CDP_API_KEY_ID` and `CDP_API_KEY_SECRET`, or pass an equivalent `createAuthHeaders` callback to `HTTPFacilitatorClient`. Add those variables to the function env in `neon.ts` and to `.env.local`.
- **Price.** `PRICE` is a USD string. The template uses testnet USDC. Test the full payment flow before switching to mainnet.

### Deploy

```bash
neon deploy --env .env.local
neon functions get paidapi
```

`--env .env.local` lets `neon.ts` resolve `X402_EVM_ADDRESS` before deployment. `neon functions get` prints the function's public URL. Call the same routes there:

```bash
curl -i https://<function-url>/premium
```

### Data model

`GET /stats` or the first settled payment creates the ledger:

```sql
CREATE TABLE IF NOT EXISTS x402_payments (
  id bigserial PRIMARY KEY,
  transaction text NOT NULL,
  network text NOT NULL,
  payer text,
  amount_atomic text NOT NULL,
  amount_usd numeric(20, 6) NOT NULL,
  asset text NOT NULL,
  resource text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS x402_payments_transaction_key
  ON x402_payments (transaction);
```

The x402 `onAfterSettle` hook inserts one row per settled payment with `ON CONFLICT (transaction) DO NOTHING`, so a retried settlement cannot double-count. The write is best-effort. If it fails, the function logs the error and still returns the response for the settled payment.

### Notes

- A Neon Function URL is public. `/` and `/stats` are free, and only `/premium` requires payment.
- `/stats` is public too. To restrict access, check a secret token in a request header.

## Related

- Previous: [Mirror WorkOS data into Postgres](https://neon.com/functions/templates/workos-sync.md)
- Next: [CRUD API with OpenAPI and Postgres](https://neon.com/functions/templates/openapi-postgres.md)
- [All templates](https://neon.com/functions/templates.md)
- [Template source](https://github.com/neondatabase/examples/tree/main/registry/x402-paid-api)
- [Use function templates](https://neon.com/docs/compute/functions/templates.md)
- [Contribute a function template](https://neon.com/docs/compute/functions/registry.md)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/functions/templates/x402-paid-api"}` to https://feedback.neon.tech/ (no auth required).