How to Cache API Calls in Next.js App Router?
Answered
Terek Sandpiper posted this in #help-forum
Terek SandpiperOP
Hey everyone,
I’m using the App Router in Next.js and have a client component that makes requests to an API route. This API route then fetches data from an external API. I want to ensure that the external API call is only made once every 10 minutes to reduce the load and improve performance.
Is there a built-in way in Next.js to handle this kind of caching, or do I need to implement my own solution? If it’s the latter, what’s the best way to go about it?
I know how to do with static pages with ISR. I am just wondering if there is similar functionality with API routes.
Thanks!
I’m using the App Router in Next.js and have a client component that makes requests to an API route. This API route then fetches data from an external API. I want to ensure that the external API call is only made once every 10 minutes to reduce the load and improve performance.
Is there a built-in way in Next.js to handle this kind of caching, or do I need to implement my own solution? If it’s the latter, what’s the best way to go about it?
I know how to do with static pages with ISR. I am just wondering if there is similar functionality with API routes.
Thanks!
13 Replies
yes
use that, set the revalidate to 60 * 10
60s * 10 so 10mins
60s * 10 so 10mins
Terek SandpiperOP
What’s the difference with this?
https://nextjs.org/docs/app/building-your-application/routing/route-handlers#revalidating-cached-data
https://nextjs.org/docs/app/building-your-application/routing/route-handlers#revalidating-cached-data
@Terek Sandpiper What’s the difference with this?
https://nextjs.org/docs/app/building-your-application/routing/route-handlers#revalidating-cached-data
it depends on you completely, for your external api.. are you using fetch?
Terek SandpiperOP
I am using fetch, yes. I guess the better question is how do I verify it is not fetching it? I tried the method in the link I shared above, and added a console.log each successful call to external API, and it logs each time not every 10 minutes.
@Terek Sandpiper I am using fetch, yes. I guess the better question is how do I verify it is not fetching it? I tried the method in the link I shared above, and added a console.log each successful call to external API, and it logs each time not every 10 minutes.
can you show your code, also your console log is where?
enable that
Terek SandpiperOP
Enabling this logging verified that my cache does work! Thank you so much.
I can see the cache skip and cache hit.
I can see the cache skip and cache hit.
yup, loooks like its caching
if it helped you, mark a solution @Terek Sandpiper
Original message was deleted
boop