Next.js Discord

Discord Forum

Pre-rendered data + dynamic data fetching

Answered
American Bobtail posted this in #help-forum
Open in Discord
American BobtailOP
I have a list of pre-rendered (at build time) public articles. But then I want to check if there is an active user session, load additional draft articles and add them to the same article list.

Is it possible to do this server-side without relying on useEffect or React Query? Can I somehow use a Suspense on a data loading hook?
Answered by American Bobtail
I found a way with Next.js unstable_cache

So I keep whole route dynamic, but I cache publicArticles instead:

export default async function ArticlesPage() {
  const getCachedPublicArticles = unstable_cache(
    // Cache public articles
    async () => getPublicArticles(),
    ['articles'],
    {
      revalidate: 30, // for 30 seconds
    },
  )
  const publicArticles = (await getCachedPublicArticles()) ?? []

  const user = await getUser()
  const articles = user
    ? [...publicArticles, ...((await getDraftArticles()) ?? [])] // If user is logged in, mix public and draft articles
    : publicArticles // Otherwise, only show public articles
View full answer

1 Reply

American BobtailOP
I found a way with Next.js unstable_cache

So I keep whole route dynamic, but I cache publicArticles instead:

export default async function ArticlesPage() {
  const getCachedPublicArticles = unstable_cache(
    // Cache public articles
    async () => getPublicArticles(),
    ['articles'],
    {
      revalidate: 30, // for 30 seconds
    },
  )
  const publicArticles = (await getCachedPublicArticles()) ?? []

  const user = await getUser()
  const articles = user
    ? [...publicArticles, ...((await getDraftArticles()) ?? [])] // If user is logged in, mix public and draft articles
    : publicArticles // Otherwise, only show public articles
Answer