Next.js Discord

Discord Forum

Caching a function in SSR rendered page, invalidate after x seconds

Unanswered
Sardinian Shepherd Dog posted this in #help-forum
Open in Discord
Avatar
Sardinian Shepherd DogOP
I’m rendering my homepage as an SSR page using the nextjs app router. Id like to implement caching to prevent abuse. I want to cache the page for all users and invalidate the cache every 60 seconds so data is refreshed periodically without fetching stats from redis on every page load. How can I implement caching with 1 minute intervals for the page, ensuring the data is refetched only after cache invalidation?

Here's my current code for the homepage:

If I use force-static then it will only render the page once and will never invalidate.
export default async function Home() {
  const stats = await redis.stats.get("...");

  return (
    <HydrateClient>
      <div className="h-full">
        <Hero />
        <Stats stats={stats} />
      </div>
    </HydrateClient>
  );
}

2 Replies

Avatar
Sardinian Shepherd DogOP
bump
Avatar
Yucatan Vireo
Oh yeah, that's just regular caching behavior with fetch(). There's plenty on the docs here:

https://nextjs.org/docs/app/api-reference/functions/fetch

& here:

https://nextjs.org/docs/app/building-your-application/caching#data-cache