Home  >  Article  >  Web Front-end  >  How to Prevent API Endpoint Data From Being Cached in Next.js?

How to Prevent API Endpoint Data From Being Cached in Next.js?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 12:34:29479browse

How to Prevent API Endpoint Data From Being Cached in Next.js?

How to Prevent API Endpoint Data From Being Cached in Next.js

Next.js v13.2 employs a new app directory with Route Handlers. In production, the framework automatically caches data fetched from API endpoints and Server Components. This can lead to inconsistencies if the backend data is updated.

Solution 1: Modifying Fetch Options

To disable caching for specific fetch queries, append revalidate or cache options to the fetch() function:

<code class="js">fetch('https://...', { next: { revalidate: 10 } }); // revalidate every 10 seconds
fetch('https://...', { cache: 'no-store' }); // no caching</code>

Solution 2: Using Route Segment Configuration

For use with other libraries (e.g., axios, ORM) or for per-route segment cache settings, consider utilizing Route Segment Configuration:

<code class="js">// layout.js, page.js, or route.js

import prisma from './lib/prisma';

/*
  Force dynamic behavior, there are more options available depending on your requirement.
*/
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();
  // ...
}</code>

The above is the detailed content of How to Prevent API Endpoint Data From Being Cached in Next.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn