Next.js: Simple Example using revalidateTag

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 – revalidatePath and revalidateTag

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'] } });
Enter fullscreen mode
Exit fullscreen mode

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')
}
Enter fullscreen mode
Exit fullscreen mode

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.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

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

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Martins ad network.