Blogs

CloudFront Functions: Increase Web Vitals Score by Serving Static Assets With a Cache Policy

Introduction

CloudFront functions are lightweight JavaScript functions that can be used to manipulate HTTP requests between your CloudFront distributions and your clients. It's as simple as that!

Why do you need CloudFront functions?

One use case is that when you're using S3 buckets and CloudFront to host your static website, you have the power to tailor and manage the requests and responses that traverse CloudFront. For instance, you can easily add additional HTTP headers like the Cache-Control header.

How can you use CloudFront functions to increase your website performance?

It's straightforward: create a CloudFront function to add to the Cache-Control HTTP header.

Quick Demo

  1. Run the PageSpeed Insights test and check your current website's score. (check the Performance tab)
  2. Log into your AWS account's console.
  3. Navigate to CloudFront.
  4. In the left panel, click on Functions.
  5. Click on Create Function.
  6. Enter the name of the function, for example, setCacheControl.
  7. Select cloudfront-js-2.0.
  8. Hit Create Function.
  9. You will notice some JavaScript code for your HTTP handler in the Build tab; replace it with the code below.
    function handler(event) {
    const response = event.response;
    const headers = response.headers;

    // Set the cache-control header

    headers['cache-control'] = {value: 'public, max-age=31536000'};

    // Return response to viewers
    return response;
    }
  10. Let's now use this function in our CloudFront distribution. To do so, navigate to the CloudFront service.
  11. Select your website's distribution.
  12. Navigate to the Behaviors tab.
  13. Click on Create Behavior
  14. In the Path pattern, enter the path of which assets should be cached, for example, /images
  15. Select the related S3 bucket in the Origin and Origin Groups drop-down list.
  16. Navigate to the bottom of the page to Function Associations. In the Viewer Response, select CloudFront Functions, then select the function we created earlier.
  17. Leave the other fields on their defaults and click on Save.
  18. Rerun the PageSpeed Insights test and notice the difference!

References

  1. Serve static assets with an efficient cache policy.
  2. Check your website's Web Vitals Score here.