In Next.js, revalidating data is the process of clearing the Data Cache and retrieving the latest data. This allows you to display the latest information to your users as your data changes.
There are two types of revalidation:
- Time-Base
- On-demand -
revalidatePathandrevalidateTag
In this post, we'll focus on On-demand revalidation revalidateTag, which manually revalidates data based on an event such as a form submission. This can only called in a Server Action or Router Handler.
Next.js has a cache tagging system for invalidating fetch requests across routes. In order to use revalidateTag, you'll need to add a tag in the fetch request:
const res = await fetch('https://baseurl.com', { next: { tags: ['mytag'] } });
This adds the cache tag mytag to the fetch request.
Then you can revalidate the fetch call by calling revalidateTag in a Server Action:
'use server'
import { revalidateTag } from 'next/cache'
export default async function action() {
revalidateTag('mytag')
}
Basic Next.js 14 example with Typescript can be found here: https://github.com/juhlmann75/Next.js-Examples/tree/main/src/app/examples/revalidateTag
More on how On-demand revalidation works.
Top comments (1)
Cool