Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-01 12:34:29
Original
517 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template