AWS Lambda@Edge: Using CloudFront Functions to Build Serverless Global Applications
Article cover image

AWS Lambda@Edge: Using CloudFront Functions to Build Serverless Global Applications

?? Hello there! Welcome to The Serverless Spotlight.

In this week's edition, we'll examine how to leverage Lambda@edge to deliver low-latency serverless applications globally and enhance their user experiences.


Have you ever needed to customize the output of a function based on the localization/region where the function is invoked?

Often times this is a necessity for applications with:

  • multi-language features
  • region-customized content
  • compliance needs?
  • And many other requirements that can change from country to country.

These capabilities are made possible and simple for you with Lambda@Edge.

What Is Lambda@Edge?

Lambda@Edge is a feature of AWS Lambda that allows you to run serverless functions at AWS edge locations worldwide.

These functions are executed in response to events coming from Amazon CloudFront. This allows you to manipulate incoming requests and responses and customize content delivery.

The key advantage with Lambda@Edge functions is that you significantly reduce the latency of function responses by having code run closer to users - even closer than a regular function being run in the same region as a user.

Unlike regular Lambda functions run in a specific AWS region, a Lambda@Edge function operates in an AWS edge location which ensures the code is executed much closer to the user.

This minimizes round-trip latency, increases performance as well as enhances security.

Some Use Cases for Lambda@Edge

Some benefits and typical use cases of using Lambda@Edge include:

  • Dynamic content generation: with Lambda@Edge you can serve dynamic content such as personalized web pages based on a user's country or language (more in demo below).
  • URL Rewriting/Redirection: you can modify incoming URLs or requests to route traffic to different endpoints based on localization.
  • User authentication: with Lambda@Edge you can authenticate users at the edge before routing requests to the backend. This minimizes unnecessary processing of unauthenticated users.
  • A/B Testing: you can customize and serve different versions of web pages based on location for testing purposes.

How Lambda@Edge Works

When a user makes a request to a website, CloudFront routes the request to the nearest edge location.

At this edge location, Lambda@Edge runs custom code before (or after) the server processes the request.

Then the Lambda@Edge function can generate dynamic content or redirect traffic based on how you configure it.

This processed response is then delivered to the user, ensuring the lowest latency possible.

Lambda@Edge Demo

The most typical use cases include localization with Lambda@Edge. However, Lambda@Edge can be used for so much more as we saw above.

However, below let's take a look at an example of how we would use Lambda@Edge to serve customized web pages to users based on the country in which they request a web page.

In this example, let's assume we are serving a static website that has static content such as HTML, CSS, JS and images files in an S3 bucket.

We'll assume you also have a CloudFront distribution configured already.

The last step is to create the Lambda@Edge function and serve customized, localized dynamic content.

In the AWS Lambda console, create a new function.

Select the Author from scratch option. Name it how you like and select the Node JS 20.x runtime.


Creating a new Lambda function

Once you create the function, on the function page, head to the Code Source section below and copy the following code in the text editor:

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

    const language = headers['accept-language'] ? headers['accept-language'][0].value.split(',')[0] : 'en';
    
    let personalizedPage;
    
    // here we'll serve different web pages based on user's language
    if (language.startsWith('fr')) {
        personalizedPage = '/fr/index.html';
    } 
    else if (language.startsWith('es')) {
        personalizedPage = '/es/index.html';
    } 
    else {
        personalizedPage = '/en/index.html';
    }

    request.uri = personalizedPage;
    return request;
};        

Save the code and deploy it.


Lambda function Code source editor

Now we need to deploy the function to Lambda@Edge.

At the top of the function page, click on the Add Trigger button.

From the dropdown option, choose "CloudFront". You'll see the option to deploy to Lambda@Edge.


Adding a trigger to Lambda function to be able to deploy it to Lambda@Edge

Click on the button Deploy to Lambda@Edge.

Under CloudFront Event, select the Viewer Requests to modify requests before they reach the origin server - as we want in this case of request routing based on the user's localization.

Select a CloudFront distribution and check the Confirm deploy to Lambda@Edge.


Creating a trigger to deploy function to Lambda@Edge

Once you click Deploy, your function will be deployed to and executed by Lambda@Edge.

Users can now visit your website using your CloudFront distribution URL and the localization processing will be done automatically by this Lambda function.

Conclusion

Lambda@Edge is a feature that allows serverless functions to run at AWS edge locations globally, reducing latency by executing code closer to users.

It integrates with Amazon CloudFront to enable functions to modify requests and responses for tasks such as dynamic content generation, URL redirection, user authentication, and A/B testing.

In this article, we took a look at a brief demo of using Lambda@Edge to serve localized web pages based on user language/region and explained the process of setting up and deploying a Lambda function to Lambda@Edge.


?? My name is Uriel Bitton and I hope you learned something in this edition of The Serverless Spotlight

?? You can share the article with your network to help others learn as well.

?? If you want to learn how to save money in the cloud you can subscribe to my brand new newsletter The Cloud Economist.

?? I hope to see you in next week's edition!

Maroosha Shahid

Web Developer | Transforming Ideas into Digital Reality

6 个月

Geographic personalization boosts relevance, impacts experience positively.

Leandro Santos

Software Architect | Cloud Architect | Solutions Architect

6 个月

Insightful

要查看或添加评论,请登录

Uriel Bitton的更多文章

社区洞察

其他会员也浏览了