Next.js - cacheTag() Function



The cacheTag() Function

The Next.js cacheTag() function used to tag cached data for on-demand invalidation. It must be used alongside "use cache" directive, inside a function or component that you want to cache.

Syntax

Following is the syntax of cacheTag() function:

'use cache'

import { unstable_cacheTag as cacheTag } from 'next/cache'

export async function getData() {
    'use cache'
    cacheTag('my-data')
    const data = await fetch('/api/data')
    return data
}

Parameters

The cacheTag() function takes a single parameter:

  • tag: A string representing the tag for the cached data. This tag can be used to invalidate the cache on-demand.

Return Value

The cacheTag function does not return any value.

Enable cacheTag Function

The cacheTag() function is an experimental feature in Next.js and needs to be enabled in the next.config.ts file. To enable the cacheTag function, set the experimental.dynamicIO flag to true in the next.config.ts file.

// File - next.config.ts

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    dynamicIO: true,
  },
}

Example 1

In the code below, the cacheTag() function is used to tag the cached data with the tag 'bookings-data'. This tag can be used to invalidate the cache on-demand.

import { unstable_cacheTag as cacheTag } from 'next/cache'
 
interface BookingsProps {
  type: string
}
 
export async function Bookings({ type = 'haircut' }: BookingsProps) {
    'use cache'
    cacheTag('bookings-data')
    
    async function getBookingsData() {
        const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
        return data
    }
}

Example 2

You can use the data returned from an async function to tag the cache entry. In the code below, the cacheTag function is used to tag the cached data with the tag 'bookings-data' and the id of the data. This tag can be used to invalidate the cache on-demand.

import { unstable_cacheTag as cacheTag } from 'next/cache'
 
interface BookingsProps {
  type: string
}
 
export async function Bookings({ type = 'haircut' }: BookingsProps) {
  async function getBookingsData() {
    'use cache'
    const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
    cacheTag('bookings-data', data.id)
    return data
  }
}
Advertisements