Chatwithcloud logo

ChatWithCloud

AWS GenAI Tools

Create Route53 Cloudfront WWW Redirect To Base Domain

In this article, we'll provide a JavaScript (JS) code for creating a Route53 Cloudfront WWW redirect to a base domain (e.g., redirecting from www.example.com to example.com).

Code

Here is the JS code for the function. This script is written for AWS SDK for Node.js and makes use of Promises and async/await syntax.

const AWS = require('aws-sdk'); const route53 = new AWS.Route53(); const cloudfront = new AWS.CloudFront(); async function createRedirect() { const changeBatch = { Changes: [{ Action: 'CREATE', ResourceRecordSet: { Name: "www.example.com", Type: "A", AliasTarget: { DNSName: "<cloudfront_distribution_domain_name>", EvaluateTargetHealth: false, HostedZoneId: "Z2FDTNDATAQYW2" } } }] }; const params = { ChangeBatch: changeBatch, HostedZoneId: "<hosted_zone_id>" }; try { const data = await route53.changeResourceRecordSets(params).promise(); console.log(data); } catch (err) { console.error(err); } } createRedirect();

Detailed Code Explanation

The script starts by importing AWS SDK and initializing Route53 and Cloudfront services.

The createRedirect() function is defined next. This function creates a changeBatch object which details the record set to be created. Here, we are creating an A type Alias record for www.example.com, pointing to a Cloudfront distribution.

The params object wraps the changeBatch and includes the hosted zone id, which is where the record should be created.

The promise() call is made on the changeResourceRecordSets() function, which will asynchronously perform the record creation. The function either logs the data if the promise resolves successfully, or logs the error if the promise is rejected.

Finally, the createRedirect() function is called to execute the script.

Expected Output

The expected output of this script, in JSON format, would look like this:

{ "ChangeInfo": { "Id": "/change/C2682N5HXP0BZ4", "Status": "PENDING", "SubmittedAt": "Datetime", "Comment": "string" } }

Considerations & Caveats

Please note that this script assumes you already have a CloudFront distribution set up with a base domain configured. Also, take note that the Hosted Zone ID for Route 53 alias records pointing to a CloudFront distribution must always be "Z2FDTNDATAQYW2".

Required IAM Permissions

An AWS IAM user executing this script requires the following permissions:

Here's an example policy that grants these permissions:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "route53:ChangeResourceRecordSets", "route53:ListHostedZones" ], "Resource": "*" } ] }

FAQ





Related articles
Monitor and Notify When Approaching Service LimitsGet Current IAM Identity TypeScriptCalculate the Size of Each S3 Bucket and Find the One with the Most Data