tezvyn:

Next.js Extends `fetch` for Server-Side Caching

AI-drafted, machine-checkedSource: nextjs.orgbeginner

Next.js extends the standard `fetch` API to control server-side caching and revalidation. In Server Components, pass options like `next: { revalidate: 3600 }` or `tags` to manage how data is cached. This extension is server-only and ignored in browsers.

WHY IT EXISTS: In the App Router, Next.js needed a way to manage data fetching and caching that was more integrated than the Pages Router's getStaticProps. Extending the globally available fetch API provided a natural way to declare data dependencies and their caching strategies directly where they are used.

THE MENTAL MODEL: Think of fetch in Next.js as the standard Web API with a special 'options' bag for the Next.js server. When Next.js sees a fetch call on the server, it checks this bag to decide how to cache the response. This makes your data fetching declarative: you describe what you want to fetch and how it should be cached, and Next.js handles the implementation.

HOW IT WORKS: When you use fetch in a Server Component, Next.js intercepts the call. The cache option controls caching: 'force-cache' (the default) caches indefinitely, while 'no-store' fetches on every request. The next.revalidate option, given seconds, enables Incremental Static Regeneration (ISR). The next.tags option, an array of strings, allows for on-demand revalidation using the revalidateTag function. Next.js also automatically deduplicates identical fetch requests within a single render pass.

WHEN TO USE IT: Use the extended fetch in Server Components, Route Handlers, and Server Actions to fetch data from external APIs, databases, or a headless CMS. It is the primary data fetching mechanism in the App Router.

WHEN NOT TO USE IT: Do not rely on the Next.js extensions in Client Components. The fetch call will work, but the next and cache options will be ignored, as they are server-side features. For client-side data fetching that requires caching, use a library like SWR or React Query.

ONE CANONICAL EXAMPLE: To fetch data that should be re-fetched at most once per hour, you would write: const res = await fetch('...', { next: { revalidate: 3600 } });. To revalidate this on-demand, add a tag: fetch('...', { next: { revalidate: 3600, tags: ['products'] } });. Then you can call revalidateTag('products') in a Server Action to trigger a refresh.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.