AWS Builder Center
Monetize Any HTTP Application with x402 and CloudFront + Lambda@Edge

Monetize Any HTTP Application with x402 and CloudFront + Lambda@Edge

Add x402 pay-per-request payments to any HTTP-based application or API - without touching your backend code.

📢 Note: Amazon CloudFront and AWS WAF now officially support AI traffic monetization (x402 today, with MPP for machine-to-machine payments coming soon) - see  AWS WAF adds AI traffic monetization capability . For most use cases, the native capability reduces the need for a custom solution like this one. This project remains available as a reference — a research and experimentation space for exploring the mechanics of how custom payment negotiation can work at the edge.

What is x402?

 x402  is an open, neutral standard for internet-native payments. It activates the long-reserved  HTTP 402 "Payment Required"  status code to enable frictionless, programmatic payments between clients and servers.
Benefit
Description
Zero protocol fees
Free for customers and merchants - just pay nominal network fees
Zero wait
Money moves at the speed of the internet
Zero friction
No accounts or personal information needed
Zero centralization
Anyone can build on or extend x402
Zero restrictions
Neutral standard, not tied to any specific network
The flow is simple: client sends request → server responds with 402 Payment Required → client pays and retries → access granted.

Use Cases

x402 + CloudFront enables pay-per-request monetization for any HTTP-based application:
  • Pay-per-call APIs and web services
  • Premium content and paywalled pages
  • AI/ML inference endpoints
  • Data feeds and market data
  • SaaS applications with usage-based billing
  • Rate-limited free tiers with paid overflow
  • MCP endpoints for AI agents - when an AI agent calls your MCP endpoint, it automatically pays from its wallet. See the  MCP Server with x402 guide  for details.

How Easy Is It? CloudFront + Lambda@Edge

Here's the exciting part: with CloudFront and Lambda@Edge, you can add x402 payment requirements to any HTTP-based application - whether it's hosted on AWS, GCP, Azure, on-prem, or third-party services - without modifying a single line of backend code.
Plain text
┌─────────┐ ┌──────────────────────────┐ ┌─────────────┐
│ Client │────▶│ CloudFront + Lambda@Edge │────▶│ Your Origin │
└─────────┘ │ (x402 verification) │ │ (unchanged) │
└──────────────────────────┘ └─────────────┘

Why This Architecture?

CloudFront Benefits (Even Without x402)

If you're not already using CloudFront in front of your applications, here's why you should consider it:
Benefit
Description
Global edge network
700+ Points of Presence worldwide for low-latency delivery
DDoS protection
Built-in AWS Shield Standard at no extra cost
SSL/TLS termination
Free SSL certificates via ACM, HTTPS everywhere
Caching
Reduce origin load and costs with intelligent caching
Origin flexibility
Works with any HTTP origin - AWS, other clouds, on-prem, SaaS
Cost optimization
Pay only for data transfer, often cheaper than direct origin access
WAF integration
Add AWS WAF for bot protection, rate limiting, geo-blocking
CloudFront acts as a reverse proxy that improves performance, security, and reliability for any HTTP application - regardless of where it's hosted.

Adding x402 at the Edge

With Lambda@Edge, you can run code at CloudFront edge locations. This makes it the perfect place to add x402 payment verification:
x402 + CloudFront Benefit
Description
Zero backend changes
Your origin application stays completely untouched
Works with any HTTP origin
Web apps, APIs, static sites, cached or non-cached content
Edge performance
Payment verification happens close to users globally
Fair billing
Customers only charged when the request succeeds
Drop-in monetization
Add payments to existing endpoints in minutes

How It Works

The x402 CloudFront integration uses two Lambda@Edge functions:
  1. Origin Request - Verifies the payment signature before forwarding to your origin
  1. Origin Response - Settles the payment only if your origin returned success (status < 400)
This two-phase approach ensures customers are never charged for failed requests.
Plain text
Client CloudFront Origin
│ │ │
│──── Request ─────────▶│ │
│ │ │
│◀─── 402 Payment ──────│ │
│ Required │ │
│ │ │
│──── Request + ───────▶│ │
│ Payment Signature │ │
│ │──── Forward ───────▶│
│ │ │
│ │◀─── Response ───────│
│ │ │
│ │ (settle payment │
│ │ if status < 400) │
│ │ │
│◀─── Response ─────────│ │

Quick Start

1. Configure Your Routes

Define which endpoints require payment and at what price:
TypeScript
// config.ts
import type { RoutesConfig } from '@x402/core/server';

export const FACILITATOR_URL = 'https://x402.org/facilitator';
export const PAY_TO = '0xYourWalletAddress';
export const NETWORK = 'eip155:84532'; // Base Sepolia (testnet)

export const ROUTES: RoutesConfig = {
'/api/*': {
accepts: {
scheme: 'exact',
network: NETWORK,
payTo: PAY_TO,
price: '$0.001',
},
description: 'API access',
},
'/api/premium/**': {
accepts: {
scheme: 'exact',
network: NETWORK,
payTo: PAY_TO,
price: '$0.01',
},
description: 'Premium API access',
},
};

2. Deploy the Lambda Functions

The example provides two handlers ready for deployment:
TypeScript
import { originRequestHandler, originResponseHandler } from './index';
Lambda Function
CloudFront Event
Purpose
 originRequestHandler 
origin-request
Verify payment, forward to origin
 originResponseHandler 
origin-response
Settle payment if origin succeeded

3. That's It!

Your HTTP application now requires payment. Clients without a valid  PAYMENT-SIGNATURE  header receive a  402 Payment Required  response with payment details.

Composable Middleware

The x402 logic is designed as composable middleware, so you can integrate it with your existing Lambda@Edge logic:
TypeScript
import { createX402Middleware, MiddlewareResultType } from './lib';

const x402 = createX402Middleware({
facilitatorUrl: 'https://x402.org/facilitator',
network: 'eip155:84532',
routes: ROUTES,
});

export const handler = async (event: CloudFrontRequestEvent) => {
const request = event.Records[0].cf.request;
// Your custom logic first (auth, WAF, logging, etc.)
if (request.headers['x-api-key']?.[0]?.value !== 'secret') {
return { status: '401', body: 'Unauthorized' };
}
// x402 payment check
const result = await x402.processOriginRequest(
request,
event.Records[0].cf.config.distributionDomainName
);
if (result.type === MiddlewareResultType.RESPOND) {
return result.response; // 402 Payment Required
}
return result.request;
};

Advanced Use Cases

Monetize Bot Traffic with AWS WAF Bot Control

One of the most powerful patterns with this architecture is charging only bots while keeping human users free. AWS WAF Bot Control can detect and label automated traffic, and you can use this information to selectively require payment.
Why this matters:
  • AI agents and scrapers consume significant resources
  • Bots often don't see ads or convert to paying customers
  • You can monetize automated access without impacting human UX
AWS WAF Bot Control provides:
  • Verified bot detection - Identifies known good bots (Googlebot, etc.) with label  awswaf:managed:aws:bot-control:bot:verified 
  • AI agent detection - Labels traffic from AI crawlers with  awswaf:managed:aws:bot-control:bot:category:ai 
  • Bot categories - Labels like  bot:category:scraping_framework ,  bot:category:http_library , etc.
  • Web Bot Auth (WBA) - New cryptographic verification for legitimate AI agents ( announced Nov 2025 )
To access WAF labels in Lambda@Edge, configure your WAF rules to add custom headers based on labels:
TypeScript
export const handler = async (event: CloudFrontRequestEvent) => {
const request = event.Records[0].cf.request;
// WAF can be configured to add custom headers based on bot labels
// Example: x-bot-category header added by WAF rule action
const botCategory = request.headers['x-bot-category']?.[0]?.value;
const isVerifiedBot = request.headers['x-verified-bot']?.[0]?.value === 'true';
// Free pass for humans (no bot label)
if (!botCategory) {
return request;
}
// Free pass for verified good bots (Googlebot, etc.)
if (isVerifiedBot) {
return request;
}
// Require payment for unverified bots and AI agents
const result = await x402.processOriginRequest(request, distributionDomain);
if (result.type === MiddlewareResultType.RESPOND) {
return result.response; // 402 Payment Required for bots
}
return result.request;
};
Setup:
  1. Enable  AWS WAF Bot Control  on your CloudFront distribution
  1. Configure WAF rules to add custom headers based on bot labels (using rule actions)
  1. Use Lambda@Edge to check headers and apply x402 selectively
This creates a sustainable model: humans browse free, bots pay for access. AI agents with valid Web Bot Auth credentials can be verified and potentially given different pricing tiers.

Caching Optimization

CloudFront caching can reduce facilitator calls:
  • Cache 402 responses so repeated unpaid requests don't hit Lambda@Edge
  • Include  PAYMENT-SIGNATURE  header in the  cache key  for token-based caching

Resources

The x402 ecosystem is growing - check out  x402.org/ecosystem  to see what others are building, or add your own project!


x402 is an open standard by Coinbase. Contributions welcome at  github.com/coinbase/x402 .
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article