This is a Next.js application that demonstrates how to use the x402-next middleware to implement paywall functionality in your Next.js routes.
- Node.js v22+ (install via nvm)
- pnpm v10 (install via pnpm.io/installation)
- A valid Ethereum address for receiving payments
- Copy
.env.localto.envand add your Ethereum address to receive payments:
cp .env.local .env- Install and build all packages from the typescript examples root:
cd ../../
pnpm install
pnpm build
cd fullstack/mainnet- Install and start the Next.js example:
pnpm devThe app includes protected routes that require payment to access:
The /protected route requires a payment of $0.001 to access. The route is protected using the x402-next middleware:
// middleware.ts
import { paymentMiddleware, Network, Resource } from "x402-next";
import { facilitator } from "@coinbase/x402";
const payTo = process.env.RESOURCE_WALLET_ADDRESS as Address;
export const middleware = paymentMiddleware(
payTo,
{
"/protected": {
price: "$0.001",
network: "base",
config: {
description: "Access to protected content",
},
},
},
facilitator
);
// Configure which paths the middleware should run on
export const config = {
matcher: ["/protected/:path*"],
runtime: "nodejs",
};{
"error": "X-PAYMENT header is required",
"paymentRequirements": {
"scheme": "exact",
"network": "base",
"maxAmountRequired": "1000",
"resource": "http://localhost:3000/protected",
"description": "Access to protected content",
"mimeType": "",
"payTo": "0xYourAddress",
"maxTimeoutSeconds": 60,
"asset": "0x...",
"outputSchema": null,
"extra": null
}
}// Headers
{
"X-PAYMENT-RESPONSE": "..." // Encoded response object
}To add more protected routes, update the middleware configuration:
export const middleware = paymentMiddleware(
payTo,
{
"/protected": {
price: "$0.001",
network: "base",
config: {
description: "Access to protected content",
},
},
"/api/premium": {
price: "$0.01",
network: "base",
config: {
description: "Premium API access",
},
},
}
);
export const config = {
matcher: ["/protected/:path*", "/api/premium/:path*"],
runtime: "nodejs",
};To access the mainnet facilitator in Next.js, simply install and use the @coinbase/x402 package.