Can I use cache in a regular API route?
#51295
Replies: 3 comments 1 reply
-
|
I'm not sure if the Cache function of APP Router is also suitable for Page Router, but as an alternative, if you want to create an API Router in App Router, you can use the |
Beta Was this translation helpful? Give feedback.
-
|
Also wondering this |
Beta Was this translation helpful? Give feedback.
-
|
Yes, API routes in APP router (for example So let say you have an API route to return items from a db table. This route will be compiled during build - and if your connection string does not work in build because of missing credentials - then the API will always return empty data. But you can configure the route to be always non cached using defining dynamic global variable: or if you want to hit the db at most every 20 seconds you define So in this case when you call the route first time, it will read the data. Then if you call it within the period of 20s, the call hits the server (if you use middleware.js - you can see the call coming in) - but the function code is never executed, just data is returned from the cache. And after the 20s if you call this api route again, the function executes. I just did not figure out how to enforce the invalidation of cache on API routes. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
https://nextjs.org/docs/app/building-your-application/data-fetching/caching the documentation here only refers to server side components it seems, will it also inside a regular api route?
Beta Was this translation helpful? Give feedback.
All reactions