x402 on Next.js / Edge Runtime
Use Next.js route handlers to return HTTP 402 challenges. This works on both Edge and Node runtimes - just change the runtime export.
Minimal Edge implementation
// app/api/priced/route.ts
export const runtime = "edge";
export async function GET() {
// TODO: verify presented receipt
const verified = false;
if (!verified) {
return new Response(JSON.stringify({
detail: "Payment required for /api/priced",
payment: {
protocol: "x402",
amount: "0.25",
currency: "USDC",
reference: "edge-001"
}
}), {
status: 402,
headers: { "content-type":"application/json" }
});
}
return Response.json({ ok: true, data: "edge-secret" });
}Edge runtime benefits
The Edge runtime deploys globally and responds fast. Perfect for 402 challenges that need to be geographically distributed.
Adding receipt verification
When the client retries with a receipt, verify it before granting access:
// app/api/priced/route.ts
export const runtime = "edge";
export async function GET(request: Request) {
const receipt = request.headers.get("x-receipt");
if (!receipt) {
return new Response(JSON.stringify({
detail: "Payment required for /api/priced",
payment: {
protocol: "x402",
amount: "0.25",
currency: "USDC",
reference: "edge-001"
}
}), {
status: 402,
headers: { "content-type":"application/json" }
});
}
// Verify receipt
const verified = await verifyReceipt(receipt);
if (!verified) {
return Response.json(
{ error: "Invalid or expired receipt" },
{ status: 403 }
);
}
return Response.json({ ok: true, data: "edge-secret" });
}Node runtime variant
For Node runtime, just change the first line:
export const runtime = "nodejs";The rest of the code stays the same. Node runtime gives you access to Node APIs like filesystem and crypto modules.
Receipt verification tips
- Use the
request.headers.get()API to read receipt headers - Verify cryptographic signatures with Web Crypto API (available in Edge)
- Return
403for invalid receipts, not402 - Cache verified receipts to reduce verification overhead
Next steps
Deploy to Vercel Edge or Node runtime and integrate with your payment rail. See the x402 pillar guide for receipt patterns.
Developer Tools