Server side caching with Next API

Unsure if this pattern is common, or if I am approaching this incorrectly. I am using an api in my backend (next route handlers /api), and want to cache the data for 24 hours, so that I am only calling the api once a day. I understand how this can be done in a typical server using memory, but am curious if there is a different method possible when using serverless (since there is no persistent memory) that doesnt involve s3 or introducing a whole db. Please clarify if I am misunderstanding anything! Thanks!
3 Replies
Guilhermo
Guilhermo2y ago
You could use the revalidate constant as per next.js route handlers docs. if you are caching for 24 hours, it would look something like this:
...
export const revalidate = 3600 * 24
...
export async function GET(){
...
}
...
...
export const revalidate = 3600 * 24
...
export async function GET(){
...
}
...
Next.js Docs guide for this: https://nextjs.org/docs/app/building-your-application/routing/router-handlers#revalidating-static-data
Routing: Route Handlers
Create custom request handlers for a given route using the Web's Request and Response APIs.
jgoon
jgoon2y ago
Since vercel uses aws lambda for route handling, doesn't this mean that the cache would only exist in the lifetime of the container? So after it the function times out, the cache would be cleared. Also, in the case that the function is run in parallel, the data would have to be recached. I'm realizing now, that I may have to add some state management after all. (correct me if im wrong)
Matvey
Matvey2y ago
No, the data will be cached on Vercel CDN.
Want results from more Discord servers?
Add your server