Caching
Caching is a fundamental building block of a good shopping experience. Combined with streaming server-side rendering, caching ensures that buyers get the quickest response possible while also displaying the latest data.
Hydrogen automatically caches responses from queries when using the Storefront client. You can disable or customize the cache for every single request to the Storefront API. This guide shows the different options available for caching.
Caching strategies
Anchor link to section titled "Caching strategies"Hydrogen includes recommended caching strategies to help you determine which cache control header to set. The following table lists the available caching strategies and their associated cache control headers and cache durations:
Caching strategy | Cache control header | Cache duration |
---|---|---|
CacheShort() |
public, max-age=1, stale-while-revalidate=9 |
10 seconds |
CacheLong() |
public, max-age=3600, stale-while-revalidate=82800 |
1 Day |
CacheNone() |
no-store |
No cache |
CacheCustom() |
Define your own cache control header | Custom |
By default, each sub-request applies the CacheShort()
strategy with the following cache options:
The following is an example of how to pass a cache strategy to the Storefront client to cache product titles:
Cache options
Anchor link to section titled "Cache options"Each mechanism accepts the same cache options API based on the Cache-Control
HTTP Header:
Name | Description |
---|---|
mode |
Sets options that don't need a duration:
|
maxAge |
Correlates with the max-age cache control header. Instructs the cache how long to store an entry. |
staleWhileRevalidate |
Correlates with the stale-while-revalidate cache control header. Instructs the cache how long after an entry’s max-Age it's acceptable to serve a stale entry. Another request for fresh data is made in the background. |
sMaxAge |
Correlates with the s-maxage cache control header. Instructs the cache how long to store an entry on CDN or proxy caches. |
staleIfError |
Correlates with the stale-if-error cache control header. Instructs how long the browser may use the cached entry when the entry returns a 5xx status error. |
Create a custom caching strategy
Anchor link to section titled "Create a custom caching strategy"If you don't want to use the caching strategies that Hydrogen provides, then you can create your own to use in your project.
For example, you can create a cache control header with max-age=30, must-revalidate, no-transform
:
Cache data from third-party APIs
Anchor link to section titled "Cache data from third-party APIs"The cache
instance that's passed to the Storefront client is available in storefront.cache
. This cache instance follows the Cache API and can be used to manually cache data that comes from other sources, such as a custom Content Management System (CMS). The following is an example caching a request to a third-party API: