Caching Shopify API data with Hydrogen and Oxygen
Hydrogen and Oxygen provide built-in caching to speed up Hydrogen storefronts. The caching API is based on the web-standard
By default, Hydrogen automatically caches Storefront API data when using Hydrogen’s built-in API client. You can customize or disable caching behavior for every request. You can optionally extend Hydrogen’s built-in utilities to cache data from third-party APIs.
Customer Account API data is never cached, because it’s personalized for each user.
Caching strategiesAnchor 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:
|Cache control header
public, max-age=1, stale-while-revalidate=9
public, max-age=3600, stale-while-revalidate=82800
|Define your own cache control header
Default caching strategyAnchor link to section titled "Default caching strategy"
By default, each sub-request applies a strategy with the following cache options, which revalidates data after one second and caches it for up to one day:
Subrequest cachingAnchor link to section titled "Subrequest caching"
You can configure the caching strategy for Storefront API data by passing a
cache option with your query.
The following simplified example shows a component that displays product titles. Because titles don't change often, it caches the data using the
Custom caching strategiesAnchor link to section titled "Custom caching strategies"
The following strategy directs clients to revalidate the cached data when it’s no longer fresh, not to transform the data, and to consider it fresh for a maximum of 30 seconds:
Cache-Control APIAnchor link to section titled "Cache-Control API"
The following options are available when creating a custom caching strategy with
|One or more comma-separated directives for how caches should handle response data. Accepts
|The length of time, in seconds, to cache the response.
|The length of time, in seconds, to serve a stale response while fetching a fresh one in the background.
|The length of time, in seconds, that proxies or CDNs can store the response.
|The length of time, in seconds, for the browser to serve a cached response instead when it receives a 5xx error.
Cache-Control API exceptionsAnchor link to section titled "Cache-Control API exceptions"
no-cache directive isn't supported by Oxygen because it instructs the browser not to use the cached data until the server returns a
304 (Not Modified) status from server. However, Oxygen doesn't return the
304 response status code, so this directive has no effect.