Server Middleware

Protect your API endpoints with Zeny's server middleware. Handles the full x402 flow: 402 challenge, payment verification, and settlement.

Basic Usage

import { createZenyMiddleware } from "@zeny/sdk/server";

const zeny = createZenyMiddleware({
  apiKey: process.env.ZENY_API_KEY!,
  payTo: "0xYourWalletAddress",
  amount: "0.01", // USDM
});

export async function GET(req: Request) {
  const paymentResponse = await zeny(req);
  if (paymentResponse) return paymentResponse;

  return Response.json({ data: "premium content" });
}

Configuration Options

interface ZenyMiddlewareConfig {
  apiKey: string;           // Your Zeny API key
  payTo: string;            // Seller wallet address
  amount: string;           // Price in USDM
  facilitatorUrl?: string;  // Custom facilitator URL
  scheme?: string;          // Payment scheme (default: "exact")
  network?: string;         // Network (default: "megaeth")
  asset?: string;           // Token address (default: USDM)
}

How It Works

  1. Middleware checks for Payment-Signature header
  2. If missing: returns 402 with Payment-Required header containing requirements
  3. If present: decodes payload, calls verify(), then settle()
  4. On success: returns null — your handler serves the resource
  5. On failure: returns error response