Caching third-party API data with Hydrogen and Oxygen
The API client built into Hydrogen includes caching strategies for Storefront API data. However, if you make
fetch requests to third-party APIs in your Hydrogen app, then the following behavior occurs:
- HTTP GET responses are cached according to their response headers.
- POST requests aren't cached.
There are several ways to manage caching of third-party data with Hydrogen and Oxygen:
- Hydrogen’s built-in
- Creating custom abstractions
- Caching content manually
Hydrogen’s built-in withCache utilityAnchor link to section titled "Hydrogen’s built-in withCache utility"
Hydrogen includes a
createWithCache utility to support caching third-party API calls. This utility wraps an arbitrary number of sub-requests under a single cache key.
Step 1: Create and inject the utility functionAnchor link to section titled "Step 1: Create and inject the utility function"
To start, create a
withCache function in your project server file and pass it as part of the Remix context.
The following example shows how
withCache works with Oxygen:
Step 2: Call withCache in Remix loaders and actionsAnchor link to section titled "Step 2: Call withCache in Remix loaders and actions"
After you pass the utility function to the Remix context,
withCache is available in all Remix loaders and actions.
In the following example, the
withCache function wraps a standard
fetch query to a third-party CMS:
Custom cache abstractionsAnchor link to section titled "Custom cache abstractions"
Instead of using
withCache directly in your routes, you can also create custom abstractions around it. For example, you can make your own CMS fetcher and inject it in the Remix context.
You can create as many abstractions as needed for your third-party APIs, and they will be available in Remix loaders and actions. For TypeScript projects, you should add types accordingly in the
Manual cachingAnchor link to section titled "Manual caching"
As an alternative to the
withCache utility, you can also directly use the
cache instance that's passed to the Storefront client and available in
This cache instance follows the Cache API. Using the cache instance directly is a low-level approach and you need to handle all the cases and features manually, including error handling and stale-while-revalidate.
The following example shows how to cache a request to a third-party API with Oxygen: