Caching
If you want to improve the performance of your Nuxt Shopify app, consider using a cache for your Storefront API and Admin API requests. Caching can help reduce the number of API calls, decrease latency, and improve the overall user experience.
Configuration
In the nuxt.config.ts, you can configure the cache presets, the client-side cache and the server-side cache in the
cache property of the storefront client configuration:
export default defineNuxtConfig({
shopify: {
clients: {
storefront: {
cache: {
// Default presets, the same as Hydrogen's `Cache.short()` and `Cache.long()`
presets: {
short: { maxAge: 1, staleWhileRevalidate: 9 },
long: { maxAge: 3600, staleWhileRevalidate: 82800 },
},
},
},
},
},
})
export default defineNuxtConfig({
shopify: {
clients: {
storefront: {
cache: {
// Custom browser cache settings
browser: {
ttl: 10, // 10 seconds
max: 100, // Maximum number of items in cache
maxSize: 10 * 1024 * 1024, // 10 MB maximum cache size
maxEntrySize: 1024 * 1024, // 1 MB maximum size of one item
},
// Or use the default settings:
// browser: true,
},
},
},
},
})
export default defineNuxtConfig({
shopify: {
clients: {
storefront: {
cache: {
// Custom server storage settings
server: {
driver: "redis",
host: "localhost",
port: 6379,
// ...
},
// Or use the default settings:
// server: true,
},
},
},
},
})
export default defineNuxtConfig({
shopify: {
clients: {
storefront: {
cache: {
// You can also use an existing nitro storage mount for the server cache
server: "my-shopify-cache-mount",
},
},
},
},
nitro: {
storage: {
"my-shopify-cache-mount": {
driver: "redis",
host: "localhost",
port: 6379,
// ...
},
},
},
})
Presets use Hydrogen's cache options.
A response is fresh for maxAge seconds.
After that, it is served for another staleWhileRevalidate seconds while it is refreshed in the background.
If the refresh fails, it is served for another staleIfError seconds.
Instead of seconds, you can also set an object such as { minutes: 10 }.
Setting presets replaces the default presets, so add short and long again if you use them.
With server: true, the server-side cache is kept in memory, with up to 1000 entries, 32 MiB in total and 4 MiB per entry.
Each response is removed once the maxAge, staleWhileRevalidate and staleIfError of its preset have passed.
To share the cache between server instances, use your own mount, such as Redis.
The routes of the module, such as the Storefront API proxy, the cart, the checkout, predictive search and the customer account routes, are never cached.
A catch-all rule like '/**': { swr: 60 } doesn't apply to them, also on Vercel, where such a rule becomes ISR.
Your own pages use your route rules as usual, including a cart page at /cart or /de-de/cart.
Only pages directly below a cart path, such as /cart/<something>, are not cached either, because they share their paths with the cart permalinks.
Cached pages are rendered without the visitor's cookies, so a page that sets a cookie for new visitors sets it in every cached render.
For example, @nuxtjs/i18n sets its locale cookie when detectBrowserLanguage.useCookie is enabled, which is the default.
Since Nitro 2.13.6, such a page isn't cached.
Older versions cache it and send its cookie to every visitor.
In this case, cache the Storefront API requests of the page instead.
Caching Storefront API Requests
Since the Storefront API can be used on the server and client side, there are different approaches to caching requests depending on where they are made.
In Your App
In your app, you can use the built-in caching of the useStorefront and useStorefrontData composables.
Caching is opt-in per request: set a preset in the cache option of the request.
- On the client side, the response is kept in an in-memory LRU cache for the
maxAgeandstaleWhileRevalidateof the preset, or for the seconds ofcache: { browser: { ttl } }. This cache is cleared when the page is refreshed. - During server-side rendering, the response is kept in the server-side cache, which is shared between all pages and visitors.
The Storefront API proxy doesn't cache, so client-side navigation only uses the client-side cache.
<script setup lang="ts">
const storefront = useStorefront()
const { data } = await storefront.request(`#graphql
query FetchProducts($first: Int) {
products(first: $first) {
nodes {
...ProductFields
}
}
}
`, {
variables: {
first: 5,
},
// Set the 'short' preset for the browser and the server
cache: 'short',
// Or set the browser and server presets separately:
// cache: { browser: 'short', server: 'long' },
})
</script>
<script setup lang="ts">
const { data } = await useStorefrontData(`#graphql
query FetchProducts($first: Int) {
products(first: $first) {
nodes {
...ProductFields
}
}
}
`, {
variables: {
first: 5,
},
transform: (data) => flattenConnection(data.products),
// Set the 'short' preset for the browser and the server
cache: 'short',
// Or set the browser and server presets separately:
// cache: { browser: 'short', server: 'long' },
})
</script>
Cached requests are sent to Shopify without the visitor's cookies, Accept-Language header and IP address, so use @inContext variables to localize them.
Mutations and responses with errors are never cached.
Server Routes
In your server routes, you can use Nitro's built-in caching utilities to cache Storefront API requests:
export default defineCachedEventHandler(async (event) => {
const storefront = useStorefront(event)
const { data } = await storefront.request(`#graphql
query FetchProducts($first: Int) {
products(first: $first) {
nodes {
...ProductFields
}
}
}
`, {
variables: {
first: 5,
},
})
return data
}, {
// Cache settings for this handler
maxAge: 60 * 60, // 1 hour
})
Caching Admin API Requests
Since the Admin API is only accessible on the server side, you can use Nitro's caching utilities to cache Admin API requests as well:
import { z } from 'zod'
export default defineCachedEventHandler(async (event) => {
const admin = useAdmin(event)
const { id } = await getValidatedQuery(event, z.object({
id: z.string(),
}).parse)
const { data } = await admin.request(`#graphql
query FetchOrder($id: ID!) {
order(id: $id) {
id
name
totalPriceSet {
shopMoney {
amount
currencyCode
}
}
displayFinancialStatus
displayFulfillmentStatus
}
}
`, {
variables: {
id: `gid://shopify/Order/${id}`,
},
})
return data
}, {
// Cache settings for this handler
maxAge: 60 * 60, // 1 hour
// Use order ID as cache key
getKey: event => `order-${getQuery(event).id}`,
})