4

I created an api endpoint in my Next.js v13.2 application that fetches data from a database.

app/api/someData

This was working well until I deployed it on Vercel. I think the problem is that the route is being cached and, as a result, returns the same response every time. How do I stop this from occurring?

I am using the new app directory in Next.js that uses Route Handlers.

Any help would be appreciated.

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
lool
  • 345
  • 1
  • 6
  • 11

1 Answers1

8

That's because in the app directory and on production, Next.js by default caches all fetched data in API Routes and Server Components. If you are using fetch(), you can change this behavior per query, with revalidate or cache option:

fetch('https://...', { next: { revalidate: 10 } });
// OR
fetch('https://...', { cache: 'no-store' });

If you are using fetch() but want to set the cache per route segment, or you're using another library like axios, or talking directly to your database with an ORM, you can use Route Segment Config:

// layout.js OR page.js OR route.js 

import prisma from "./lib/prisma";

/*
  Keep one of the possibilities shown below (there are more on the doc), 
  depending on your needs. 
*/

export const revalidate = 10; // If you want to revalidate every 10s
// OR
export const dynamic = "force-dynamic"; // If you want no caching at all
// ...

async function getPosts() {
  const posts = await prisma.post.findMany();
  return posts;
}

export default async function Page() {
  const posts = await getPosts();
  // ...
}
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65