Deviopath › Next.js

cacheLife Profiles

Hard · Caching

With Cache Components (cacheComponents: true), you cache a function or component with the "use cache" directive and set its lifetime with cacheLife(profile). A profile has three numbers (in seconds):

- stale: how long the client router may reuse the data without asking the server.

- revalidate: after this age, the next request is served the cached value while the server regenerates it in the background.

- expire: after this age, the next request must wait for fresh content.

The built-in profiles (from the cacheLife docs):

- default: stale 300, revalidate 900, expire never (Infinity)

- seconds: stale 30, revalidate 1, expire 60

- minutes: stale 300, revalidate 60, expire 3600

- hours: stale 300, revalidate 3600, expire 86400

- days: stale 300, revalidate 86400, expire 604800

- weeks: stale 300, revalidate 604800, expire 2592000

- max: stale 300, revalidate 2592000, expire 31536000

Write cacheLifeState(profile, ageSeconds, config). profile is a profile name or an inline object. config is the cacheLife object from next.config.ts (optional).

- Resolving: config.default (if any) is merged over the built-in default. A named profile from config replaces the built-in profile with the same name. Any property missing from a config profile or an inline object is taken from the resolved default (so {} means default).

- An unknown name returns { error: 'Unknown cacheLife profile "<name>"' }.

- If the resolved profile has expire <= revalidate, return { error: "expire must be longer than revalidate" }.

- server: "fresh" if age < revalidate, "stale" if age < expire, otherwise "expired".

- client: the router enforces a minimum stale time of 30 seconds, so it is "reuse" if age < Math.max(stale, 30), otherwise "refetch".

- prerender: "excluded" if revalidate === 0, expire < 300 or stale < 30 (a dynamic hole resolved at request time); "not-in-shell" if stale < 300; otherwise "shell".

Return { stale, revalidate, expire, server, client, prerender }.

Next: Load More with a Server Action