Next.js Discord

Discord Forum

Serverless function caching question

Unanswered
Dogue de Bordeaux posted this in #help-forum
Open in Discord
Dogue de BordeauxOP
Hi,

My application requires product prices be loaded occasionally (a few times a week) from an external api to stay up to date. I've implemented a serverless function to grab the data I need, but am confused with how caching this data works, as to not run up a bill on serverless function usage. Here is some information on what I'm doing:

I'm making a request to an external api via an api route. I set the Cache Control header, and see that that is working fine. Requests made to my endpoint are served instantly after the max-age is set.

When a client hits the site, which in turn makes a request to the serverless function, is this just hitting the cache now (before it is invalidated via timeout) and serverless function usage does not count, or must I do additional setup to ensure that both the external api, and the serverless function are not being hit often?

Perhaps I misunderstood something here, such as the serverless function counting as hit regardless of whether it serves cached data? I haven't yet written code to query this endpoint via client components, but I will need to soon.

We expect a lot of traffic soon, and do not want to run up a bill. I see there is a Data Cache in Vercel, but I'm not quite sure if it's what I'm looking for. Normally I'd set up a cron job to grab this data, or just grab it at set intervals / invalidate it via webhooks.

Let me know if I can further clarify, thanks.

Some code:

export async function GET(request) {
  try {
    const data = await getPriceDataFromThirdParty();
    return new Response(JSON.stringify(data), {
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'public, max-age=86400',
      },
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      headers: { 'Content-Type': 'application/json' },
      status: 500,
    });
  }
}

0 Replies