Fast and Secure Frontend Serving with AWS CloudFront CDN
Tags: webdev, javascript, programming, aws
Published: 2022-08-29 16:35:00

Modern frontends are blazingly fast and responsive. Moreover, it requires specialized tools and platforms to deliver at scale. One such platform is AWS CloudFront, a CDN (Content Delivery Network), highly customizable.

So, in this article, I will take you through 6 best practices to optimize CloudFront for fast and secure frontend serving. Let's get started.

---

## 1. Caching Frontend Assets using the CDN

<figure>
<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gj5307eutstgkp7a4sa2.png" alt="Fast and Secure Frontend Serving with AWS CloudFront" style="width:100%">
<figcaption align = "center"><b>Reference: <a href="https://aws.amazon.com/blogs/architecture/a-case-study-in-global-fault-isolation" target="_blank">A Case Study in Global Fault Isolation</a></b></figcaption>
</figure>


AWS CloudFront CDN acts as the middle man between your frontend hosting and the users. With CloudFront, you can cache HTML, CSS, JavaScript, and images. Since the cache is closer to the user, the content will be delivered with minimal latency.

You can also configure CloudFront with origin failover for fallback handling in scenarios requiring high availability.

And the best advantage is that AWS CloudFront natively supports integrating Amazon S3, where you can host your frontend artifacts. Besides, you can host your frontend anywhere and still serve through AWS CloudFront.

For more details, refer to the AWS article on [Using CloudFront to Serve Static Websites](https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serve-static-website/).

---

## 2. Using Cache Invalidation Upon New Deployments

It is always good to invalidate the cache when performing a new deployment to prevent browsers from retrieving old file versions from the cache.

AWS CloudFront now supports fast cache invalidation, allowing you to deploy updates to your SPA instantly while still having the benefit of CDN caching.

> Note: As a practice, you could invalidate only the files that are modified in your deployment. For instance, if you use Webpack with default configuration, you only need to invalidate the index.html since each modified JS and CSS will have new file names.

You could also use AWS Amplify to simplify your deployments and cache invalidations with built-in optimizations.

---

## 3. Use Private S3 Buckets and Origin Access Identity for Security

If you’re using an Amazon S3 bucket as the origin for a CloudFront distribution, it’s essential to restrict public access to S3.

Restricting access prevents someone from bypassing CloudFront and accessing content that you want to keep secure via the Amazon S3 URL.

**You will wonder why does it matter since it’s frontend assets that are meant to be public?** The reason is that serving through AWS CloudFront comes with more control, where you can set Web Application Firewall (WAF) rules and other restrictions on your content for security.

---

## 4. For Hash-less URLs, use Lambda@Edge

Lambda@Edge allows you to intercept HTTP requests that go through CloudFront. These functions run in CloudFront Edge Locations closer to the user, making it faster to respond or act upon content at transit.

Some common use cases of Lamda@Edge are,

- Dynamically generate custom content based on request or response attributes, such as resizing images based on request attributes.
- To add logic to requests and responses, such as creating pretty URLs and managing authentication and authorization for origin requests.
- To increase the cache hit ratio, resulting in improved application performance by avoiding latency caused by a cache miss.
- To handle custom authentication and authorization.

If you need to explore more about Lamda@Edge, you can look through the [documentation](https://aws.amazon.com/blogs/networking-and-content-delivery/lambdaedge-design-best-practices/) provided by AWS.

> Note: If you need simple needs like using only Hashless URLs, there is a simple follow-up approach. Since the objective is to serve the index.html even a user directly goes to a route, we can set the CloudFront error handling to server the index.html if S3 returns the error “resource not found” with error code 404.

---

## 5. Using Compression (Brotli, Gzip)

Another best practice I encourage you to follow is using a compression method. With AWS CloudFront, you can serve your applications using Brotli or GZip and reduce content download speed drastically.

Faster downloads, especially for JavaScript and CSS files, can result in the faster rendering of your SPA.

Furthermore, because CloudFront data transfer costs are based on the total amount of data served, serving compressed files is less expensive than serving uncompressed files.

Brotli is a widely used lossless compression algorithm that frequently outperforms Gzip in terms of compression ratio. Compared to Gzip, CloudFront’s Brotli edge compression results in up to 24% smaller file sizes.

Compression features can be enabled via the CloudFront Console, SDK, and the CLI. You need to set EnableAcceptEncodingGzip to true to return Gzip compressed objects and EnableAcceptEncodingBrotli to true to return Brotli compressed objects. CloudFront will use Brotli when the viewer supports both formats.

The Chrome and Firefox web browsers support Brotli compression only when the request is sent using HTTPS. Brotli is not supported with HTTP requests in these browsers.

## 6. Using Versioned File Names

When performing a new deployment, you can either invalidate files or give them versioned file names to control the versions of files served by your distribution. If you frequently update your files, it is best to use file versioning.

Versioning gives you better control over the content that CloudFront serves. slider_v1.js, image_v1.jpg are some example file versioning names you can use.

- Versioning makes it easier to analyze the effects of file changes because CloudFront access logs include file names.
- Versioning enables different versions of files to be served to different users.
- Versioning simplifies rolling back and forth between file revisions.
- The cost of versioning is lower. You must still pay CloudFront to transfer new versions of your files to edge locations, but you don’t have to pay for invalidating files.

---

## Conclusion

No matter how well you design and develop applications, users will be less attracted if it is not performing well. Using AWS CloudFront, you could address most of the performance and security challenges that affect your application frontend.

Therefore, I invite you to try out AWS CloudFront and follow these practices to speed up and secure your frontends at scale.

Thank you for reading!