Last updated on October 3, 2023
In this article, we will guide you through the process of setting up a CloudFront Function for your CloudFront distribution. We’ll walk you through a scenario where we use CloudFront Functions to redirect users to different content based on their device type. By the end of this guide, you’ll gain a clear understanding of how CloudFront Functions can benefit your specific use case.
Creating an S3Â Bucket
This bucket will simply serve as a mock origin for the CloudFront distribution that we’ll be creating. If you have some test buckets lying around, you may use them instead and skip this step.Â
- Navigate to the Amazon S3 service in the AWS Management Console.
- Click on Create bucket.
- Provide a unique name for your bucket.
- Choose a region.
- Click on ‘Create’.
Creating the CloudFront Function
- On the left-hand side of the CloudFront Console, click Functions.
- Click Create Function.
- Name your function, then click Create Function.
- On the IDE, copy and paste the code found on this Github link.
- Select the Publish tab, then click Publish Function.
Creating an Origin Request Policy
- On the left-hand side of the CloudFront Console, click Policies.
- Select Origin request.
- Under Custom Policies, click Create origin request policy.
- Enter CloudFront-Is_Headers for the name.
- In the Origin request settings, select All viewer headers and the following CloudFront header, then add the following headers:
-
CloudFront-Is-Desktop-Viewer
- CloudFront-Is-Mobile-Viewer
-
- Finally, click Create.
Creating a CloudFront Distribution
- On the left-hand side of the CloudFront Console, click Distributions, then click on the Create Distribution button.
- In the Origin settings section, for Origin Domain Name, select the S3 bucket you created earlier from the drop-down list.
- Leave the rest of the settings in this section as default.
- Scroll down to the Default Cache Behavior Settings. For Cache Policy, select CachingOptimized from the drop-down list.
- For Origin Request Policy, select the custom policy you created earlier from the drop-down list.
- Scroll down to the Functions Association. Click on Add function.
- In the function type dropdown, select CloudFront Functions.
- In the function ARN/Name, choose the CloudFront function you created earlier.
- Finally, click Create Distribution.
Verification
Now comes the fun part, verifying our function. Once your CloudFront distribution is up and running, copy its distribution URL and access it using your browser. If you access the URL through a desktop, you should be taken to a GIF showing a person at a desk. On the other hand, if you access the URL on a mobile device, you should be taken to a GIF representing a mobile phone. Congratulations! You’ve successfully set up and tested an Amazon CloudFront Function for device-based content personalization.