Caching and revalidation
Running the same database query for every visitor wastes time and money. In Next.js 16 you opt into caching with "use cache", control its lifetime with cacheLife, label it with cacheTag and refresh it with updateTag, revalidateTag or revalidatePath.
64.1 Problem: a DB query on every request
- getProducts has no "use cache", so the page renders dynamically (with a loading file) on every request.
- Three users open the page: every request takes about 850 ms although the data is the same.
React (TSX)
// app/products/page.tsximport { getProducts } from "@/lib/products"; export default async function ProductsPage() { const products = await getProducts(); return ( <ul> {products.map((p) => ( <li key={p.id}> {p.name}: ₹{p.price} </li> ))} </ul> );}Output
$ npm run devGET /products 200 in 846msGET /products 200 in 843msGET /products 200 in 843ms64.2 Why is it used?
- Older Next.js cached fetch automatically, and developers were confused why data did not update.
- From Next.js 15 data is not cached automatically; in 16 you decide, and without "use cache" data is fresh per request.
- That is correct, but for data that is the same for everyone and rarely changes, hitting the DB every time wastes time and money.
64.3 Step 1: cacheComponents in next.config
- The config from create-next-app already has cacheComponents: true.
- Rule: data stays dynamic until you mark it with "use cache".
- The same flag also turns on Partial Prerendering (rendering video).
TypeScript
// next.config.tsimport type { NextConfig } from "next"; const nextConfig: NextConfig = { cacheComponents: true,}; export default nextConfig;64.4 use cache, cacheLife and cacheTag
- "use cache": store the function's result; a later call with the same arguments returns the stored result without running it.
- cacheLife("hours"): data is refreshed in the background roughly every hour (ISR); until then users get the cached data.
- cacheTag("products"): a label on this cache entry, so later you can refresh it by name.
- First request still queries the DB (1506 ms); next ones come from cache in about 70 ms.
TypeScript
// lib/products.tsimport { cacheLife, cacheTag,} from "next/cache";import { db } from "./db"; export async function getProducts() { "use cache"; cacheLife("hours"); cacheTag("products"); return db.product.findMany();}Output
$ npm run devGET /products 200 in 1506msGET /products 200 in 72msGET /products 200 in 70ms- Step 1
1.First request: cache empty -> DB query, result saved
- Step 2
2.Next requests: cache hit, DB not touched (~70 ms)
- Step 3
3.cacheLife time is up: user gets the stale data
- Step 4
4.Next.js loads fresh data in the background and updates the cache
This pattern is called stale-while-revalidate
64.5 Price update: updateTag
- The admin changes Running Shoes from ₹999 to ₹799, but the cache still shows the old price.
- A Server Function (next video) saves the new price, then updateTag("products") expires the products cache immediately.
- The admin sees ₹799 on the page right away.
TypeScript
"use server";import { updateTag } from "next/cache";import { db } from "@/lib/db"; export async function updatePrice( id: number, price: number,) { await db.product.update({ where: { id }, data: { price }, }); updateTag("products");}Output
Running Shoes: ₹999Cotton T-shirt: ₹499 (after updatePrice)Running Shoes: ₹799Cotton T-shirt: ₹499- Step 1
1.Admin submits a new price
- Step 2
2.Server Action: db.product.update(...)
- Step 3
3.updateTag("products") expires every entry tagged products
- Step 4
4.Next render of /products runs getProducts again
- Step 5
5.Admin sees Running Shoes: ₹799
64.6 Comparison: 3 tools to refresh the cache
TypeScript
updateTag("products"); // in a Server Action: expires nowrevalidateTag("products", "max"); // also from a webhook: background refreshrevalidatePath("/products"); // refresh a whole URL| Tool | Where it works | What the next visitor sees | Use for |
|---|---|---|---|
| updateTag(tag) | Only in Server Actions | Fresh data immediately | Users seeing their own change (profile, cart) |
| revalidateTag(tag, "max") | Server Actions, Route Handlers, webhooks | Old data while refresh runs in background | CMS/webhook updates |
| revalidatePath(path) | Server Actions, Route Handlers | Fresh render of that URL | Refreshing a whole page like /products |
64.7 Checkpoint: how many DB queries?
- getProduct is called three times in one request: id 1, id 1, id 2.
- Answer: 2. The arguments are part of the cache key: the second id 1 call is a cache hit, id 2 is a new key.
TypeScript
import { db } from "@/lib/db"; async function getProduct(id: number) { "use cache"; console.log("DB query", id); return db.product.findUnique({ where: { id }, });} // same requestawait getProduct(1);await getProduct(1);await getProduct(2);Output
DB query 1DB query 264.8 Common mistakes
- Reading cookies() inside a "use cache" function: error, because a cached result is shared by all users but cookies differ per user.
- Fix: read cookies in the page and pass the city as an argument; every city gets its own cache entry.
- Cookies belong to each request, so that page folder also needs a loading file.
- Myth: Next.js caches everything automatically. True up to Next 14; from 15 fetch is not cached by default, and in 16 data is cached only with "use cache".
- "use cache" is not only for fetch: put it on a DB query or on a whole component.
React (TSX)
// Wrong: Error: cookies() can't be read inside "use cache"import { cookies } from "next/headers";import { db } from "@/lib/db"; async function getDeals() { "use cache"; const jar = await cookies(); const city = jar.get("city")?.value; return db.deal.findMany({ where: { city }, });}React (TSX)
// Right: city argument = its own cache keyimport { cookies } from "next/headers";import { db } from "@/lib/db"; async function getDeals(city = "Delhi") { "use cache"; return db.deal.findMany({ where: { city }, });}export default async function DealsPage() { const jar = await cookies(); const city = jar.get("city")?.value; const deals = await getDeals(city); return <p>{deals.length} deals</p>;}64.9 Best practices
- Cache only data that is the same for everyone and changes rarely (product list, blog posts), not a cart or order history.
- Put a cacheTag on every cached function so you can refresh exactly that data.
- Call updateTag or revalidateTag as soon as the data changes.
- Read cookies and headers outside the cache and pass them in as arguments.
64.10 Interview tips
- In Next.js 16 uncached data is fresh on every request and streams inside Suspense.
- To cache, add "use cache" to a function or component; its arguments become the cache key.
- cacheLife sets the lifetime; cacheTag labels it; updateTag / revalidateTag refresh it when data changes.
- updateTag = read-your-own-writes in actions; revalidateTag(tag, "max") = stale-while-revalidate, works from webhooks.
- Never read cookies or headers inside a cached scope; pass them as arguments.