Skip to main content

Caching

The caching functions cache Storefront API queries, third-party API responses, and other async work. Use the functions to choose how long each result stays fresh and to cache data under a key that you choose.

For Storefront API reads, use the cache option on createStorefrontClient. For other third-party requests, use createFetchWithCache. For any other async work, use createRunWithCache.

Import Cache, createFetchWithCache, and createRunWithCache from @shopify/hydrogen.


Creates caching strategies for Storefront API queries, cached fetches, and cached runs. Call Cache with options for a custom strategy, or use the short, long, and none presets.

(overrideOptions?: ) =>
required

Keeps public entries fresh for 1 hour, then serves stale entries for 23 more hours while the cache refreshes them. Pass options to override the mode or either duration, or to add staleIfError.

() =>
required

Returns a strategy that skips the cache. The preset takes no options.

Anchor to short
short
(overrideOptions?: ) =>
required

Keeps public entries fresh for 1 second, then serves stale entries for 9 more seconds while the cache refreshes them. Pass options to override the mode or either duration, or to add staleIfError.

Examples

TypeScript

import {
Cache,
createShopifyRequestContext,
createStorefrontClient,
gql,
} from "@shopify/hydrogen";

const PRODUCTS_QUERY = gql(`query { products(first: 10) { nodes { title } } }`);

export async function getProducts(request: Request, waitUntil: (promise: Promise<unknown>) => void) {
const storefront = createStorefrontClient({
type: "public",
requestContext: createShopifyRequestContext({ request, i18n: { country: "US", language: "EN" } }),
config: {
storeDomain: process.env.PUBLIC_STORE_DOMAIN!,
publicStorefrontToken: process.env.PUBLIC_STOREFRONT_API_TOKEN,
cache: await caches.open("hydrogen"),
waitUntil,
},
});

return storefront.graphql(PRODUCTS_QUERY, { cache: Cache.long() });
}

Creates a fetch function that caches responses from third-party APIs. Call the function like fetch(), and pass a key and strategy in the third argument to cache the response. Calls without the third argument skip the cache. Return false from a shouldCacheResponse option to skip caching one response.

The function caches only OK responses with no body or with a JSON, text, XML, HTML, GraphQL, or JavaScript content type. Other responses skip the cache. The function removes the set-cookie and server-timing headers from each cached response, including the response that a cache miss returns. With staleIfError, the function serves a stale entry only after a 500, 502, 503, or 504 status, or when the fetch throws.

Anchor to input1
input1
required

A cache, or the function from createRunWithCache to share its cache, plus an optional fetch function.

A fetch function that adds a Cache-Status header to calls with cache options, unless annotateCacheStatus is false.

Examples

TypeScript

import { Cache, createFetchWithCache } from "@shopify/hydrogen";

export async function fetchReviews(productId: string, waitUntil: (promise: Promise<unknown>) => void) {
const fetchWithCache = createFetchWithCache({
cache: await caches.open("reviews"),
waitUntil,
});

const url = `https://reviews.example.com/products/${productId}`;

return fetchWithCache(url, undefined, {
key: ["reviews", productId],
strategy: Cache.short(),
shouldCacheResponse: async ({ json }) => {
const payload = await json?.().catch(() => undefined);
return typeof payload === "object" && payload != null && !("errors" in payload);
},
});
}

Creates a function that caches the result of any async work, such as data that several API calls produce together. For a single fetch response, use createFetchWithCache.

Anchor to input1
input1
required

The cache, and the function that keeps the runtime alive for background cache writes.

A function that returns cached data or runs your callback, and reports the cache status.

Returns cached data for the key, or runs the callback and caches the result.

The callback returns an object with data and a boolean shouldCache. The function throws a TypeError for any other shape. During the staleWhileRevalidate window, the function returns the stale data right away and runs the callback in the background. During the staleIfError window, the function returns the stale data when the callback throws. A no-store strategy runs the callback and skips the cache.

Anchor to options
options
required

The cache key and caching strategy for this call.

() => <<>>
required

Produces the data and decides whether to cache it. Runs whenever the cache has no fresh entry.

Promise<<>>

The data, and whether the data came from the cache, the callback, or a bypass.

Examples

TypeScript

import { Cache, createRunWithCache } from "@shopify/hydrogen";

export async function getInventorySummary(
handle: string,
waitUntil: (promise: Promise<unknown>) => void,
) {
const runWithCache = createRunWithCache({
cache: await caches.open("inventory"),
waitUntil,
});

const { data, cacheStatus } = await runWithCache(
{ key: ["inventory-summary", handle], strategy: Cache.short() },
async () => {
const response = await fetch(`https://inventory.example.com/${handle}`);
if (!response.ok) {
throw new Error(`Inventory request failed with ${response.status}`);
}
const summary: { available: number } = await response.json();
return { data: summary, shouldCache: true };
},
);

return { ...data, cacheStatus };
}

Anchor to Storefront API queriesStorefront API queries

To cache a Storefront API query, pass a cache to the Storefront API client and a Cache strategy to the query. Leave cart and customer queries without a strategy, and cache customer-specific work with createRunWithCache under a key unique to that customer.


Was this page helpful?