Adding CDN caching to a Vite build

Content Delivery Networks or CDNs allow you to improve the delivery of your website’s static resources, notably through CDN caching. They do this by serving your content from edge locations around the world. When a user navigates to your website and your website requests resources from the CDN, the CDN forwards that request to the closest edge location. If that location has the requested resources, either from this user’s previous visit or from someone else, the content will be served from the cache. If not, the CDN will request, store, and serve the content from your underlying domain.

There are tons of CDNs out there, but for this post we’re using AWS CloudFront. We’ll look at setting up a CloudFront distribution to serve all of our website’s assets: JavaScript files, CSS files, font files, etc. Then we’ll see how to integrate it into a Vit build. If you want to learn more about Vite, I have an introduction here.

Bạn Đang Xem: Adding CDN Caching to a Vite Build | CSS tricks

Set up a CloudFront CDN distribution

Let’s jump right in and set up our CloudFront CDN distribution.

For any serious project, you should set up your serverless infrastructure with code using something like the Serverless Framework or AWS’s CDK. But to keep things simple, here we set up our CDN using the AWS console.

Go to the CloudFront home page. At the top right you should see an orange button to create a new distribution.

The build screen has a ton of options, but for the most part the default choices are fine. First and foremost, add the domain where your resources reside.

CloudFront CDN distribution creation screen.

Next, scroll down and find the Response header policy drop-down menu and select “CORS-With-Preflight”.

CloudFront response header settings.

Finally click on Create distribution button below and hopefully you will see your new distro.

CloudFront CDN distribution overview screen.

Integrating the CDN into Vite

Xem Thêm : Mobile Legends Redeem Code Updates April 1st

It’s one thing to have our CDN set up and ready to serve our files. But it’s another thing for our side to know how to request them from our CDN. I’ll go through the integration with Vite, but other build systems like Webpack or Rollup will be similar.

When Vite builds our website, it maintains a “chart” of all the JavaScript and CSS files that import different parts of our website and injects the appropriate ones <script> keywords <link> tags or import() Instructions to load what is needed. What we need to do is tell Vite to request these assets from our CDN during production. Let’s see how.

Open yours vite.config.ts File. First we need to know if we are on the live site (production) or in development (development).

const isProduction = process.env.NODE_ENV === "production"; 

This works because Vite sets this environment variable when running vite buildwhat we do for production as opposed to dev mode with reloading hot modules.

Next we tell Vite to pull our assets from our CDN like this by using the base Property of our configuration object:

export default defineConfig({
  base: isProduction ? process.env.REACT_CDN : "",

Be sure to set yours REACT_CDN Environment variable to the location of your CDN, which in this case is the location of our CloudFront distribution. Mine looks something like (but not exactly) this:

https://distributiondomainname.cloudfront.net

Pay attention to your VitePWA settings!

As a final piece of cleaning, if you’re using the VitePWA plugin, make sure to reset yours base property like this:

VitePWA({
  base: "https://css-tricks.com/",

Otherwise yours web.manifest File will have invalid settings and cause errors.

Let’s see how the CDN works

Xem Thêm : What is Blogger’s job? Why do we use Blogger?

Once everything is set up, navigate to your website and check any network requirements for your script or CSS files. For starters, the log should be h2.

Viewing the assets served via CDN caching in DevTools.  Each filename contains a unique random string of letters and numbers.

From there you can take a look into the response headers of one of these files and you should see some CloudFront data there:

Screenshot of a response header.

cache busting

It’s hard to talk about CDNs without mentioning cache busting. CDNs like CloudFront have features to manually “eject” items from the cache. However, with assets created by Vite, we get this “for free” because Vite adds fingerprints, or hash codes, to the filenames of the assets it creates.

So Vite could spin one home.js file inside home-abc123.js during a build, but if you then modify and rebuild that file, it might become home-xyz987.js. This is good because it “destroys the cache” and doesn’t cache the newly created file, requiring the CDN to contact our host domain for the actual content.

CDN caching for other static assets

JavaScript, CSS, and font files aren’t the only types of assets that can benefit from CDN caching. If you have an S3 bucket that you serve images from, consider setting up a CloudFront distribution for it as well. There are options specific to S3 that make building a breeze. Not only do you get the same edge caching, but you also get HTTP/2 responses, which S3 doesn’t offer.

Advanced CDN Practices

Integrating a CDN here was fairly easy, but we’re only enjoying a fraction of the potential benefits. Right now, users navigate to our app, our server serves our root HTML file, and then the user’s browser connects to our CDN to start fetching all of our static assets.

Additionally, we want to serve our entire website from a CDN. This allows it to communicate with our web server when needed for non-static and non-cached assets.

Conclusion

CDNs are a great way to improve your website’s performance. They offer edge caching and HTTP/2 out of the box. Not only that, they’re also relatively easy to set up. Now you have a new tool in your belt that can both set up a CDN and integrate with Vite.