DEV Community

Cover image for Dynamically Modifying CloudFront Origin for Country-Specific and A/B Testing
Avinash Dalvi for AWS Community Builders

Posted on • Originally published at internetkatta.com

Dynamically Modifying CloudFront Origin for Country-Specific and A/B Testing

Hey Devs,

As a dedicated developer, I'm always on the lookout for more efficient ways to implement feature development. However, it's equally important to ensure that the features I build are genuinely beneficial for users. This is where A/B testing comes into play—it helps validate what truly resonates with users.

Previously, I was familiar with A/B testing using Google Analytics and custom logic to direct traffic to specific features. However, I sought a more seamless and scalable approach that didn't rely on additional infrastructure. As re:Invent approached, my focus wasn't solely on DevOps updates; I was actively searching for innovations that could simplify A/B testing and enhance feature development.

This led me to explore whether AWS had introduced any new capabilities to streamline this process. When I came across the recent update to Amazon CloudFront, allowing origin modifications using CloudFront Functions, I realised its potential in dynamically routing users based on key attributes like location or device type.

Amazon CloudFront recently introduced support for modifying the origin using CloudFront Functions, enabling developers to dynamically route requests to different origins based on user attributes such as country, device type, or other request headers. This feature unlocks new possibilities for global content delivery, including country-specific websites, A/B testing, and device-based content optimization.

This update immediately caught my attention as I was in the middle of preparing for the re:Cap event. It felt like the perfect opportunity to explore its real-world applications.

The Story Behind This Update

As part of AWS re:Invent preparations, AWS announced a Pre-re:Invent update on November 21, 2024, introducing new CloudFront capabilities. In preparation for the re:Cap event on January 6, 2025, I explored these new capabilities to showcase them in demos. When I came across this update, I decided to do a deep dive into CloudFront Functions and explore how it could be leveraged for dynamic origin selection. This led me to experiment with different use cases like country-based content delivery, A/B testing, and device-specific optimisations. Through this exploration, I realized how impactful this update could be for developers optimising global content distribution.

Why Modify CloudFront Origin Dynamically?

Traditionally, CloudFront distributions have a fixed origin (an S3 bucket, EC2 instance, or any HTTP endpoint). However, with CloudFront Functions, we can dynamically select the origin based on request attributes, such as:

  • User’s country: Serve country-specific content from different S3 buckets or servers.

  • A/B Testing: Route a percentage of traffic to different versions of a website or application.

  • Device Type: Serve optimised content for mobile or desktop users.

How It Works

CloudFront Functions allow lightweight JavaScript-based logic to run at the viewer request stage, enabling modifications to the request before it reaches the origin. One key function is request.updateRequestOrigin(), which allows us to change the request origin dynamically.

Example: Changing Origin Based on User’s Country

For a country-specific website, we can use CloudFront-Viewer-Country header to decide which S3 bucket or server should serve the request.

Step 1: Create a CloudFront Function

You can create a CloudFront Function from the AWS Management Console or AWS CLI. Below is a sample function to modify the origin based on the user’s country.

Step 2: Deploy the CloudFront Function

  1. Go to AWS CloudFront Console → Select CloudFront Functions

  2. Create a new function and name it (e.g., ModifyOriginBasedOnCountry)

    You can choose any runtime but preferred one to use latest runtime.

  3. Paste the JavaScript code and publish the function

    function handler(event) {
        var request = event.request;
        var headers = request.headers;
    
        // Extract country code from CloudFront-Viewer-Country header
        var country = headers['cloudfront-viewer-country'] ? headers['cloudfront-viewer-country'].value : 'US';
    
        // Define origin mapping based on country
        var origins = {
            'US': { domainName: 'us-content.example.com' },
            'IN': { domainName: 'in-content.example.com' },
            'UK': { domainName: 'uk-content.example.com' }
        };
    
        // Default to US if no specific origin is found
        var newOrigin = origins[country] || origins['US'];
    
        // Update the origin
        request.updateRequestOrigin(newOrigin);
        return request;
    }
    

  4. Associate the function with the desired CloudFront distribution at the viewer request stage.

  5. Make sure to publish function whenever make changes.

Step 3: Test the Function

To test country-specific content delivery, you can use any VPN-based proxy site like https://proxyium.com to browse the website from different locations. This will allow you to verify if the CloudFront function is correctly routing requests based on the user's country. Or Use curl to simulate requests from different countries by setting the CloudFront-Viewer-Country header.

curl -H "CloudFront-Viewer-Country: IN" https://your-cloudfront-domain.com
Enter fullscreen mode Exit fullscreen mode

If implemented correctly, users from different regions will be routed to the appropriate origin. Same for can be tested for device specific using browser device testing under developer tool or test it on different physical devices.

Other Use Cases

1. A/B Testing

Modify the function to route a percentage of traffic to different origins for testing purposes.

var randomValue = Math.random();
if (randomValue < 0.5) {
    request.updateRequestOrigin({ domainName: 'experiment.example.com' });
}
Enter fullscreen mode Exit fullscreen mode

2. Device-Based Content Routing

Use the User-Agent header to route requests based on mobile or desktop access.

var userAgent = headers['user-agent'].value.toLowerCase();
if (userAgent.includes('mobile')) {
    request.updateRequestOrigin({ domainName: 'mobile-content.example.com' });
}
Enter fullscreen mode Exit fullscreen mode

Live demo

Summary

With the new updateRequestOrigin functionality in CloudFront Functions, developers can build highly customisable and dynamic content delivery strategies. Whether it's serving country-specific content, conducting A/B tests, or optimising content for different devices, this feature brings greater flexibility to AWS CloudFront.

🚀 Start leveraging CloudFront Functions today to optimise your content delivery!

I hope this blog helps you to learn. Feel free to reach out to me on my Twitter handle @AvinashDalvi_ or leave comment on the blog. Stay tuned for more learning.

References

Top comments (0)