Deploy a Website based on Geographic Location with AWS CloudFront and Lambda@Edge

Kübra Kuş
4 min readJun 4, 2024

--

Originally published at http://kubikolog.com on June 4, 2024.
You can visit the original for the Turkish version.

Today, I want to revisit a topic discussed in my recent article “Today’s Agenda: AWS CloudFront.” In that post, we delved into CloudFront in detail. Now, let’s explore how to deploy personalized website content based on geographic location using CloudFront and Lambda@Edge. Let’s get started! 🐸

Requirements:

First, you’ll need an AWS account and console access. The steps we’ll follow are:

  1. Create an S3 Bucket and Upload Static Content
  2. Create a Lambda@Edge Function
  3. Create a CloudFront Distribution
  4. Test the CloudFront Distribution

Let’s begin with the demo steps: 👇🏻

Steps:

1. Create an S3 Bucket and Upload Static Content

  1. Log in to the AWS Management Console.

2. Open the S3 service and create a new bucket.

  • Bucket Name: kubikolog-demo-website
  • Region: Select the region closest to you.

3. After creating the bucket, go into it and navigate to the Permissions tab.

4. Add the following bucket policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::kubikolog-demo-website/*"
}
]
}

5. Go to the Properties tab and in the Static website hosting section, check “Use this bucket to host a website.”

  • Index document: index.html

6. Save the following content as index.html on your computer, then upload it to the bucket:6. Aşağıdaki içeriği bilgisayarınızda index.html olarak kaydedip ardından Upload sekmesine gidelim ve index.html adlı basit bir HTML dosyası yükleyelim.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Geolocation Demo</title>
</head>
<body>
<h1 id="greeting">Welcome!</h1>
<p>This website uses CloudFront and Lambda@Edge to personalize content based on your location for kubikolog demo.</p>
</body>
</html>

2. Create a Lambda@Edge Function

  1. In the AWS Management Console, open the Lambda service.

2. Click the “Create function” button and fill in the fields as follows:

  • Function name: GeoGreetingFunction
  • Runtime: Node.js 20.x
  • Role: Create a new role with basic Lambda permissions

3. After creating the function, paste the following code into the Function code section and save the function:

exports.handler = async (event) => {
const request = event.Records[0].cf.request;
const response = event.Records[0].cf.response;
const headers = request.headers;

const country = headers['cloudfront-viewer-country'] ? headers['cloudfront-viewer-country'][0].value : 'unknown';

let greeting = 'Welcome!';
if (country === 'US') {
greeting = 'Hello World!!';
} else if (country === 'FR') {
greeting = 'Bonjour de la France!';
} else if (country === 'JP') {
greeting = 'こんにちは、日本から!';
}

const modifiedResponse = {
status: response.status,
statusDescription: response.statusDescription,
headers: response.headers,
body: response.body.replace('<h1 id="greeting">Welcome!</h1>', `<h1 id="greeting">${greeting}</h1>`),
bodyEncoding: 'text',
};

return modifiedResponse;
};

3. Create a CloudFront Distribution

  1. In the AWS Management Console, open the CloudFront service.

2. Click the “Create Distribution” button, select “Web,” and proceed.

3. In the Origin Settings section:

  • Origin Domain Name: Select your S3 bucket (kubikolog-demo-website.s3.amazonaws.com).
  • Origin Path: Leave blank.
  • Name: kubikolog-geo-origin (default).

4. In the Default Cache Behavior Settings section:

  • Viewer Protocol Policy: Select “Redirect HTTP to HTTPS.”
  • Lambda Function Associations: Under Origin Response, add the Lambda function you created (GeoGreetingFunction).

5. In the Distribution Settings section:

  • Price Class: Use Only North America and Europe (to keep costs low).
  • Alternate Domain Names (CNAMEs): Leave blank.
  • SSL Certificate: Default CloudFront Certificate (for TLS use).

6. Click the “Create Distribution” button to save.

4. CloudFront Dağıtımını Test Etme

4. Test the CloudFront Distribution

  1. Wait for the CloudFront distribution status to be Deployed (this may take a few minutes).

2. Copy the Domain Name of the distribution (e.g., d1234567890abcdef.cloudfront.net) and open it in a web browser.

If everything is configured correctly, your web page will display a personalized message based on the user’s geographic location. For example, users accessing from the US will see “Hello World!!”

By following these steps, you will have created a web application that delivers personalized content based on geographic location using AWS CloudFront and Lambda@Edge. This demo illustrates the integration of CloudFront with Lambda@Edge and the powerful capabilities this combination offers.

As we wrap up this article, I’d like to dedicate a song that evokes a range of emotions while you listen 🐸🦋

“Biraz neşe biraz hüzün, biraz öyle biraz da böyle”
(“A little joy, a little sadness, a bit of this, and a bit of that.”)

You can visit the original for the Turkish version.
Originally published at
http://kubikolog.com on June 4, 2024.

--

--