Next.js Discord

Discord Forum

Conditionally caching pages on the edge

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
How would you guys handle this if your app is on vercel:

Based on if the client is logged in or not ( which you check server side on initial page request via cookie headers ) you will provide a page with either 1) personalized content or 2) default content. For personalized content you need to hit your Backend CMS to get data, but for default content you don’t want to do that extra hop so you cache the default content in JS memory, and revalidate it in the background every now and then

I believe a problem here is you can’t persist the cached data in the JS heap on the edge.

And since cache control headers can’t adapt to cookies existing or not that isn’t the solution either

9 Replies

const getDefaultContent = unstable_cache(...);

async function getData() {
  const user = await getUser();
  if (!user) return getDefaultContent(...);
  return getUserContent(user);
}


is what i would do, which solely relies on nextjs apis. i don't tend to use vercel-specific apis, because that means vendor lock-in that makes migration non-trivial.
@joulev tsx const getDefaultContent = unstable_cache(...); async function getData() { const user = await getUser(); if (!user) return getDefaultContent(...); return getUserContent(user); } is what i would do, which solely relies on nextjs apis. i don't tend to use vercel-specific apis, because that means vendor lock-in that makes migration non-trivial.
Asian black bearOP
Sorry for responding late… I seriously didn’t realize you responded 😄 yes that’s what im thinking too, the issue im foreseeing is persistence in an edge environment… wouldn’t all that state get flushed every now and then?
@joulev It depends on where you host the data cache. On Vercel, it’s not even wiped after you redeploy, so it’s safe.
Asian black bearOP
whats your recommendation for how i should host the data cache
my idea was literally just in the js memory
nothing too complicated, the goal is to decrease hops at the end of the day...
@Asian black bear whats your recommendation for how i should host the data cache
Well, Vercel handles it for you automagically. So you don’t have to worry about that part.
@joulev Well, Vercel handles it for you automagically. So you don’t have to worry about that part.
Asian black bearOP
So I just do a normal javascript variable and dont worry about the rest?
Just use cached functions, such as unstable_cache