Resolving Server side cache issues in Nextjs

Next.js has a built-in Data Cache that persists the result of data fetches across incoming server requests and deployments. 

By default, data requests that use fetch are cached. We can use the cache and next.revalidate options of fetch to configure the caching behavior.

The Data Cache is persistent across incoming requests and deployments unless you revalidate or opt-out.

Cached data can be revalidated in two ways, with:

Time-based Revalidation: Revalidate data after a certain amount of time has passed and a new request is made.

On-demand Revalidation: Revalidate data based on an event.

Time-based Revalidation

To revalidate data at a timed interval, we can use the next.revalidate option of fetch to set the cache lifetime of a resource (in seconds).

fetch(‘https://…’, { next: { revalidate: 3600 } })

On-demand Revalidation

Data can be revalidated on-demand by path (revalidatePath) or by cache tag (revalidateTag).

Opting out

For individual data fetches, you can opt out of caching by setting the cache option to no-store. This means data will be fetched whenever fetch is called.

// Opt out of caching for an individual fetch request

fetch(<https://…,> { cache: ‘no-store’ })

The above methods are found to be useful while resolving server side cache issues.

Apart from this, router.refresh() function can be used. The refresh option of the useRouter hook can be used to manually refresh a route. This completely clears the Router Cache, and makes a new request to the server for the current route. refresh does not affect the Data or Full Route Cache.

The rendered result will be reconciled on the client while preserving React state and browser state.

Leave a comment

Your email address will not be published. Required fields are marked *