There are 4 phases between your end users and original servers as the following:

- After CloudFront receives a request from a viewer (viewer request)
- Before CloudFront forwards the request to the origin (origin request)
- After CloudFront receives the response from the origin (origin response)
- Before CloudFront forwards the response to the viewer (viewer response)
There are 2 ways so far for you to manipulate content that CloudFront delivers, which are CloudFront Functions and Lambda@Edge.
Take Lambda@Edge as example, you could consider implementing a Lambda function at the 'Origin Request' phase where early hints would be sent to allow clients to start preloading resources. It is feasible to use the Lambda function to generate an HTTP response that CloudFront returns directly to the viewer without forwarding the response to the origin. The following is a simple example:
import json
def lambda_handler(event, context):
# Get the response object from the event
response = event['Records'][0]['cf']['response']
# Define preload resources
preload_resources = [
'</styles/main.css>; rel=preload; as=style',
'</scripts/main.js>; rel=preload; as=script'
]
# Join the preload resources with commas and add them to the "Link" header
link_header_value = ', '.join(preload_resources)
response['headers']['link'] = [{'key': 'Link', 'value': link_header_value}]
# Return the modified response
return response
A brief about the difference between Lambda@Edge and CloudFront Functions. For more details, please refer to here.
|
CloudFront Functions |
Lambda@Edge |
Programming languages |
JavaScript (ECMAScript 5.1 compliant) |
Node.js and Python |
Event sources |
Viewer request Viewer response |
Viewer request Viewer response Viewer response Origin request Origin response |
Scale |
10,000,000 requests per second or more |
Up to 10,000 requests per second per Region |
Function duration |
Submillisecond |
Up to 5 seconds (viewer request and viewer response) Up to 30 seconds (origin request and origin response) |
Maximum memory |
2 MB |
128 – 3,008 MB |
Maximum size of the function code and included libraries |
10 KB |
1 MB (viewer request and viewer response) 50 MB (origin request and origin response) |
Network access |
No |
Yes |
File system access |
No |
Yes |
Access to the request body |
No |
Yes |
Access to geolocation and device data |
Yes |
No (viewer request) Yes (origin request, origin response, and viewer response) |
Can build and test entirely within CloudFront |
Yes |
No |
Function logging and metrics |
Yes |
Yes |
Pricing |
Free tier available; charged per request |
No free tier; charged per request and function duration |
Here are some examples how you implement CloudFront Functions and Lambda@Edge with CDK.
- https://github.com/aws-samples/amazon-cloudfront-functions
- https://github.com/aws-samples/ab-testing-at-edge