Example: persisting assets forever with fingerprints

Use case

Deploys on Netlify are atomic and immutable which has many of benefits for maintaining sites in known states and allowing very useful default caching configurations on the CDN and in browsers. But there is a use case where sites might want to have HTML which is either cached in the browser for long periods, or is left open in the browser for long periods and might reference a resource which might be updated on the CDN as a result of frequent deploys.

You can define your own caching behaviour on Netlify via the custom headers configuration, but you can also ensure that an HTML file always has access to the correct version of its dependencies for subsequent requests to the CDN even if it hangs around long after new deploys have taken place.

A common pattern for binding a given version of an html file to specific versions of its dependencies it to add a fingerprint query parameter

/scripts/some-versioned-resource.js?fingerprint=123456789

Since Netlify generates a uniquely addressable version of the site for every deploy, we can use this as a way to direct requests to any version of an asset which has ever been deployed. A redirect rule lets us support whatever URL format we like for this perform http rewrites the CDN edge to return the desired assets version.

Method

  1. Add a redirect rule to serve fingerprinted assets when that querystring is used
  2. Associate version dependent assets with the current build of the site by using the deploy ID for the fingerprint parameter

1. The redirect configuration added to netlify.toml

  
  [[redirects]]
    from = "/*"
    query = {fingerprint = ":hash"}
    to = "https://:hash--test-fingerprint.netlify.app/:splat?"
    status = 200
    force = true
  

2. Use the DEPLOY_ID value in your build

(Using whatever site generator or framework you like to access the DEPLOY_ID environment variable provided by Netlify)

/scripts/some-versioned-resource.js?fingerprint={{ DEPLOY_ID }}

Demo

This site has a image of a cat which has evolved over time. (They grow up so fast!)

This is the version of an asset included in this deploy.

Previously deployed versions of this asset are addressable via their fingerprint