Cache busting CSS/JS files

I am not sure if this is possible with Hugo. I have added custom query strings to my CSS and JS files in templates which I change manually via params.toml to allow purging when external hosts build the site (like Cloudflare pages). However, I would like to automate this process and have the query string change only when a (CSS or JS) file is modified (in local and pushed to Github) so that a site like Cloudflare pages detects the file has changed and updates the query string, but does not change the query string if the file has not been edited. Is this possible to achieve?

Basically the term you are looking for is called cache busting assets.

The general Idea is to use a timestamp with the Unix function.

OR

If you are using Hugo Pipes you can fingerprint the assets.

Also see this post:

P.S. A support ticket is best when it is tagged as such.

1 Like

I am not a dev. Sorry. Just a Jekyll to Hugo user who knows their way around following docs to get things done.

You can surely select the support tag when opening a forum topic.
Thank you.

OOh. That…I sometimes forget to do that. You’re right.

I tried this but it throws an error. It is looking for the file inside the content folder instead of my assets folder that I have defined as static directory

```
{{ $stylemin := os.Stat “css/style.min.css” }}

```

Forget that. This worked

{{ $stylemin := os.Stat "assets/css/style.min.css" }}
<link rel="stylesheet" href="{{ "css/style.min.css" | absURL }}?{{ $stylemin.ModTime.Unix }}">

But once I modify the file locally, the query string does not change. It does not change when --watch is on (I use Git for command line). But it changes when I close Git and do hugo serve again. So I will test this on the production site and see.

Fingerprinting is better (IMHO) than a ModTime:

{{ $style := resources.Get "css/style.css" 
  | minify
  | fingerprint 
}}
<link rel="stylesheet" href="{{ $style.RelPermalink }}">
2 Likes

This works for CSS, but it makes JS not to work even though it shows it is loaded via CTRL+U.

Please share your repository.

Solved. Missing </script>

What works for me now since my CSS files are already minified.

{{ $css := resources.Get "css/style.min.css" | fingerprint "sha512" }}
<link rel="stylesheet" href="{{ $css.Permalink }}">
{{ $js := resources.Get "js/scripts.min.js" | fingerprint "sha512" }}
<script type="text/javascript" src="{{ $js.Permalink }}" defer></script>
2 Likes

Thanks everyone for the help @alexandros @nfriedli @jmooring . Cheers!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.