How to avoid caching in the app directory of Next.js?

Yes, in the app folder, Next.js by default caches all fetched results. If you are using fetch(), you can change this behavior per query, with revalidate or cache option:

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

You can also control the behavior with Route Segment Config, again if you are using fetch(), by exporting a fetchCache from a Page, Layout, or Route Handler, or a revalidate:

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

export const fetchCache="force-no-store";
// OR
export const revalidate = 0;

Now, if you’re not using fetch() to get data, but something like Axios or an ORM, the doc says:

As a temporary solution, until the caching behavior of third-party queries can be configured, you can use Route Segment Config to customize the cache behavior of the entire segment.

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

import prisma from './lib/prisma';
 
export const revalidate = 2; // revalidate every 2s, it can be 0 if you want no caching
 
async function getPosts() {
  const posts = await prisma.post.findMany();
  return posts;
}
 
export default async function Page() {
  const posts = await getPosts();
  // ...
}

For more, you can read Data Fetching.

Leave a Comment