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.
BenefitDescription
Zero protocol feesFree for customers and merchants - just pay nominal network fees
Zero waitMoney moves at the speed of the internet
Zero frictionNo accounts or personal information needed
Zero centralizationAnyone can build on or extend x402
Zero restrictionsNeutral 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:
BenefitDescription
Global edge network700+ Points of Presence worldwide for low-latency delivery
DDoS protectionBuilt-in AWS Shield Standard at no extra cost
SSL/TLS terminationFree SSL certificates via ACM, HTTPS everywhere
CachingReduce origin load and costs with intelligent caching
Origin flexibilityWorks with any HTTP origin - AWS, other clouds, on-prem, SaaS
Cost optimizationPay only for data transfer, often cheaper than direct origin access
WAF integrationAdd 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 BenefitDescription
Zero backend changesYour origin application stays completely untouched
Works with any HTTP originWeb apps, APIs, static sites, cached or non-cached content
Edge performancePayment verification happens close to users globally
Fair billingCustomers only charged when the request succeeds
Drop-in monetizationAdd 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
  2. 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 FunctionCloudFront EventPurpose
originRequestHandlerorigin-requestVerify payment, forward to origin
originResponseHandlerorigin-responseSettle 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:
  1. Enable AWS WAF Bot ControlΒ  on your CloudFront distribution
  2. Configure WAF rules to add custom headers based on bot labels (using rule actions)
  3. 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