CloudFront Functions - dynamic switching between origins
You can switch between different applications sharing the same URL in CloudFront. The use case I have a web app served using CloudFront from S3. I need a mechanism to seamlessly replace this app with another one, served from a different S3 bucket, but with the same URL. The bottom line is to switch apps under the hood without redeploying the stack so users won't really notice a switch.…
CloudFront Functions enable dynamic routing between different applications that share the same URL. The example case involves a web application hosted on CloudFront using Amazon S3 as the origin. The goal is to switch between two versions of the application - AppOne and AppTwo - without redeploying the infrastructure, ensuring a seamless experience for users.
A CloudFront Function is implemented to dynamically select the appropriate origin based on a specific parameter value stored in the CloudFront KeyValueStore. When managing requests and responses in CloudFront, two primary options are available: CloudFront Functions and Lambda@Edge. Lambda@Edge provides access to Node.js or Python runtime close to the user, enabling integration with AWS services, whereas the CloudFront Function operates on every request with a restricted JavaScript runtime, offering low latency.
In this implementation, a dummy setup is created with CloudFront serving two separate web applications, AppOne and AppTwo, each with its own behavior and S3 origin. Initially, the default behavior is set to direct traffic to AppOne. A CloudFront Function, named OriginSwitchFunction, is created to determine which origin to use based on the parameter value stored in the KeyValueStore.
The function reads the parameter from the KeyValueStore, retrieves the corresponding origin ID, and alters the request to route traffic accordingly.
To complete the setup, a KeyValueStore named OriginSwitchKvs is created and associated with the CloudFront Function. The function itself is then linked to the default behavior of the web application, allowing for dynamic origin switching. Upon deploying the template, users can test the functionality by setting the parameter to "appOne" or "appTwo" and observing the application switch without any noticeable changes in their browsing experience.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.