Caching Gatsby Sites

One of the foundational best practices for Gatsby static sites is to perform proper HTTP caching, which enables browsers to optimally cache resources from a given website such that the user experiences a near-instantaneous load. The Gatsby documentation outlines several types of resources in the public directory that should be cached (or not) according to a particular set of configurations:HTMLHTML files should not be cached by the browser, because each Gatsby rebuild updates the contents of static HTML files that Gatsby generates. Browsers should be set to verify on each request whether a newer version of the HTML file needs to be downloaded.Page dataGatsby recommends excluding the JSON files located in the public/page-data directory from browser caching, because these files are also entirely updated on each rebuild and, in fact, can be updated without a rebuild taking place. Therefore, browsers should be set to verify on each request whether new page data is available for download.App dataThe app-data.json file includes the build hash for the most recent deployment of the Gatsby site and thus ought to share the same cache-control header as page-data.json, so that the version of application data loaded in the browser remains in sync with the current Gatsby deployment.Static filesFiles in the static directory are designed to be cached in perpetuity. Gatsby generates paths for each file in this directory that are associated with the contents of the file, such that filepaths change when the file contents evolve.JavaScript and CSS assetsAny JavaScript and CSS assets that are handled by Webpack should be cached in perpetuity as well, as they are unchanging unless their file contents change. The only exception to this best practice is the /sw.js file, which is generated by the gatsby-plugin-offline plugin (see ““Adding Offline Support with Service Workers””).

Table 13-3 outlines the cache-control headers that should be set for each of these asset types when caching Gatsby sites.

Asset typeHeader
HTMLcache-control: public, max-age=0, must-revalidate
Page data
App data
Static filescache-control: public, max-age=31536000, immutable
JavaScript and CSS assets
/sw.jscache-control: public, max-age=0, must-revalidate

The gatsby-plugin-netlify and gatsby-plugin-s3 plugins have automated caching headers enabled for their respective infrastructures.

TIP

The following cache header can also be used for HTML, page data, and app data, because no-cache enables a cache to deliver cached content so long as it validates the freshness of the cache first:

cache-control: public, no-cache

Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *