Cache shared, non-personal reads with use cache, cacheLife and cacheTag (Next.js 16 Cache Components). Check auth outside cached code, key on every input, invalidate tags where you write, never CDN-cache cookie responses, and fix slow SQL with indexes first.
Must-have checklist
Must
Check the session and permissions on every request outside the cached function, pass the verified user or tenant id in, and keep the cached helper unexported.
A cache hit returns the stored result without running the function body, so a check inside it is skipped.
Pass every input the result depends on (user or tenant id, role, locale, filters) as an argument; never cache per-user or permission-dependent data under a shared key.
Arguments and captured variables form the cache key; anything left out is shared between callers.
Key and tag on stable ids; keep tokens, passwords and raw emails out of cached-function arguments and cacheTag values.
Next.js stores cache keys and tags in plain text, including in remote cache handlers.
Send Cache-Control private, no-store on any response that sets a cookie or depends on the session; never public or s-maxage.
Set-Cookie alone does not stop a shared cache from storing and reusing a response (RFC 9111, section 7.3).
Authenticate Route Handlers that call revalidateTag or revalidatePath for webhooks (shared secret or signature) and accept only known tags.
An open endpoint lets anyone flush the cache and push the load onto Postgres.
Tag cached reads with cacheTag (collection and entity tags) and invalidate those tags in every Server Action, Route Handler or job that writes, after the write commits.
After a user's own change, call updateTag in the Server Action (Next.js 16) so their next read waits for fresh data; use revalidateTag(tag, 'max') where brief staleness is fine.
Wrap components that read cookies, headers, searchParams or uncached data in Suspense with a fallback, and move those reads as deep in the tree as possible.
With Cache Components, an uncached or runtime read outside Suspense is flagged as a blocking route.
With more than one app instance, use a cache handler that shares tag state across instances, or document that other instances may be stale up to cacheLife.
By default revalidateTag only invalidates the cache on the instance that received the call.
Before caching a slow query, find it with pg_stat_statements, read its plan with EXPLAIN (ANALYZE, BUFFERS), and add the missing index.
Use a pooled Postgres connection so cache-miss bursts after a deploy or revalidation don't exhaust max_connections.
Postgres runs one backend process per connection and max_connections is typically 100 by default.
Should
Set an explicit cacheLife in every use cache scope, chosen from how stale that data may be.
Without it the implicit default profile applies, and nested lifetimes become hard to reason about.
Serve heavy shared aggregates from a materialized view with a unique index, refreshed CONCURRENTLY on a schedule or after batch writes.
CONCURRENTLY refreshes without blocking reads but needs a unique index on plain columns.
Give only public, non-personalised GET Route Handlers Cache-Control public, s-maxage and stale-while-revalidate, and purge the CDN when on-demand revalidation must reach it.
revalidateTag and revalidatePath clear the Next.js cache, not a CDN copy.
Decisions to make
Asked before building01Which Next.js caching model does the app use?
02How quickly must readers see a change after it is written?
03Are pages personalised per user or per permission?
04How many app instances or services read and write this data?
05Do pages show expensive aggregates (counts, sums or reports over large tables)?
Options
3 comparedNext.js framework cache (Cache Components)
- Data is shared by many users and may be a little stale
- One Next.js app owns the writes and can invalidate tags
- You want cached parts in the prerendered static shell
- Several services must share cached values outside Next.js
- Entries must survive a deploy
- The default store is in-memory per instance, ephemeral on serverless, and resets on every deploy
- Invalidation reaches other instances only through a shared cache handler
- Cache keys and tags are stored in plain text
Shared external cache (Redis-compatible)
Examples, not endorsements: Redis, Valkey, Upstash Redis
- Several app instances or services need the same cached values
- A slow or rate-limited upstream must be protected under high traffic
- You self-host and need a shared store behind
use cache: remote(cacheHandlers)
- One instance and the framework cache are enough
- Keys are mostly unique per request or per user, so the hit rate is low
- The query is already fast
- A network round trip on every lookup
- Another service to run, secure, monitor and pay for
- Every write path must delete or re-tag the affected keys
Database-side materialized views
- Heavy aggregates are read often and change in batches
- Several apps or services read the same summaries
- Minutes to hours of staleness is acceptable
- Data must be current on every read
- Base tables change so often that refreshes would run back to back
- Each refresh recomputes the whole query
- CONCURRENTLY needs a unique index and an already populated view
- You schedule and monitor refreshes yourself
Why this approach
With Next.js 16 Cache Components, data is dynamic by default and you opt in per function with use cache, so the framework cache is the cheapest correct default: no extra service, tag-based invalidation, and cached parts join the prerendered shell. Cache only data that is the same for everyone who can see it, or key it on a verified user id, and invalidate its tags in the code that writes. Add a shared Redis-compatible cache (through use cache: remote or your data layer) when several instances or services must share entries and the hit rate is high. Use Postgres materialized views for heavy aggregates that many readers share, and fix slow queries with indexes before caching anything.
Lenses
The main risk is serving one user's data to another. A use cache or use cache: remote entry is shared by every caller that passes the same arguments, so check the session and permissions outside the cached function on every request, pass in the verified user or tenant id, and keep the cached helper unexported so no caller can pass someone else's id. A check inside a cached function is skipped on a cache hit. use cache: private keeps results in the browser only, never in a server cache. Next.js stores cache keys and tags in plain text, so key on stable ids, never on tokens or emails. Responses that set cookies or read the session must send Cache-Control: private, no-store, because Set-Cookie alone does not stop a shared cache from storing them (RFC 9111, section 7.3). Authenticate revalidation webhooks: an open endpoint lets anyone flush the cache.
Version notes
use cacheis experimental only; cache Postgres queries withunstable_cache(fn, keyParts, { tags, revalidate })and dedupe per request with Reactcache.fetchandGETRoute Handlers are not cached by default; opt in withcache: 'force-cache'orexport const dynamic = 'force-static'.revalidateTag(tag)takes one argument andupdateTagdoes not exist; callrevalidateTagorrevalidatePathin the Server Action that writes.- Reading
cookies()orheaders()makes the whole route dynamic, and they can't be read insideunstable_cache: pass values as arguments.
- Enable
cacheComponents: true(and setpartialPrefetchingexplicitly from 16.3); data is dynamic by default and you opt in withuse cache,cacheLifeandcacheTag. cookies(),headers()andsearchParamsthrow insideuse cacheanduse cache: remote; read them outside and pass values in, or useuse cache: private(browser only).revalidateTag(tag, profile)needs a second argument ('max', or{ expire: 0 }in webhooks);updateTag(tag)works only in Server Actions.- Uncached or runtime reads outside
<Suspense>are flagged as blocking routes; Cache Components needs the Node.js runtime (remove anyruntimeexport). - By default
use cacheentries live in per-instance memory, and all entries reset on every deploy;use cache: remoteneeds a cache handler from your host orcacheHandlers.
Verify checks
Two users with different permissions load the same page and endpoint twice; each sees only their own data, including on the second, cached request.
Calling the exported data getter without a valid session redirects or returns 401 even when a cached entry exists for another user.
Every response that sets a cookie or reads the session has Cache-Control with private or no-store, and never public or s-maxage.
No cached function takes a token, password or raw email as an argument, and no cacheTag value contains one.
The revalidation Route Handler returns 401 without a valid secret or signature and ignores unknown tags.
After a user saves a change through a Server Action, the next page view shows the new value without a reload or waiting for cacheLife to pass.
Writing a row invalidates every cached read tagged for it; list and detail views return the new data on the next request.
With two app instances, a write handled by one instance is visible on the other within the documented freshness window.
The materialized view has a unique index, and REFRESH MATERIALIZED VIEW CONCURRENTLY completes while concurrent reads keep returning rows.
The top queries in pg_stat_statements use index scans or have a recorded reason not to, and each cached query has an EXPLAIN ANALYZE plan on record.
Common mistakes
- Checking the session inside a
use cachefunction, so a cache hit skips the check. - Caching per-user or role-dependent data without the user, tenant or role in the arguments.
- Reading
cookies()orheaders()insideuse cache(it throws) instead of passing the values in. - Marking responses that set cookies or show account data
publicors-maxagefor a CDN. - Writing to Postgres without invalidating the tags that cache that data, or invalidating before the transaction commits.
- Calling
revalidateTag(tag)with one argument on Next.js 16 (deprecated), orupdateTagin a Route Handler (it throws). - Expecting
revalidateTagon one instance to clear the other instances or the CDN. - Caching a slow query instead of adding the missing index.
- Using
use cache: remotefor keys that are unique per request, so the hit rate is near zero. - Omitting
cacheLifeand relying on the implicitdefaultprofile.