#caching in async components

1 messages · Page 1 of 1 (latest)

dire nest
#

what's the best way to cache and revalidate data that im getting from my db within an async server component. im hesitant to use route handlers since I believe directly making these requests is ideal in server components

balmy mangoBOT
#

Hi @dire nest. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Next.js extends the native fetch Web API to allow you to configure the caching and revalidating behavior for each fetch request on the server. You can use fetch with async/await in Server Components.

Here's an example of how you can use fetch to cache and revalidate data in an async server component:

export default async function Page() {
  // This request should be cached until manually invalidated.
  // Similar to `getStaticProps`.
  // `force-cache` is the default and can be omitted.
  const staticData = await fetch(`<https://...`,> { cache: 'force-cache' })
 
  // This request should be refetched on every request.
  // Similar to `getServerSideProps`.
  const dynamicData = await fetch(`<https://...`,> { cache: 'no-store' })
 
  // This request should be cached with a lifetime of 10 seconds.
  // Similar to `getStaticProps` with the `revalidate` option.
  const revalidatedData = await fetch(`<https://...`,> {
    next: { revalidate: 10 },
  })
 
  return <div>...</div>
}

In this example, fetch is used with different cache options to control how the data is cached and revalidated. The force-cache option indicates that the request should be cached until manually invalidated. The no-store option indicates that the request should be refetched on every request. The revalidate option indicates that the request should be cached with a lifetime of 10 seconds[^1^].

You can also revalidate the Next.js Cache inside your Server Actions with the revalidatePath or revalidateTag APIs[^9^].

#

@dire nest kapa.ai is still learning and improving, please let us know how it did by reacting below

dire nest
#

@balmy mango im directly making calls to my database through db.find, not through fetch requests. how do i cache these results without the use of fetch requests?

balmy mangoBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In cases where you're using a third-party library that doesn't support or expose fetch (for example, a database, CMS, or ORM client), you can still configure the caching and revalidating behavior of those requests using the Route Segment Config Option and React's cache function[^5^].

Here's an example of how you can use the cache function to memoize data requests:

import { cache } from 'react'
 
export const getItem = cache(async (id: string) => {
  const item = await db.item.findUnique({ id })
  return item
})

In this example, the getItem function is called twice, but only one query will be made to the database[^2^].

You can also use the revalidate option in the Layout and Page segments to set the cache lifetime of a resource (in seconds):

import { getItem } from '@/utils/get-item'
 
export const revalidate = 3600 // revalidate the data at most every hour
 
export default async function Layout({
  params: { id },
}: {
  params: { id: string }
}) {
  const item = await getItem(id)
  // ...
}

In this example, the revalidate option is set to 3600, meaning the data will be cached and revalidated at most every hour[^2^].

[^2^]: (source: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#example)
[^5^]: (source: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-third-party-libraries)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@dire nest kapa.ai is still learning and improving, please let us know how it did by reacting below

dire nest
#

@balmy mango can these functions be associated with tags so that i can conditionally revalidate any function that uses these tags?

balmy mangoBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In Next.js, the revalidateTag function is used to invalidate the cache for a specific tag[^4^]. However, this function is typically used in conjunction with fetch requests, where you can associate cache entries with one or more tags[^2^].

As of now, there's no direct way to associate tags with database queries or other non-fetch operations. The cache tagging system in Next.js is designed to work with fetch requests and the built-in caching mechanism[^2^].

If you want to conditionally revalidate data based on certain conditions, you might need to implement your own caching layer or use a third-party caching library that supports tagging.

[^2^]: (source: https://nextjs.org/docs/app/building-your-application/caching#fetch-optionsnexttags-and-revalidatetag)
[^4^]: (source: https://nextjs.org/docs/app/api-reference/functions/revalidateTag)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: