CoursesControlling cached content in Next.jsTime-based cache revalidation
Track
Work-ready Next.js

Controlling cached content in Next.js

Lesson
4

Time-based cache revalidation

Time-based revalidation is simple to setup and predictable. It might be "enough" for your project.
Log in to mark your progress for each Lesson and Task
See the Next.js documentation about time-based revalidation

For every fetch made so far, you've only been implementing time-based revalidation. This has been primarily for convenience. It's simple to set up and invalidates itself.

The default setting of 60 seconds is okay. The type of content your application displays and the volume of traffic you receive will determine whether to modify that setting.

Content that changes often, like product pages, may benefit from a lower revalidation time because accuracy is more important than raw speed. Other content, like your terms and conditions pages, likely changes so infrequently that their cache time could safely be set to hours.

The blog post index and individual pages fall into the latter category. Let's update the requests on both routes to cache the responses for an hour.

Update the fetch on your post-index route
src/app/(frontend)/posts/page.tsx
const posts = await sanityFetch({
query: POSTS_QUERY,
revalidate: 3600,
})
Update the fetch on your post route
src/app/(frontend)/posts/[slug]/page.tsx
const post = await sanityFetch({
query: POST_QUERY,
params,
revalidate: 3600,
})

Instead of hitting Sanity's CDN at least once a minute, requests will be served by the Next.js cache for up to an hour, a significant performance and bandwidth improvement.

Your business stakeholders and end-users are happy. Your content authors could be less so.

Imagine you're a content author who has just published a new post – or fixed a typo on a post – and want to ensure the site is fixed immediately. Right now, they may need to wait up to an hour for the world to see those changes.

You do have a route to clear the entire cache, but this can potentially impact the performance of every request to every page for every user. The hammer option isn't ideal for fixing a typo.

Fortunately, the passage of time isn't the only way to invalidate the cache. Next.js provides a way to invalidate a specific route on demand, and Sanity provides a way to run it automatically on content changes.

Let's revalidate by path in the next lesson.

You have 2 uncompleted tasks in this lesson
0 of 2