Next.jsMedium

How do you cache fetch requests in Next.js?

With Cache Components, put the fetch inside a "use cache" function or component and set cacheLife and cacheTag. Without Cache Components, pass cache: 'force-cache' or next: { revalidate, tags } to fetch. Either way, invalidate on demand with revalidateTag or updateTag.

Cache Components approach (recommended)

  1. Enable cacheComponents: true (default for new apps in Next.js 16.4).
  2. Write a data function with "use cache" at the top.
  3. Set a lifetime: cacheLife('hours').
  4. Tag it: cacheTag('products').
  5. Invalidate: revalidateTag('products', 'max') from a webhook, or updateTag('products') in a Server Function.

Arguments become part of the cache key, so getProduct('a') and getProduct('b') are separate entries. This also caches non-fetch work such as database queries.

Previous model

  • fetch(url, { cache: 'force-cache' }) caches indefinitely.
  • fetch(url, { next: { revalidate: 600 } }) caches with ISR timing.
  • fetch(url, { next: { tags: ['products'] } }) adds tags.
  • Route-wide defaults: export const fetchCache = 'default-cache' or export const revalidate = 600.

Where cached data lives

  • Build-time results are part of the prerendered static shell.
  • Runtime use cache entries live in an in-memory LRU per server instance by default. On serverless they may not persist, so use "use cache: remote" with a cache handler for shared, durable caching.
  • The browser keeps results for the stale time.

Pitfalls

  • Caching per-user data in a shared cache leaks it to other users. Pass the user ID as an argument (so it is part of the key) or use "use cache: private".
  • POST requests are not cached.

Code example

tsx
1// lib/products.ts
2import "server-only";
3import { cacheLife, cacheTag } from "next/cache";
4
5type Product = { id: string; name: string; price: number };
6
7export async function getProducts(category: string): Promise<Product[]> {
8 "use cache";
9 cacheLife("hours");
10 cacheTag("products", `category:${category}`); // category is part of the cache key
11 const res = await fetch(`https://api.example.com/products?category=${category}`);
12 if (!res.ok) throw new Error("Failed to load products");
13 return res.json();
14}
15
16// app/admin/actions.ts
17// "use server";
18// import { updateTag } from "next/cache";
19// export async function updatePrice(id: string, price: number) {
20// await db.product.update({ where: { id }, data: { price } });
21// updateTag("products"); // every product list refreshes on next read
22// }
23
24// Previous model equivalent:
25// fetch(url, { next: { revalidate: 3600, tags: ["products"] } });

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app