Next.js Discord

Discord Forum

Cache revalidation strategy

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Avatar
Masai LionOP
I am building a storefront (Next 14 app router) and an admin using MedusaJS for my backend, but I am having some issues with how I am handling caching on the storefront. For example, in my storefront I have a fetch request to localhost:9000/store/products/${id} which gets me some data about a product in a dynamic route. I fetched that data with
next: {
  tag: [`product-${id}`]
}

inside the fetch call. However, when I update some info about the product in my admin (e.x. product description), the storefront keeps the un-updated data for a while. I was wondering if there was a programmatical way to invalidate cache. The idea would be to update the product in the admin (another nextjs app), and as soon as the updating server action is triggered, some sort of signal should get sent to the storefront to invalidate the cache for that specific route. Is that a good way of thinking about this issue?

Other two possibilities I considered are export const dynamic = 'force-dynamic', or just shortening the revalidation time for that route, however, those are less then ideal since I'd like for the cache to be invalidated only when a change is made (which is not going to happen too often, but will happen at least weekly).

4 Replies

Avatar
Great-tailed Grackle
could you show the code for the data mutation? next has this feature called revalidatePath or revalidateTag for more specific cache invalidation method, refer to this link:
https://nextjs.org/docs/14/app/building-your-application/data-fetching/fetching#on-demand-revalidation
Avatar
Great-tailed Grackle
>since I'd like for the cache to be invalidated only when a change is made (which is not going to happen too often, but will happen at least weekly).

if you're using a db provider to fetch data, it isn't cached by default (so does fetch too now in next 15). you can use unstable_cache to cache the data from a db query, add tag to the data, and then set its max revalidation interval (in seconds). then revalidate the tag after you mutate it by using revalidateTag.
Avatar
Masai LionOP
I feel so dumb, I left out the most important part.. I am using tanstack query v5 for data fetching. I am pre-fetching the data in the page.tx with the queryClient.prefetchQuery method, and then hydrating the data in the component. However, since the product info changes are happening in a separate app (admin app of the medusaJs backend that I am building), I can't really use revalidatePath or revalidateTag since the change is happening in the admin (Nextjs app 1), and I want to invalidate the cache in another app (Storefront, nextjs app 2).

Hope I clarified my issue a bit better.