Next.jsHard
What is the data cache in the App Router?
The Data Cache is the persistent server-side cache for fetch responses in the previous caching model. Responses fetched with cache: 'force-cache' or next: { revalidate } were stored across requests and deployments and invalidated by time or tags. With Cache Components, "use cache" entries take over this role for any async function, not just fetch.
Previous model details
- Opt in per request:
fetch(url, { cache: 'force-cache' })or{ next: { revalidate: 3600, tags: ['posts'] } }. - Default since Next.js 15: not cached (
no-storebehavior). In Next.js 14 the default was cached. - Persists across requests and, on Vercel and with a configured handler, across deployments.
- Invalidation: time-based (
revalidate) or on-demand (revalidateTag,revalidatePath). unstable_cache(fn, keys, { tags, revalidate })gave the same caching to database calls.- Separate from request memoization, which only lasts for one render.
Cache Components equivalent
"use cache"caches the return value of any async function or component.- Cache key: build ID, function ID, serialized arguments and captured variables.
- Lifetime:
cacheLife(stale,revalidate,expire). - Tags:
cacheTag; invalidate withrevalidateTag(tag, profile)orupdateTag(tag). - Storage: in-memory LRU per instance by default (
cacheMaxMemorySize),"use cache: remote"withcacheHandlersfor shared storage,"use cache: private"for browser-only per-user caching. - Scope: entries are tied to the build, so a new deploy starts fresh. If data must survive deploys, keep using the
fetchcache orunstable_cache, which still work.
Self-hosting
With multiple instances, configure a custom cache handler (Redis or similar) so all instances share entries and revalidations.
Code example
tsx
1// Previous model: Data Cache via fetch options and unstable_cache2import { unstable_cache } from "next/cache";3import { db } from "@/lib/db";45export async function getPosts() {6 const res = await fetch("https://cms.example.com/posts", {7 next: { revalidate: 3600, tags: ["posts"] },8 });9 return res.json();10}1112export const getAuthors = unstable_cache(13 async () => db.author.findMany(),14 ["authors"], // key parts15 { tags: ["authors"], revalidate: 3600 }16);1718// Cache Components equivalent19import { cacheLife, cacheTag } from "next/cache";2021export async function getAuthorsCached() {22 "use cache";23 cacheLife("hours");24 cacheTag("authors");25 return db.author.findMany();26}
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.