Netlify x Hugo : using custom headers for better caching

Last modified September 25, 2019
.* :☆゚

It’s not completely obvious to people new to using Netlify, but by default, the service turns off any caching rules in its headers.

This is intentional so new builds can propagate faster and be debugged quicker, but it can also be a downside if you know things like your stylesheet or homepage images aren’t changing anytime soon.

Leaving Netlify headers at its default means a user could be loading and re-requesting the same stylesheet or image several times throughout their visit on your site.

So, if you want to cache certain assets, you will have to use custom Netlify headers.

This snippet below is for a Hugo + Netlify build, but I think it’s format is similar (probably not exactly the same) to other SSGs as well.

To check the custom headers are working, make sure your changes are deployed, then go to Network in Chrome DevTools and inspect any loaded asset’s headers.


Paste this in your config.toml file and edit as required.

[[headers]]
  for = "/images/*"
  [headers.values]
    Cache-Control = "public, max-age=604800"
[[headers]]
  for = "/*.css"
  [headers.values]
    Cache-Control = "public, max-age=604800"
[[headers]]
  for = "/*.js"
  [headers.values]
    Cache-Control = "public, max-age=604800"