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 },
});
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();