Essentials

Caching

Caching Shopify Storefront API and Admin API requests, best practices and strategies for improving performance in your Nuxt Shopify app.

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.

The client-side and server-side caches are only available for the Storefront API. Admin API requests can only be cached on the server side using Nitro's caching utilities. Customer Account API responses are never stored in shared caches, see customer account caching.

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:

nuxt.config.ts
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 },
          },
        },
      },
    },
  },
})

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 maxAge and staleWhileRevalidate of the preset, or for the seconds of cache: { 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.

app/pages/products.vue
<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>

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.

The server-side cache is shared by all visitors. Its cache key only includes the query, the variables, the preset and the access token. Never use a server-side preset for personalized queries, such as carts, customer data or buyer-specific prices, or one visitor's response will be served to another. The client-side cache only holds the responses of one visitor, so this doesn't apply to it.

Server Routes

In your server routes, you can use Nitro's built-in caching utilities to cache Storefront API requests:

server/api/products.ts
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:

server/api/admin/orders.ts
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}`,
})
Published under the MIT License