#cached value in layout
1 messages · Page 1 of 1 (latest)
Based on the information provided in the knowledge sources, I can offer some guidance on caching data in a layout component for Next.js 14.2.14 using the App Router. However, it's important to note that some of the newer caching mechanisms mentioned in the sources are not available in your version.
For your specific use case of caching a number in a layout component for 10 minutes, you can try the following approach using unstable_cache:
- First, ensure you're importing
unstable_cachefrom Next.js:
import { unstable_cache } from 'next/cache';
- Then, modify your
getCachedKomCountfunction to useunstable_cache:
const getCachedKomCount = unstable_cache(
async () => {
const session = await checkAuth()
if (!session.isLoggedIn || session.pbAuth == null) throw new Error("Couldn't authenticate!")
pb.authStore.save(session.pbAuth)
return pb.collection(Collections.KomTimeseries).getFirstListItem("", {
sort: "-created",
})
},
['kom-count'],
{ revalidate: 600 } // 600 seconds = 10 minutes
);
This approach uses unstable_cache to cache the result of your database query for 10 minutes. The **'kom-count'] array is used as a cache key, and the revalidate option is set to 600 seconds (10 minutes) [Unstable_cache** (https://nextjs.org/docs/app/api-reference/functions/unstable_cache).
However, there are a few important points to consider:
- Authentication: Since your function involves authentication, be cautious about caching sensitive data. You might need to adjust the caching strategy based on your authentication requirements.
-
Dynamic data: If you're accessing dynamic data sources like
headersorcookiesinside the cached function, this might not work as expected. The documentation states that accessing such dynamic data sources inside a cache scope is not supported Unstable_cache (https://nextjs.org/docs/app/api-reference/functions/unstable_cache). -
Server Components: Ensure that the component where you're using this cached function is a Server Component, as
unstable_cacheis meant for server-side use.
If you're still experiencing issues with database logs showing unique requests, you might want to consider implementing a more robust caching solution at the database or API level.
Alternatively, if the data doesn't need to be real-time and can be static for all users, you could consider using Incremental Static Regeneration (ISR) by setting a revalidate time in your data fetching function Incremental Static Regeneration (https://nextjs.org/docs/pages/building-your-application/upgrading/app-router-migration#incremental-static-regeneration-getstaticprops-with-revalidate).
If none of these solutions work for your specific use case, using a Context Provider as you mentioned could be a viable alternative, especially if you need to share this data across multiple components and want more control over when and how it's updated.