How to serve static files from GitHub

How to serve static files from GitHub

Julien Danjou

Like many developers out there, you might use GitHub to store your source code. When you're building something pretty simple like a Web application, HTML files, JavaScript code, CSS stylesheets, etc., it could be useful to directly distribute your file through HTTP.

The Naive Approach

You probably tried the first simple approach, which is using GitHub directly as your content distributor. You could use an URL such as https://raw.githubusercontent.com/twbs/bootstrap/main/js/src/button.js to include the JavaScript file as part of your Web site.

Except that won't work. A good reason for it to fail is that GitHub does not set the right Content-Type header according to the file type.

$ http --headers head https://raw.githubusercontent.com/twbs/bootstrap/main/js/src/button.js | grep '^Content-Type'
Content-Type: text/plain; charset=utf-8

The file type ain't text/plain for sure. It should be application/javascript, and the fact that it's not returned correctly will prevent your browser from loading it for security reasons.

Statically to the Rescue

Statically is a content delivery network (CDN) that can serve files directly from GitHub, GitLab, or Bitbucket. You don't need to create any account to use Statically, and the service is free — though you can donate to sponsor them — which makes it straightforward to use.

To use Statically, simply replace the https://raw.githubusercontent.com prefix in your GitHub URL by https://cdn.statically.io/ghand you're done.

$ http --headers head https://cdn.statically.io/gh/twbs/bootstrap/main/js/src/button.js | grep '^Content-Type'
Content-Type: application/javascript; charset=utf-8

Serving the same file through Statically returns the correct Content-Type this time, allowing it to be loaded by a Web browser.

Caveats

Statically caches files for one year, except if the files are retrieved from a branch named main, master or dev — in that case, they are only cached for one day. This is important to notice as you might get crazy while testing your files as they are not reloaded from GitHub but are served from the cache.

A caching delay this long might not be a problem for resources you don't update often. However, if it is an issue, you should replace the branch name in the URL with a commit SHA id, e.g., https://cdn.statically.io/gh/twbs/bootstrap/85208ae5570aeefe4e94c1ceb29ca3b6ffdf83a1/js/src/button.js.

Use Case

For Mergify, we used this technique to embed our annoying cookies consent popup on our Web site.

The code is made of a JavaScript and a CSS file and is hosted on GitHub. With Statically, we've been able to embed the files directly without deploying them anywhere else. We can git push our changes and see them appear on our website 24 hours later (or before if we change the URL 😉).