4 min read
Next.js Cache Tags and Shopify Webhooks That Actually Invalidate
Stale product pages cost sales and confuse AI agents. Here is how to tag Shopify data in the Next.js cache, wire webhooks to revalidateTag, and avoid the common traps that leave old prices live.

On this page
You update a price in Shopify admin. You refresh the product page on your Next.js storefront. The old price is still there. You refresh again. Still there. Ten minutes later it finally changes, or worse, it never does until the next deploy.
Stale product pages are annoying for humans and more dangerous for AI agents. A shopper can see the real price at checkout. An agent that read your cached product page or an API route backed by the same cache may quote the old price with total confidence. Getting invalidation right is not just a performance detail anymore.
The good news is that Next.js has a clean model for this: tag your cached data, and invalidate by tag when Shopify tells you something changed.
How tagged caching works
When you fetch data in a Next.js server component or route handler, you can attach cache tags to that fetch. Later, calling revalidateTag('some-tag') marks every cached entry with that tag as stale, so the next request fetches fresh data.
For Shopify Storefront API calls, that looks like this:
const res = await fetch(SHOPIFY_STOREFRONT_URL, {
method: 'POST',
headers,
body: JSON.stringify({ query, variables }),
next: { tags: ['products', `product:${handle}`] },
});Recent Next.js versions also offer cacheTag() inside functions marked with the 'use cache' directive, which does the same job for non fetch work. Check the docs for the version you run, since caching defaults have changed across major releases. The idea stays the same: data gets labels, labels get invalidated.
Choose tags you can actually target
The tags you pick decide how precise your invalidation can be. A practical scheme for a Shopify store:
productsfor anything that lists products (collections, search, home page grids)product:<handle>for a single product pagecollection:<handle>for one collectioncollectionsfor menus and collection listsinventoryif you show stock levels in many places
Tag a product page fetch with both products and product:<handle>. Tag a collection page with collections and collection:<handle>, plus products if it shows product cards.
Avoid tagging by Shopify numeric ID alone if your pages are keyed by handle. Webhook payloads include both, so you can map either way, but keep it consistent.
Wire Shopify webhooks to a route handler
Subscribe to the webhook topics that affect what customers see:
products/create,products/update,products/deletecollections/create,collections/update,collections/deleteinventory_levels/updateif stock shows on your pages
Point them at a route handler in your Next.js app, for example /api/revalidate. The handler does three things:
- Verify the HMAC. Shopify signs every webhook with your app secret. Compute the HMAC SHA256 of the raw request body and compare it to the
X-Shopify-Hmac-Sha256header using a constant time comparison. Reject anything that does not match. Read the raw body before parsing JSON, or the signature will not line up. - Work out which tags to invalidate. Read the topic header and the payload. A product update should invalidate
product:<handle>andproducts. - Call
revalidateTagfor each tag and return 200 quickly. Shopify expects a fast response and will retry on failures.
export async function POST(req: Request) {
const raw = await req.text();
if (!verifyShopifyHmac(raw, req.headers.get('x-shopify-hmac-sha256'))) {
return new Response('Unauthorized', { status: 401 });
}
const topic = req.headers.get('x-shopify-topic') ?? '';
const body = JSON.parse(raw);
if (topic.startsWith('products/')) {
revalidateTag('products');
if (body.handle) revalidateTag(`product:${body.handle}`);
}
if (topic.startsWith('collections/')) {
revalidateTag('collections');
if (body.handle) revalidateTag(`collection:${body.handle}`);
}
return new Response('ok');
}The traps that leave old prices live
Most "webhooks don't work" reports come down to a handful of issues:
- Handle changes. If a merchant renames a product handle, the old tag never gets invalidated because the payload carries the new handle. Invalidate the broad
productstag on every product update so listings stay correct, and redirect old handles. - Inventory webhooks do not carry handles.
inventory_levels/updategives you an inventory item ID. You need a lookup to map it to a product, or fall back to invalidating a wider tag. - Untagged fetches. One fetch without tags, or with a long time based revalidate, keeps serving old data no matter how many tags you clear. Grep your codebase for Storefront calls and make sure every one passes tags.
- CDN or edge caching in front. If you also set long
Cache-Controlheaders for a CDN, Next.js revalidation will not purge that layer. Keep CDN caching consistent with your framework's invalidation, or purge both. - Silent HMAC failures. If verification fails, nothing invalidates and nothing logs loudly. Log every rejected webhook with the topic.
- Duplicate deliveries. Shopify can send the same webhook more than once. Revalidating twice is harmless, so keep the handler idempotent and do not add side effects you would regret repeating.
Keep a safety net
Webhooks are reliable, not guaranteed. Add a modest time based revalidation as a backstop, for example a few minutes on product pages, so a missed webhook does not leave a page stale forever. Combine that with a small admin action or script that can invalidate products on demand during a big sale.
Why this matters for agents
If you expose catalog data to AI agents through an MCP server or API routes, those routes probably share the same data layer and the same cache. A stale cache means the agent's answer is stale too, and agents do not double check by refreshing the page.
Two habits help. First, tag agent facing data the same way as page data, so one webhook fixes both. Second, for anything that affects money, like price and availability right before adding to cart, read straight from the Storefront API with caching off. Cache is for browsing speed. Checkout decisions should hit the source.
A quick checklist
- Every Storefront fetch has tags.
- Tags include a broad list tag and a precise item tag.
- Webhook handler verifies HMAC against the raw body.
- Product, collection, and inventory topics are subscribed.
- Rejected and failed webhooks are logged.
- A short time based backstop exists.
- Agent facing price and stock reads bypass the cache before cart actions.
Get these right and price changes in Shopify show up on your storefront within seconds, for shoppers and for the agents shopping on their behalf.
Need help tuning caching and webhooks on a headless Shopify and Next.js store? I build and fix these setups regularly. Get in touch through my contact section or at ahmadraza365pro@gmail.com.


