Next.js - revalidateTag() Function



The revalidateTag() Function

The Next.js revalidateTag() function is used to remove cached data on-demand for a specific tag.

Syntax

The syntax for the revalidateTag() function is as follows:

import { revalidateTag } from 'next/cache'

revalidateTag(tag: string): void;

Parameters

The revalidateTag() function accepts one parameter.

  • tag: A string representing the cache tag associated with the data you want to revalidate. Must be less than or equal to 256 characters. This value is case-sensitive.

Tags are used to identify cached data. You can add tags to any data while fetching the data using the next.js fetch API. For example, you can add tags to fetch() function as follows:

fetch(url, { next: { tags: [...] } });

Return Value

The revalidateTag() function does not return any value.

Example 1

In the example below, we are using the revalidateTag() function to revalidate the tag "post". This will remove the cached data for the "post" tag.

import { revalidateTag } from 'next/cache'
revalidateTag('post')

Example 2

The code below will revalidate any URL that matches the provided page file on the next page visit. This will not invalidate pages beneath the specific page. For example, /blog/[slug] won't invalidate /blog/[slug]/[author].

//  app/actions.ts

'use server'
 
import { revalidateTag } from 'next/cache'
 
export default async function submit() {
    await addPost()
    revalidateTag('posts')
}


// app/api/revalidate/route.ts

import type { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
 
export async function GET(request: NextRequest) {
    const tag = request.nextUrl.searchParams.get('tag')
    revalidateTag(tag)
    return Response.json({ revalidated: true, now: Date.now() })
}
Advertisements