
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.
1
2
3
4
βββββββββββ ββββββββββββββββββββββββββββ βββββββββββββββ
β 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:
- Origin Request - Verifies the payment signature before forwarding to your origin
- 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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:
1
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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:
- Enable AWS WAF Bot ControlΒ on your CloudFront distribution
- Configure WAF rules to add custom headers based on bot labels (using rule actions)
- 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-SIGNATUREheader in the cache keyΒ for token-based caching
Resources
- Full Example: github.com/coinbase/x402/.../cloudfront-lambda-edgeΒ
- x402 Website: x402.orgΒ
- x402 Documentation: docs.x402.orgΒ
- Quickstart for Sellers: How to accept payments in your applicationΒ
- Quickstart for Buyers: How to set up a wallet and make paymentsΒ
- CDP Wallet API: Recommended for programmatic paymentsΒ
- x402 Specification: github.com/coinbase/x402/specsΒ
- AWS WAF adds AI traffic monetization capabilityΒ
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Β .
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article