Plugins can cache data as JSON objects and retrieve them on consecutive builds.
Caching is already used by Gatsby and plugins for example:
- any nodes created by source/transformer plugins are cached
gatsby-plugin-sharpcaches built thumbnails
Build outputs are stored in the
public directories relative to your project root.
The cache API is passed to Gatsby’s Node APIs which is typically implemented by plugins.
The two functions you would want to use are:
cache.set(key: string, value: any) => Promise<any>
Retrieve cached value
cache.get(key: string) => Promise<any>
The Node API helpers documentation offers more detailed information on the API.
In your plugin’s
gatsby-node.js file, you can access the
cache argument like so:
Since cache files are stored within the
.cache directory, deleting it will clear all cache. You can also use
gatsby clean to delete the
The cache is also invalidated by Gatsby in a few cases, specifically:
package.jsonchanges, for example a dependency is updated or added
gatsby-config.jschanges, for example a plugin is added or modified
gatsby-node.jschanges, for example if you invoke a new Node API, or change a
With the cache API you’re able to persist data between builds, which is really helpful while developing a site with Gatsby (as you re-run
gatsby develop really often). Performance-heavy operations (like image transformations) or downloading data can slow down the bootstrap of Gatsby significantly and adding this optimization to your plugin can be a huge improvement to your end users. You can also have a look at the following examples who implemented the cache API: gatsby-source-contentful, gatsby-source-shopify, gatsby-source-wordpress, gatsby-transformer-remark, gatsby-source-tmdb.