#Dynamically Adding Cache Tags in Next.js ISR After Fetch

1 messages · Page 1 of 1 (latest)

mighty thicketBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

coarse agate
#

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"
coarse hound
# coarse agate you can do something like this: ```ts const userId = 12 const user = await get...

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?

coarse agate
#

maybe using 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
}
#

it is currently experimental though I've never had any issues using it for a past month or so

coarse hound
#

Ohh big thanks, I'll take a closer look at that!

coarse agate
#

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.

coarse hound