Make Your Own Little (Easy-to-Update) CDN

By, uh, using other people’s CDNs.

Step 1) Make a GitHub Repo

And put files in it that you want CDNized URLs to.

I don’t think GitHub likes it when you use them as a CDN. They provide a “raw” URL to files, but they serve the wrong content-type headers, so we can’t just use that.

This JavaScript file should have application/javascript as the header. Probably matters.

Step 2) Link to them from jsDelivr instead

Use a URL in a format like this:

https://cdn.jsdelivr.net/gh/{GITHUB_USERNAME}/{REPO_NAME}/{PATH_TO_FILE}

So for my file:

https://cdn.jsdelivr.net/gh/chriscoyier/personal-cdn/console-log.js

Now it’s:

  1. On a proper CDN
  2. Has the right content-type

This is a real documented feature.

Works great:

Step 3) Now your update strategy is just to update the file on GitHub

You can do that right on GitHub.com. Not the mobile app for some reason? I don’t think? But oh well.

ARGGGGG Oh no! Caching!

So this URL:

https://cdn.jsdelivr.net/gh/chriscoyier/personal-cdn/console-log.js

That ain’t gonna break cache. It’s cached out the wazoo forever. Unless you have access to some secret purging mechanism.

There is something of a solution though, and it’s to:

  1. Update the code
  2. Then publish a versioned release
  3. Then either link to a release or link to the latest published release:
https://cdn.jsdelivr.net/gh/chriscoyier/personal-cdn@1.0.0/console-log.js

https://cdn.jsdelivr.net/gh/chriscoyier/personal-cdn@latest/console-log.js

That’s easy enough to do right on GitHub.com as well:

This works and honestly, it’s probably the adult way to handle this. If you want to hand out a URL that always has the latest code to people, use the industry-standard-ish @latest language, and publish releases.

Other ideas?

Hook up the GitHub repo to a published Netlify site. Then when you commit the change, Netlify will pick it up and deploy it, and Netlify will break the cache for you. So mayyyyybe slightly easier? Just adds more tooling to the idea, maybe cost if it’s massively trafficked, and a smidge of deploy slowdown (barely, since probably zero build process).

CodePen also has pretty sweet Asset Hosting as a feature as well, I might add. But I’m afraid it isn’t exactly designed to be your personal CDN. We’ve seen situations where absolutely massive traffic comes into individual files, and the Cloudflare protection bots pick it up and captcha protect that file. That’s a feature I think we’ll leave in place, knowing we haven’t designed the feature to be a public CDN anyway.

2 responses to “Make Your Own Little (Easy-to-Update) CDN”

  1. Mykal Machon says:

    Great read! Was cool to watch this concept come together a bit in the d-d-d-discord.

    I have a few JS utilities that I use across a bunch of sites that would be great for this flow.

Leave a Reply

Your email address will not be published.