4

I am working on a Next.js project version 13.4.6 and I have a dynamic route /product/[id]. I need to revalidate the data for a specific product, for example, /product/123, when its content changes.

I am aware of the revalidatePath function, which allows revalidating data associated with a specific path. However, when I use revalidatePath with a dynamic segment such as revalidatePath('/product/[id]'), it revalidates all segments under /product/[id].

Here is an example code snippet that demonstrates how to use the revalidatePath function:

import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'

export async function GET(request: NextRequest) {
  const path = request.nextUrl.searchParams.get('path') || '/'
  revalidatePath(path)
  return NextResponse.json({ revalidated: true, now: Date.now() })
}

The Next.js version 13.4.6 documentation says that the revalidatePath function accepts a single parameter, path, which should be a string representing the filesystem path associated with the data you want to revalidate. This is not the literal route segment(e.g. /product/123), but instead, the path on the filesystem (e.g. /product/[id])​​.

What I want to achieve is to selectively revalidate only a specific product ID, like /product/123, without revalidating all the other segments under /product/[id].

Is there a way to achieve this selective revalidation in Next.js 13?

Any tested alternative strategies or best practices would be greatly appreciated.

Thank you in advance!

0 Answers0