javascriptreactjscachingnext.jsvercel

Data is not being updated (always getting the same result) after the project is deployed


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.


Solution

  • 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";
    
    /*
      Bleow option is when you want no caching at all, there are more options
      on the doc depending on your needs. 
    */
    export const dynamic = "force-dynamic";
    
    async function getPosts() {
      const posts = await prisma.post.findMany();
      return posts;
    }
    
    export default async function Page() {
      const posts = await getPosts();
      // ...
    }