DEV Community

Jonathan U
Jonathan U

Posted on

12 2 1

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
noscrubs profile image
No Scrubs

Cool

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay