Next.js Discord

Discord Forum

Dynamically Adding Cache Tags in Next.js ISR After Fetch

Answered
Raspberry Horntail posted this in #help-forum
Open in Discord
Original message was deleted.
Answered by American black bear
maybe using [dynamicIO](https://nextjs.org/docs/app/api-reference/config/next-config-js/dynamicIO) experimental and use cache:

export function fetchDataThenSetCacheTag() {
  "use cache"
  const res = await fetch ("https://api.example.com/data")
  const data = await res.json()

  cacheTag(`data-${data.id}`)

  return data
}
View full answer

8 Replies

American black bear
you can do something like this:

const userId = 12

const user = await getUserProfile(12)

// set this as tag
`user-${userId}-profile`

// on server the function result is cached under the following tag:
// "user-12-profile"
@American black bear you can do something like this: ts const userId = 12 const user = await getUserProfile(12) // set this as tag `user-${userId}-profile` // on server the function result is cached under the following tag: // "user-12-profile"
Raspberry Horntail
Thanks for your reply!

My issue is that I’d like to assign the ISR tag after receiving the API response — based on the returned data. Right now, I can add tags like this:

const res = await fetch('https://api.example.com/data', {
next: { tags: [user-${userId}-profile] },
});

But what I’d really like to do is generate the tag dynamically, depending on the data I get back from the API (e.g. once I get a 200 response). Is that possible?
American black bear
maybe using [dynamicIO](https://nextjs.org/docs/app/api-reference/config/next-config-js/dynamicIO) experimental and use cache:

export function fetchDataThenSetCacheTag() {
  "use cache"
  const res = await fetch ("https://api.example.com/data")
  const data = await res.json()

  cacheTag(`data-${data.id}`)

  return data
}
Answer
American black bear
it is currently experimental though I've never had any issues using it for a past month or so
Raspberry Horntail
Ohh big thanks, I'll take a closer look at that!
American black bear
it has some weird quirks such as having to wrap the root layout in suspense, but after you get used to it it improves caching dx a bunch imo.
@American black bear it has some weird quirks such as having to wrap the root layout in suspense, but after you get used to it it improves caching dx a bunch imo.
Raspberry Horntail
Thank you very much, I just tested it and it works. I will check if it has any negative impact with the canary version!