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)
- Enable
cacheComponents: true(default for new apps in Next.js 16.4). - Write a data function with
"use cache"at the top. - Set a lifetime:
cacheLife('hours'). - Tag it:
cacheTag('products'). - Invalidate:
revalidateTag('products', 'max')from a webhook, orupdateTag('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'orexport const revalidate = 600.
Where cached data lives
- Build-time results are part of the prerendered static shell.
- Runtime
use cacheentries 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
staletime.
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". POSTrequests are not cached.
Code example
tsx
1// lib/products.ts2import "server-only";3import { cacheLife, cacheTag } from "next/cache";45type Product = { id: string; name: string; price: number };67export async function getProducts(category: string): Promise<Product[]> {8 "use cache";9 cacheLife("hours");10 cacheTag("products", `category:${category}`); // category is part of the cache key11 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}1516// app/admin/actions.ts17// "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 read22// }2324// 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.