Prerequisites

Before you begin, ensure you have the following:

Create Your First Paid API

1

Install x402 packages

Create a new project and install the required packages:
mkdir my-paid-api && cd my-paid-api
npm init -y
npm install @sei-js/x402-express express dotenv
Expected outcome: Project directory created with x402 dependencies installed.
2

Create a simple paid API server

Facilitator Might be Required: The code references facilitatorUrl environment variable that need to be configured. You’ll need to set up a facilitator to process payments or use a public facilitator. See the Facilitator Example here.
Create server.js with a protected API endpoint:
import {config} from "dotenv";
import express from "express";
import {paymentMiddleware, Resource} from "@sei-js/x402-express";
config();

const facilitatorUrl = process.env.FACILITATOR_URL as Resource;
const payTo = process.env.ADDRESS as `0x${string}`;

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

const app = express();

app.use(
  paymentMiddleware(
    payTo,
    {
      "GET /weather": {
        // USDC amount in dollars
        price: "$0.001",
        network: "sei-testnet",
      }
    },
    {
        url: facilitatorUrl,
    },
   ),
);

app.get("/weather", (req, res) => {
res.send({
    report: {
        weather: "sunny",
        temperature: 70,
    },
  });
});

app.listen(4021, () => {
  console.log(`Server listening at http://localhost:${4021}`);
});

Expected outcome: Express server configured with x402 payment middleware.
3

Test the payment requirement

Start your server and test the payment requirement:
node server.js
In another terminal, try accessing the protected endpoint:
curl http://localhost:4021/weather
Expected outcome: You should receive a 402 Payment Required response with payment details.
Example response:
{
    "error": "Payment Required",
    "amount": "0.01",
    "currency": "SEI",
    "recipient": "YOUR_WALLET_ADDRESS",
    "network": "sei-testnet"
}