I recently wanted to setup a link to redirect people who either clicked on a link or scanned a QR code to be taken to their relevant app stores on IOS or Android for my React Native App. I’m sure theres a few websites out there that do this, but I preferred to have it under my domain, and didn’t want to pay for it.
I thought I’d give it a go using CloudFront functions. It was a bit tricky to get setup using CDK but I’m happy with how it turned out, so I thought I’d share in case anyone was looking to setup a similar thing.
You may be thinking, is setting up a whole CDN a bit overkill for a redirect based on a user agent header? Probably. But its not actually that much code , users wont have to wait for a cold-start or experience distance latency, and CloudFront is pay as you go. So why not.
I’m going to be writing the CDK code in Typescript, and I won’t be diving into setting up Route53, or a CDK project as theres plenty of tutorials out there on those topics.
CDK Stack
First thing to note — make sure this stack is deployed in us-east-1 as that’s where CloudFront functions/distributions must be deployed.
First in the CDK stack we want to add something like this:
In the stack we’re creating a cloudfront distribution, s3 bucket, acm certificate and cloudfront function.
The bucket doesn’t actually do anything here, but the distribution needs an origin of some kind. Note we’re setting the cloudfront function as the Viewer Request which means it will be triggered before the request ever gets to the origin.
Since we’ll be setting up the function to redirect the request, the request never reaches the bucket.
The other key part of the configuration is the line:
originRequestPolicy:
cloudfront.OriginRequestPolicy.ALL_VIEWER_AND_CLOUDFRONT_2022,
This tells cloudfront to forward headers to our function that we’ll need in order to redirect based on the device type. You can read more about it here:
CloudFront Function
Next we need the js file that we pointed the CloudFront function to in the stack:
Make sure to line up the path to the function with whatever you set it as in the stack. In our example this file is at src/functions/app-store-redirect.js
The function is making use of the CloudFront headers that we specified to be forwarded to the origin. Customise this to your needs as it can probably be used for more than this simple use case. Make sure to redirect in every scenario unless you’ve setup the bucket to handle requests, otherwise you’ll get an error.
Route 53
Finally we need to create a record to tell Route53 to point whatever domain/path we want to the cloudfront distribution.
I just used the console to create the record using an alias. Read here about how to do that here:
AWS Route 53 CloudFront Distribution Docs
And thats it, if users are on an iPhone they’ll be taken to the IOS App Store and if they’re on an Android the Google Play Store.
Hope you found this useful.
Top comments (0)