Custom Caching #84828
-
SummaryI want to have a route that's has content that is immediately returned to the user, before the code for the page is run, at which point that code (client side) takes over. However, if the page changes, I want this to become the new default (cached) page that is returned immediately for future requests. Additional informationI am using websockets to access my database, and receive any updates to a particular row. This data is unlikely to change often (hence why I want it cached), but if there is any changes I want it to immediately change. I have got the 2 extremes working (no caching at all and default next js caching where it will invalidate every x seconds) but I want an in between. I essentially want a ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
You can achieve this by using Incremental Static Regeneration together with on-demand revalidation in Next.js. Essentially, you serve a pre-rendered (cached) version instantly, but can update it the moment your data changes. In the App Router, you can disable automatic time-based invalidation by setting export const revalidate = 0;. Then, whenever your WebSocket detects a database update trigger a revalidation request to your API route. This way the user immediately receives the last cached content while your client-side WebSocket keeps it live and reactive after hydration. Once the data changes, the cache for that route is instantly refreshed for future requests. |
Beta Was this translation helpful? Give feedback.
You can achieve this by using Incremental Static Regeneration together with on-demand revalidation in Next.js. Essentially, you serve a pre-rendered (cached) version instantly, but can update it the moment your data changes. In the App Router, you can disable automatic time-based invalidation by setting export const revalidate = 0;. Then, whenever your WebSocket detects a database update trigger a revalidation request to your API route. This way the user immediately receives the last cached content while your client-side WebSocket keeps it live and reactive after hydration. Once the data changes, the cache for that route is instantly refreshed for future requests.