CloudFront with WAF and Lambda@Edge
Attach AWS WAF to block common web attacks and run lightweight request/response transformations at the edge with Lambda@Edge.
CloudFront with WAF and Lambda@Edge is a free AWS Solutions Architect lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AWS Solutions Architect learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Protecting CloudFront with AWS WAF
AWS WAF (Web Application Firewall) filters and monitors HTTP/HTTPS requests reaching your CloudFront distribution. By attaching a WAF Web ACL to your distribution, you can block common web exploits—SQL injection, cross-site scripting (XSS), bad bots, and OWASP Top 10 attacks—before they reach your origin.
WAF operates at the CloudFront edge, meaning malicious requests are rejected at the nearest edge location rather than reaching your ALB or application server. This reduces load on your backend and stops attacks closer to the attacker.
# Associate a WAF Web ACL with a CloudFront distribution
aws wafv2 associate-web-acl \
--web-acl-arn arn:aws:wafv2:us-east-1:123456789:global/webacl/MyACL/12345 \
--resource-arn arn:aws:cloudfront::123456789:distribution/EDFDVBD6EXAMPLEWAF Rules and Rule Groups
A WAF Web ACL contains ordered rules and rule groups that each match request attributes and take an action (Allow, Block, Count, CAPTCHA). Rules are evaluated in priority order; the first matching rule's action is applied.
AWS provides managed rule groups—pre-built rulesets maintained by AWS and AWS Marketplace sellers. The AWS Managed Rules - Core Rule Set covers OWASP Top 10 without any configuration. Managed rule groups are updated by AWS as new threats emerge, reducing your operational burden.
# Create a Web ACL with AWS Managed Core Rule Set
aws wafv2 create-web-acl \
--name MyCloudFrontACL \
--scope CLOUDFRONT \
--default-action Allow={} \
--rules '[{
"Name": "CoreRuleSet",
"Priority": 1,
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesCommonRuleSet"
}
},
"OverrideAction": {"None": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "CoreRuleSet"
}
}]' \
--visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=MyACL \
--region us-east-1WAF Rate Limiting and Bot Control
Rate-based rules in WAF count requests from each source IP over a 5-minute window. If an IP exceeds the threshold (e.g., 2,000 requests per 5 minutes), WAF blocks further requests from that IP until the rate drops. Rate-based rules defend against brute force, credential stuffing, and simple DDoS scraping attacks.
AWS WAF Bot Control is a managed rule group that classifies traffic into categories: verified bots (Googlebot, Bingbot), scrapers, monitoring tools, and human traffic. You can configure different actions per category—allow search engine bots, challenge unknown bots with CAPTCHA, block malicious scrapers.
WAF Scope: CLOUDFRONT vs REGIONAL
WAF Web ACLs are scoped to either CLOUDFRONT (global, for use with CloudFront) or REGIONAL (for use with ALB, API Gateway, AppSync, or Cognito User Pools in a specific Region). CloudFront-scoped WAF ACLs must be created in the us-east-1 Region, regardless of where traffic originates, because CloudFront is managed from that Region.
This is an important exam gotcha: if you create a WAF Web ACL in eu-west-1 and try to attach it to CloudFront, the attachment fails. Always create CloudFront WAF ACLs in us-east-1.
Introduction to Lambda@Edge
Lambda@Edge lets you run Node.js or Python Lambda functions at CloudFront edge locations in response to CloudFront events. Functions run within milliseconds of the user's request, without routing traffic back to a central Region for processing.
Lambda@Edge functions are deployed to the us-east-1 Region but automatically replicated to all CloudFront edge locations globally. This means your code executes as close to the user as possible, enabling personalisation, authentication, and A/B testing at the edge with minimal latency overhead.
Lambda@Edge Trigger Points
Lambda@Edge functions can intercept CloudFront requests and responses at four points in the lifecycle:
- Viewer Request: after CloudFront receives the request from the viewer, before checking the cache—use for authentication, redirects, header manipulation
- Origin Request: after a cache miss, before forwarding to origin—use for URL rewriting, custom headers to origin
- Origin Response: after receiving the response from origin, before caching it—use for adding security headers, modifying response
- Viewer Response: before CloudFront sends the response to the viewer—use for adding/modifying response headers
Lambda@Edge vs CloudFront Functions
AWS offers two edge compute options with different trade-offs:
- CloudFront Functions: sub-millisecond execution, JavaScript only, extremely low cost (~1/6 the price), runs only at Viewer Request and Viewer Response events, 1 ms compute time limit, no VPC/network access
- Lambda@Edge: up to 30 seconds (Viewer) / 30 seconds (Origin) execution time, Node.js or Python, all four trigger points, can make network requests, has access to request/response bodies
Use CloudFront Functions for simple header manipulation, URL normalization, and cache key computation. Use Lambda@Edge for complex logic that requires network calls, longer computation, or origin-side processing.
Lambda@Edge Use Cases
Common Lambda@Edge patterns on the SAA-C03 exam:
- JWT validation at the edge: Viewer Request function validates an Authorization header; unauthorised requests return 401 without hitting the origin
- A/B testing: Viewer Request assigns users to A or B group (via cookie) and modifies the request to fetch
/a/page.htmlor/b/page.html - URL rewriting: Origin Request rewrites clean URLs to the actual file paths in S3
- Dynamic image resizing: Origin Request constructs a request to an image processing Lambda; Origin Response caches the resized image
- HTTP security headers: Viewer Response injects CSP, HSTS, X-Frame-Options headers
Lambda@Edge Limitations
Lambda@Edge has several restrictions compared to standard Lambda:
- Functions must be in us-east-1 Region
- No VPC support (cannot access resources in a VPC)
- No environment variables (embed configuration in function code or fetch from Parameter Store at cold start)
- Cannot use Lambda Layers
- Viewer event timeout: 5 seconds; Origin event timeout: 30 seconds
- Deployment package size limit: 1 MB (Viewer events) / 50 MB (Origin events)
These limitations make Lambda@Edge unsuitable for long-running computations, VPC-dependent operations, or functions that need dynamic configuration per deployment.
WAF + Lambda@Edge: Layered Security
WAF and Lambda@Edge serve different security roles and complement each other:
- WAF: signature-based attack blocking (SQL injection, XSS, known bad actors, rate limiting)—managed rules handle common attacks automatically
- Lambda@Edge: custom business logic security (JWT validation, session checks, access-token verification)—flexible but requires development effort
A defence-in-depth architecture: WAF blocks known attack patterns first; Lambda@Edge validates business-level authentication; CloudFront signed URLs/cookies restrict content access; OAC keeps S3 private. Each layer independently prevents a different class of attack.
Monitoring WAF and Lambda@Edge
Monitor your edge security layer with these tools:
- WAF logs: enable full request logging to S3, CloudWatch Logs, or Kinesis Firehose to see which rules match and what traffic is blocked
- WAF metrics:
BlockedRequests,AllowedRequests,CountedRequestsper rule in CloudWatch - Lambda@Edge logs: CloudWatch Logs groups are created in each Region where the function executes; use CloudWatch Insights to query across Regions
- CloudFront Real-Time Logs: stream access logs to Kinesis for immediate analysis (vs standard access logs which batch every few minutes)
Quick Check
Test your understanding of AWS Solutions Architect (SAA-C03) concepts from this lesson.
Lesson Recap
In this lesson you learned: AWS WAF blocks common web attacks at the CloudFront edge using managed and custom rule groups, Lambda@Edge runs custom code at four CloudFront trigger points globally, and CloudFront Functions offer sub-millisecond execution for simple viewer-side logic. WAF ACLs for CloudFront must be created in us-east-1. Next up we explore Application, Network, and Gateway Load Balancers.
Frequently asked questions
Is the “CloudFront with WAF and Lambda@Edge” lesson free?
Yes — the full text of “CloudFront with WAF and Lambda@Edge” is free to read here on the web, and the AWS Solutions Architect course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AWS Solutions Architect course, upgrade to CoddyKit PRO.
What will I learn in “CloudFront with WAF and Lambda@Edge”?
Attach AWS WAF to block common web attacks and run lightweight request/response transformations at the edge with Lambda@Edge. You practise AWS Solutions Architect with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AWS Solutions Architect?
No prior experience is required. AWS Solutions Architect on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “CloudFront with WAF and Lambda@Edge” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AWS Solutions Architect lesson?
Yes. Every AWS Solutions Architect lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- CloudFront Distributions and Origins
- Cache Behaviors and TTL Settings
- Signed URLs, Signed Cookies, and Geo-Restriction
- CloudFront with WAF and Lambda@Edge