#Cache on GET api route?

1 messages · Page 1 of 1 (latest)

shut crown
#

I am creating a API GET route that is getting data from my Mongo Database that im then using on my website. The thing I am wondering if there is some kind of "auto cache" on that or if I either need create my own simple cache to just store it in memory or if I don't need to do anything at all?

I want/need to have caching on it because otherwise it will connect to the database and get the data every time someone visits my website.

lament moonBOT
#

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

#

In Next.js, when you create an API GET route, caching behavior is applied by default. Specifically, Route Handlers are cached by default when using the GET method with the Response object. This means you don't need to create your own caching mechanism unless you have specific requirements.

Here is an example of a GET route that fetches data from a MongoDB API and leverages the default caching behavior:

export async function GET() {
  const res = await fetch('<https://data.mongodb-api.com/...',> {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': process.env.DATA_API_KEY,
    },
  });
  const data = await res.json();

  return Response.json({ data });
}

If you need to revalidate the cached data periodically, you can use the next.revalidate option to specify the revalidation interval. For example, to revalidate the data every 60 seconds:

export async function GET() {
  const res = await fetch('<https://data.mongodb-api.com/...',> {
    next: { revalidate: 60 }, // Revalidate every 60 seconds
  });
  const data = await res.json();

  return Response.json(data);
}

Alternatively, you can use the revalidate segment config option:

export const revalidate = 60;

If you want to opt out of caching for specific reasons, you can do so by using the Request object with the GET method or by using other HTTP methods like POST. Here is an example of opting out of caching using the Request object:

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const id = searchParams.get('id');
  const res = await fetch(`<https://data.mongodb-api.com/product/${id}`,> {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': process.env.DATA_API_KEY!,
    },
  });
  const product = await res.json();
#

return Response.json({ product });
}


For more details, you can refer to the **Next.js documentation on caching** (<https://nextjs.org/docs/app/building-your-application/routing/route-handlers#caching>) and **opting out of caching** (<https://nextjs.org/docs/app/building-your-application/routing/route-handlers#opting-out-of-caching>).

By leveraging these built-in caching mechanisms, you can ensure that your API GET route is efficiently cached, reducing the need to connect to the database on every request.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

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

shut crown
#

@lament moon Alright, And what is the default time that the data stays cached before "updating" it?

lament moonBOT
#

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

#

The default caching behavior for data in Next.js can vary depending on the context in which the data is being cached. For API routes, the default caching duration is not explicitly defined in the provided knowledge sources. However, for other caching mechanisms in Next.js, such as the Data Cache and Router Cache, there are some default values mentioned.

For example, the default cache duration for routes in Next.js is 30 seconds, as mentioned in the staleTimes documentation (https://nextjs.org/docs/app/api-reference/next-config-js/staleTimes):

"Next routes have a default cache of 30 seconds, even if it is SSR."

To explicitly set the revalidation interval for your API route, you can use the next.revalidate option in your fetch request. Here is an example of setting the revalidation interval to 60 seconds:

export async function GET() {
  const res = await fetch('<https://data.mongodb-api.com/...',> {
    next: { revalidate: 60 }, // Revalidate every 60 seconds
  });
  const data = await res.json();

  return Response.json(data);
}

Alternatively, you can use the revalidate segment config option:

export const revalidate = 60;

For more details on caching and revalidation, you can refer to the Next.js documentation on caching (https://nextjs.org/docs/app/building-your-application/caching#overview) and revalidation behavior (https://vercel.com/docs/infrastructure/data-cache#revalidation-behavior).

By setting the revalidation interval, you can control how long the data stays cached before it is updated.

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

#

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

shut crown
#

@lament moon Okay, but how could I change the revalidate time inside the GET route when I dont use fetch in there?

lament moonBOT
#

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

#

If you want to change the revalidation time for a GET route without using the fetch function, you can use the revalidate segment config option. This allows you to set the revalidation interval for the entire route.

Here is an example of how to set the revalidation interval to 60 seconds for a GET route:

// app/items/route.ts

export const revalidate = 60; // Revalidate every 60 seconds

export async function GET() {
  // Your logic to fetch data from MongoDB
  const data = await getDataFromMongoDB();

  return Response.json(data);
}

In this example, the revalidate export sets the revalidation interval to 60 seconds. This means that the data will be revalidated every 60 seconds, even if you are not using the fetch function within the GET route.

For more details, you can refer to the Next.js documentation on the revalidate segment config option (https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#revalidate).

By using the revalidate segment config option, you can control the revalidation interval for your GET route without needing to use the fetch function.

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