Next.js Discord

Discord Forum

revalidateTag for specific route

Answered
Thrianta posted this in #help-forum
Open in Discord
ThriantaOP
I have a blog with comments. I want to revalidate only the comments after a user posts a comment. I have a function to fetch comments based on an article id:
import "server-only"
import {unstable_cache} from "next/cache"

export const getArticleComments = unstable_cache(async (id: number) => {...}, [], { tags: ["article-comments"] })


However, when I revalidate comments, it revalidates the comments of every blog post.

I feel like revalidatePath is not granular enough: I don't want to revalidate the blog post and whatever else I've fetched on that route.

Could I use parallel routes and revalidatePath("/blog/[id]/@comments") to only target that part of the page?
Answered by joulev
try this
import "server-only"
import { unstable_cache } from "next/cache"

export const getArticleComments = (id: number) =>
  unstable_cache(
    async (id: number) => {...},
    [],
    { tags: [`article-comments:${id}`] }
  )(id);

then
"use server";
...
revalidateTag("article-comments:1");
View full answer

10 Replies

Answer
ThriantaOP
Wow. Thanks mod let me test it quickly. I am a bit worried that each invocation will create a new cache though. I understand revalidate and unstable_cache is new, but do you have any idea if this is a common practice?
@Thrianta Wow. Thanks mod let me test it quickly. I am a bit worried that each invocation will create a new cache though. I understand revalidate and unstable_cache is new, but do you have any idea if this is a common practice?
each invocation will create a new cache
correct, each id has its own cache tag which may or may not be desirable for your credit card. but without the id, obviously you cannot tell nextjs to "revalidate only the comments for this article and not every articles". it's a compromise that you need to make on how granular you want your cache to be.

do you have any idea if this is a common practice?
i'd say pretty common, i've seen it used elsewhere on this server, and i am using this technique in prod at work – one day a co-worker suddenly brought this to the table from some random internet blog posts and we've been using it ever since
ThriantaOP
Will do. Thanks
do update me if it works, i am also interested in it
ThriantaOP
Will do, I don't want to waste too much time figuring out parallel routing now, but if I do I hope I will remember to tag you. Also, it seems like you know a lot about the cache, or at least more than the docs explain. Did you read source code or can you direct me where I can learn more about how the cache works? Other than [the docs](https://nextjs.org/docs/app/api-reference/functions/unstable_cache).
ThriantaOP
I appriciate the resources 👍