Caching a function in SSR rendered page, invalidate after x seconds
Answered
Sardinian Shepherd Dog posted this in #help-forum
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.
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>
);
}
11 Replies
Sardinian Shepherd DogOP
bump
Yucatan Vireo
Oh yeah, that's just regular caching behavior with
https://nextjs.org/docs/app/api-reference/functions/fetch
& here:
https://nextjs.org/docs/app/building-your-application/caching#data-cache
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
@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
Sardinian Shepherd DogOP
Hi, thank you for the response but I am not using fetch. This isn't a http request, I am using redis and would like to cache the entire page for x period of time.
Sardinian Shepherd DogOP
bump
export const revalidate = 60
Answer
@James4u tsx
export const revalidate = 60
Sardinian Shepherd DogOP
Hi thanks, I gave this a go but if I add a console log into the pages code (server side) it still is output on every render, is this because revalidate only works on vercel?
@Sardinian Shepherd Dog Hi thanks, I gave this a go but if I add a console log into the pages code (server side) it still is output on every render, is this because revalidate only works on vercel?
on your local dev server, there will be only fresh one no stale data
@James4u on your local dev server, there will be only fresh one no stale data
Sardinian Shepherd DogOP
Okay thank you for the response 🙂
@Sardinian Shepherd Dog Okay thank you for the response 🙂
great! mark solution to close the thread!
@Sardinian Shepherd Dog resolved?
@James4u <@576483462421151779> resolved?
Sardinian Shepherd DogOP
yes thank you very much