DEV Community

Cover image for How to Monetise Your API in Next.js using the x402 Protocol
Joshua Omobola
Joshua Omobola Subscriber

Posted on • Originally published at koha.hashnode.dev

How to Monetise Your API in Next.js using the x402 Protocol

What if you could charge a few cents every time users access your API? This is almost impossible using payment processors like Stripe and PayPal. Their transaction fees alone make micropayments impossible, not to mention the complex setup needed to get it to work.  Plus, you can't ask users to fill in a payment form just to spend half a cent on an API call every time. Nobody is going to do that.

x402 changes this.

x402 is a new payment standard that lets you charge for API access through standard HTTP responses. x402 works without credit cards, sign-ups, or subscriptions. It uses stablecoins on the blockchain to make instant and near-zero fees finally possible.

In this tutorial, you'll build a simple marketplace for premium AI prompts with Next.js. Users will be able to unlock premium AI prompts by paying $0.005 USD per call to your API. 

Here’s a demo of what you will build using this guide:

an image showing the final demo

Prefer a video version of this tutorial? Check out How to Monetise your APIs in Next.js with x402 Protocol

What is x402?

x402 is an open payment standard that enables web services and AI agents to charge for API access and content directly over HTTP. It is built on top of the long-reserved HTTP 402Payment Required” status code. 

x402 removes the need for API keys, subscriptions, and manual payment processing, enabling any web service to request payment in real time using stablecoins like USDC. With just one line of code, developers can integrate pay-per-use monetisation and receive instant, seamless payments for APIs & digital services.

Core Components of x402

  • Sellers: People or companies who want to monetise their APIs or content.

  • Buyers: Developers and AI agents seeking to access paid services without accounts or manual payment flows.

  • Facilitators: This is a service that verifies and settles payments on behalf of the buyers and sellers. e.g PayAI

How x402 Works

When a client(user) first requests a resource from the  server(your app), the server responds with an HTTP 402 Payment Required status code along with payment instructions. 

The client then prepares the payment based on these requirements and retries the request, this time including an X-PAYMENT header containing a signed payload. 

On receiving this payment proof, the server verifies it through a facilitator service, settles the payment on the blockchain, and finally delivers the requested resource once the payment is confirmed.

an image showing the payment flow of how x402 works

Now that you have a good understanding of x402 protocol and how it works under the hood, let's move on to building the demo. 

Prerequisites

To follow along with this guide, you will need:

Step 1: Setting up the project

First, create a new Next.js app by running the following command in your terminal:

npx create-next-app@latest x402-prompt-store
Enter fullscreen mode Exit fullscreen mode

The installation will prompt you to select a few options; make sure to accept all the defaults

Next, navigate into the x402-prompt-store directory, and install the dependencies:

// navigate into project
cd x402-prompt-store

// install the packages you need
npm install x402-next x402-fetch viem
Enter fullscreen mode Exit fullscreen mode

Here's what each one does:

  • x402-next — middleware package for Next.js that intercepts API requests and verifies payments

  • x402-fetch — client library that automatically handles the payment flow when it sees a 402 status code response

  • viem — a library that handles blockchain interactions like connecting to wallets & signing transactions.

Step 2: Creating the API routes

Inside of app/api/premium directory, create a new file named route.ts

touch app/api/premium/route.ts
Enter fullscreen mode Exit fullscreen mode

Your file structure should look like this:

 app/
  ├── api/
  │   └── premium/
  │       └── route.ts
  ...
Enter fullscreen mode Exit fullscreen mode

Add the following code to route.ts:

// app/api/premium/route.ts

import { NextRequest } from "next/server";
const PREMIUM_PROMPT = `You are a creative developer who creates stunning UI with motion and interactions. You create eye stunning ui experience with Lovable for Anvil. You are given a prompt and you need to create a lovable UI prompt for Anvil.`;

export async function GET(req: NextRequest) {
  return Response.json({ promptText: PREMIUM_PROMPT });
}
Enter fullscreen mode Exit fullscreen mode

The code above returns the PREMIUM_PROMPT as JSON when it’s called.

You now have a working API endpoint. Start your dev server with npm run dev and visit http://localhost:3000/api/premium in your browser. The output should be the JSON response of the prompt.

an image showing the api response from the x402 demo without payment middleware

Right now, this endpoint is completely free and accessible to anyone. In the next step, you'll add a payment middleware to protect it behind a paywall.

Step 3: Adding a payment paywall to the API

Create middleware.ts at the root of your project, where you will define the payment guard for the API endpoint.

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

const SellersWallet = "Replace_with_your_wallet_address"
const facilitatorObj = { 
    url: "https://facilitator.payai.network" as `https://${string}` 
}

// middleware configuration that paywalls the /api/premium route
export const middleware = paymentMiddleware(
  SellersWallet,
  {
    '/api/premium': { 
      price: '$0.005',
      network: "base-sepolia",
      config: {
        description: 'Access to protected premium content'
      }
    },
  },
  facilitatorObj
);

// Configure which paths the middleware should run on
export const config = {
  matcher: [
    '/api/:path*',
  ],
  runtime: "nodejs"
};
Enter fullscreen mode Exit fullscreen mode

Let's break this down:

The code above uses the paymentMiddleware function from x402-next to define the monetised routes. It accepts three parameters:

  • payTo: The wallet address to receive the payments. R*eplace* SellersWallet with your own wallet address.

  • routes: Route configurations for the protected endpoints

  • facilitator: Configuration for the facilitator service that verifies the payments

With these three parameters, you can pretty much configure the monetisation settings for any API in the app.

In this case, every call to api/premium will cost $0.005 USD, and the payment will settle to the SellersWallet on the base-sepolia network.

The matcher config tells Next.js which routes this middleware should run on, in this case, any route under /api/ directory.

Now, when someone requests /api/premium, the middleware returns a 402 status code response with payment details (how much, where to send it, and which blockchain network).

an image showing the x402 status code after adding the payment middleware

Step 4: Creating the Frontend Interface

Now that you have the API endpoint and paywall middleware in place, let’s add the frontend UI.

Replace the content of  app/page.tsx with the following code:

// app/page.tsx

"use client";

import { useState } from "react";
import { wrapFetchWithPayment } from "x402-fetch";
import { createWalletClient, custom } from "viem";
import { baseSepolia } from "viem/chains";

export default function Home() {
  const [loading, setLoading] = useState(false);

  const handlePremiumPromptClick = async () => {
    console.log("Premium prompt clicked");
  };

  return (
      <main className="mx-auto max-w-3xl p-6">
      <h1 className="text-2xl font-semibold mb-4 font-mono">
        THE PROMPT SUPERSTORE
      </h1>
      <ul className="space-y-4">
        {/* Premium */}
        <li className="border p-4 rounded-md">
          <div className="mt-2 text-sm">Premium($0.005)</div>
          <h2 className="text-xl font-medium">
            Creating Lovable UI Prompts for Anvil
          </h2>
          <button
            onClick={handlePremiumPromptClick}
            className="cursor-pointer mt-3 inline-block text-xs bg-amber-500 dark:text-black px-2 py-0.5 font-mono">
            {loading ? "Unlocking..." : "Unlock"}
          </button>
        </li>
      </ul>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

This code above creates a minimal UI with basic tailwind styling that lets users access your AI prompts.

Right now, you have a single premium prompt card, and clicking the "unlock" button calls the handlePremiumPromptClick function, which prints a message to the console.

an image showing the frontend ui for the x402 demo

Now let's implement the payment logic. 

Update the handlePremiumPromptClick function with the following code:

// app/page.tsx

const handlePremiumPromptClick = async () => {
    try {
      setLoading(true);

      // Request wallet access
      const [address] = await (window as any).ethereum.request({
        method: "eth_requestAccounts",
      });

      // Create wallet client
      const walletClient = createWalletClient({
        account: address,
        chain: baseSepolia,
        transport: custom((window as any).ethereum),
      });

      // Wrap fetch with payment capability
      const fetchWithPayment = wrapFetchWithPayment(
        fetch as any,
        walletClient as any
      );

      // Make API request & automatically handle payment on 402
      const res = await fetchWithPayment("/api/premium", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });

      const data = await res.json();
      alert(`Prompt: ${data.promptText}`);

    } catch (error) {
      console.error("Payment error:", error);
      alert("Failed to unlock premium prompt. Please try again.");

    } finally { 
      setLoading(false);
    }
  };
Enter fullscreen mode Exit fullscreen mode

The code above does the following:

  • Requests the user's wallet address from the browser using the MetaMask wallet extension

  • Creates a wallet client configured with the baseSepolia testnet

  • Wraps the native browser fetch with wrapFetchWithPayment() function, which automatically handles payment when receiving a 402 response

  • Makes a GET request to /api/premium, when the middleware returns 402, the payment flow executes automatically

  • Displays the premium prompt in an alert on success, or shows an error message if payment fails

Let's test it out.

Step 5: Testing the Paywall

Start the server by running the following command:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:3000 in your browser, and you should see THE PROMPT SUPERSTORE UI with one premium prompt item card.

an image showing the frontend ui for the x402 final demo

When users click the unlock button, the MetaMask wallet will pop up, prompting them to confirm a $0.005 USD payment to access the AI prompt.

Conclusion

That's it! You just learned how to monetise APIs in Next.js using the x402 Protocol. You built a simple AI prompts store that requires users to pay to call your API. This kind of Micropayment is really difficult to do with traditional payment providers like Stripe and PayPal, but with x402, it's effortless.

For next steps, explore how to deploy to mainnet or implement dynamic pricing based on content value. Fun stuff!

Here's a list of resources I'd recommend you check out about x402:

If you are stuck or have questions, find me on Twitter (@kohawithstuff). I'm always ready to help.

Happy building!

Top comments (1)

Collapse
 
kopeboy profile image
Lorenzo Giovenali

It doesn't use stablecoins but any coin.. it's an open protocol. The best coin for AIs might not be one that depends on a particular government, maybe a decentralized one that can move instantly without fees and has a fixed supply like Nano (Ӿ).