@okxweb3/x402-express
v0.1.0
Published
x402 Payment Protocol
Keywords
Readme
@okxweb3/x402-express
Express middleware for the x402 Payment Protocol. Adds x402 payment requirements to Express.js applications.
Installation
npm install @okxweb3/x402-expressQuick Start
import express from "express";
import { paymentMiddleware, x402ResourceServer } from "@okxweb3/x402-express";
import { ExactEvmScheme } from "@okxweb3/x402-evm/exact/server";
import { OKXFacilitatorClient } from "@okxweb3/x402-core/server";
const app = express();
const facilitatorClient = new OKXFacilitatorClient();
const resourceServer = new x402ResourceServer(facilitatorClient)
.register("eip155:196", new ExactEvmScheme());
app.use(
paymentMiddleware(
{
"GET /protected-route": {
accepts: {
scheme: "exact",
price: "$0.10",
network: "eip155:196",
payTo: "0xYourAddress",
},
description: "Access to premium content",
},
},
resourceServer,
),
);
app.get("/protected-route", (req, res) => {
res.json({ message: "Premium content" });
});
app.listen(3000);API Reference
paymentMiddleware
function paymentMiddleware(
routes: RoutesConfig,
server: x402ResourceServer,
syncFacilitatorOnStart?: boolean,
): (req: Request, res: Response, next: NextFunction) => Promise<void>;Creates Express middleware that:
- Checks if the incoming request matches a protected route
- Validates payment headers if required
- Returns payment instructions (402 status) if payment is missing or invalid
- Processes the request if payment is valid
- Handles settlement after successful response
Parameters
| Parameter | Required | Description |
|-----------|----------|-------------|
| routes | Yes | Route configurations for protected endpoints |
| server | Yes | Pre-configured x402ResourceServer instance |
| syncFacilitatorOnStart | No | Whether to sync with facilitator on startup (default: true) |
setSettlementOverrides
function setSettlementOverrides(res: Response, overrides: SettlementOverrides): void;Set settlement overrides on the response for partial settlement.
Route Configuration
const routes: RoutesConfig = {
"GET /api/protected": {
accepts: {
scheme: "exact",
price: "$0.10",
network: "eip155:196",
payTo: "0xYourAddress",
maxTimeoutSeconds: 60,
},
description: "Premium API access",
},
};
app.use(paymentMiddleware(routes, resourceServer));Multiple Protected Routes
app.use(
paymentMiddleware(
{
"GET /api/premium/*": {
accepts: {
scheme: "exact",
price: "$1.00",
network: "eip155:196",
payTo: "0xYourAddress",
},
description: "Premium API access",
},
"GET /api/data": {
accepts: {
scheme: "exact",
price: "$0.50",
network: "eip155:196",
payTo: "0xYourAddress",
maxTimeoutSeconds: 120,
},
description: "Data endpoint access",
},
},
resourceServer,
),
);