---
title: "Caching in Next.js 16: use cache, cacheLife and cacheTag explained"
description: "How Cache Components work in Next.js 16: switching them on, caching with use cache, setting lifetimes with cacheLife, and invalidating with cacheTag, updateTag and revalidateTag."
url: https://www.danny.engineering/article/caching-in-nextjs-16-use-cache-cachelife-and-cachetag-explained
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:25:00.000Z
tags: ["Next.js"]
---

# Caching in Next.js 16: use cache, cacheLife and cacheTag explained

Caching in the Next.js App Router used to be a common source of confusion. In Next.js 14 and 15, `fetch` calls, route segments and the client router each had their own caching rules, and many developers discovered them only when a page refused to update.


Next.js 16 introduces a different model called **Cache Components**. Instead of caching things implicitly, nothing is cached unless you ask for it. You mark functions and components as cacheable with the `"use cache"` directive, set how long results live with `cacheLife`, and label them with `cacheTag` so you can clear them when your data changes.


This article is for developers building with the App Router who want to understand the new model properly. We will start with switching it on and build up to a real page that mixes static, cached and per-request content.


## The mental model


With Cache Components enabled, three kinds of content can live on the same page:

- **Static content** that does not depend on any data. It is prerendered at build time automatically.
- **Cached content** that comes from data but can be shared between requests. You mark it with `"use cache"` and it becomes part of the prerendered page.
- **Dynamic content** that must be fresh for every request, or that depends on the request itself (cookies, headers, search params). You wrap it in `Suspense` and it streams in at request time.

Next.js prerenders a static shell made of the first two, sends it immediately, and streams the dynamic parts in afterwards. This is Partial Prerendering (PPR), and with Cache Components it is simply how the App Router works rather than a separate experimental flag.


The key shift is that data fetching is **dynamic by default**. You opt in to caching, not out of it.


## Switching on Cache Components


Cache Components is enabled with a top-level option in your Next.js config. It became stable in Next.js 16.0, replacing the older `experimental.dynamicIO`, `experimental.useCache` and `experimental.ppr` flags.


```typescript
// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
};

export default nextConfig;
```


The `partialPrefetching` option was added in Next.js 16.3 and changes how links prefetch: the router fetches one reusable shell per route instead of one prefetch per link. The current docs recommend setting it explicitly alongside `cacheComponents`, and Next.js logs a warning if you leave it unset. If you are on a 16.x release earlier than 16.3, leave it out. New apps created with `create-next-app` have both options turned on already.


Two things to know before you switch it on in an existing app:

- Cache Components requires the Node.js runtime. Remove any `runtime` export from your route segments, including `runtime = 'edge'`.
- Route segment options like `revalidate` and `dynamic` belong to the old model. The Next.js team publishes a migration guide for moving these to `"use cache"` and `cacheLife`.

## Caching with "use cache"


The `"use cache"` directive marks an async function or component as cacheable. You can use it at three levels.


### Caching a data function


Put the directive at the top of the function body. The function must be async.


```typescript
// app/lib/products.ts
import { cacheLife } from 'next/cache';

export async function getProducts() {
  'use cache';
  cacheLife('hours');

  const res = await fetch('https://api.example.com/products');
  return res.json();
}
```


This is useful when the same data appears in several components, or when you want to cache data separately from the UI.


### Caching a component


Put the directive at the top of an async component to cache its rendered output.


```typescript
// app/components/featured.tsx
import { cacheLife } from 'next/cache';

export async function Featured({ category }: { category: string }) {
  'use cache';
  cacheLife('days');

  const items = await getFeatured(category);
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}
```


### Caching a whole file


Put the directive at the top of a file and every export in it becomes cached. Every exported function in the file must be async.


```typescript
// app/about/page.tsx
'use cache';

export default async function AboutPage() {
  const team = await getTeam();
  return <TeamList team={team} />;
}
```


For a page, remember that each layout, page and parallel route slot is its own module. If you want a whole route prerendered, each of those files needs the directive.


## How cache keys work


You never write a cache key by hand. Next.js builds one from:

- the build ID (or `deploymentId` if you set one), so a new deployment starts with a fresh cache
- an ID for the function, based on where it lives in your code
- the serialised arguments, or props for a component
- any variables the function captures from an outer scope

So `Featured` with `category="shoes"` and `Featured` with `category="hats"` get separate cache entries. This has two consequences worth remembering.


First, **arguments must be serialisable**. Strings, numbers, plain objects, arrays, dates, maps and sets are fine. Class instances, symbols and functions are not, unless you only pass them through without reading them (for example, `children` or a Server Action handed to a child).


Second, **you cannot read request data inside a cached scope**. Calling `cookies()`, `headers()` or reading `searchParams` inside `"use cache"` throws an error, and that applies to any helper the cached function calls too. Read the value outside and pass it in as an argument instead:


```typescript
// app/account/page.tsx
import { cookies } from 'next/headers';
import { Suspense } from 'react';

export default function AccountPage() {
  return (
    <Suspense fallback={<p>Loading your account...</p>}>
      <AccountContent />
    </Suspense>
  );
}

async function AccountContent() {
  const region = (await cookies()).get('region')?.value ?? 'uk';
  return <RegionalOffers region={region} />;
}

async function RegionalOffers({ region }: { region: string }) {
  'use cache';
  const offers = await getOffers(region); // region is part of the cache key
  return <OfferList offers={offers} />;
}
```


If you genuinely cannot restructure code this way, Next.js also provides `"use cache: private"`, which can read request APIs directly but only caches the result in the browser. Treat it as a last resort.


## Setting lifetimes with cacheLife


`cacheLife` sets how long a cached result lives. Import it from `next/cache` and call it inside the cached scope. It cannot be called at module level.


Every profile is made of three timings:

- **stale**: how long the browser can reuse the result without asking the server
- **revalidate**: after this, the next request gets the cached result while Next.js refreshes it in the background
- **expire**: after this long with no requests, the next request waits for fresh content

Next.js ships with these preset profiles:


| Profile   | stale      | revalidate | expire   |
| --------- | ---------- | ---------- | -------- |
| `default` | 5 minutes  | 15 minutes | never    |
| `seconds` | 30 seconds | 1 second   | 1 minute |
| `minutes` | 5 minutes  | 1 minute   | 1 hour   |
| `hours`   | 5 minutes  | 1 hour     | 1 day    |
| `days`    | 5 minutes  | 1 day      | 1 week   |
| `weeks`   | 5 minutes  | 1 week     | 30 days  |
| `max`     | 5 minutes  | 30 days    | 1 year   |


If you do not call `cacheLife`, the `default` profile applies. The docs recommend calling it in every cached scope anyway, so anyone reading the code can see the lifetime at a glance.


### Custom profiles


You can define named profiles in your config and use them by name:


```typescript
// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  cacheComponents: true,
  cacheLife: {
    editorial: {
      stale: 600, // 10 minutes
      revalidate: 3600, // 1 hour
      expire: 86400, // 1 day
    },
  },
};

export default nextConfig;
```


```typescript
export async function getArticles() {
  'use cache';
  cacheLife('editorial');
  return db.article.findMany();
}
```


For a one-off case, pass an object directly, for example `cacheLife({ revalidate: 900 })`. Any timing you leave out is taken from the `default` profile.


### Short lifetimes and the static shell


A very short lifetime cannot sensibly be prerendered. A cache with a `revalidate` of zero or an `expire` under five minutes is left out of the static shell and resolved at request time instead. Of the presets, only `seconds` falls into this category, so wrap components that use it in `Suspense`.


Nesting matters too. If a cached component without its own `cacheLife` renders a child with a short lifetime, Next.js raises an error during prerendering, because the parent would silently become short-lived as well. Adding an explicit `cacheLife` to the parent fixes it.


## Tagging with cacheTag


Time-based lifetimes are only half the story. When a user edits a product, you want the product page to update now, not in an hour. That is what tags are for.


Call `cacheTag` inside a cached scope to label the entry:


```typescript
// app/lib/products.ts
import { cacheLife, cacheTag } from 'next/cache';

export async function getProduct(id: string) {
  'use cache';
  cacheLife('max');
  cacheTag('products', `product-${id}`);

  return db.product.findUnique({ where: { id } });
}
```


A common pattern is a long lifetime like `max` combined with tags. The data stays cached until something actually changes, and you clear it on demand when it does.


## Invalidating with updateTag and revalidateTag


Next.js 16 gives you two functions for clearing tagged entries, and the difference between them matters.


### updateTag: show the user their own change


`updateTag` expires the tagged data immediately. The next request waits for fresh data rather than seeing the old version. It is designed for "read your own writes", where a user saves something and expects to see it straight away. It can **only** be called inside a Server Action.


```typescript
// app/products/actions.ts
'use server';

import { updateTag } from 'next/cache';

export async function renameProduct(id: string, formData: FormData) {
  const name = String(formData.get('name'));
  await db.product.update({ where: { id }, data: { name } });

  updateTag(`product-${id}`);
  updateTag('products');
}
```


When a Server Action calls `updateTag`, Next.js also re-renders the current route and sends the fresh UI back in the action's response.


### revalidateTag: refresh in the background


`revalidateTag` works in Server Actions and Route Handlers. In Next.js 16 it takes a second argument, a cache profile. The recommended value is `'max'`, which gives stale-while-revalidate behaviour: visitors keep seeing the cached version while a fresh one is generated in the background.


```typescript
// app/api/webhooks/cms/route.ts
import { revalidateTag } from 'next/cache';

export async function POST(request: Request) {
  const { productId } = await request.json();
  // check the webhook signature before trusting this request

  revalidateTag(`product-${productId}`, 'max');
  return Response.json({ revalidated: true });
}
```


This suits webhooks from a CMS or a background job, where nobody is waiting to see the result. Calling `revalidateTag` with only a tag still works but is the legacy form; it behaves like `updateTag`. Pass a profile so your intent is clear.


As a rule of thumb: use `updateTag` when the person who made the change is looking at the page, and `revalidateTag` with `'max'` when the change came from somewhere else.


## Putting it together


Here is a product page that uses all three kinds of content:


```typescript
// app/products/[id]/page.tsx
import { Suspense } from 'react';
import { cookies } from 'next/headers';
import { cacheLife, cacheTag } from 'next/cache';

export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  return (
    <main>
      <SiteHeader />
      <Suspense fallback={<p>Loading product...</p>}>
        {params.then(({ id }) => (
          <ProductDetails id={id} />
        ))}
      </Suspense>
      <Suspense fallback={<p>Loading your basket...</p>}>
        <Basket />
      </Suspense>
    </main>
  );
}

// Static: no data, prerendered automatically
function SiteHeader() {
  return <header>Our shop</header>;
}

// Cached: shared by every visitor, cleared by tag
async function ProductDetails({ id }: { id: string }) {
  'use cache';
  cacheLife('max');
  cacheTag(`product-${id}`);

  const product = await db.product.findUnique({ where: { id } });
  return <h1>{product?.name}</h1>;
}

// Dynamic: depends on the visitor's cookies, streams at request time
async function Basket() {
  const basketId = (await cookies()).get('basket')?.value;
  const basket = basketId ? await getBasket(basketId) : null;
  return <p>{basket ? `${basket.count} items` : 'Your basket is empty'}</p>;
}
```


The header and the `Suspense` fallbacks go into the static shell. Product details are cached and included once their `id` is known. The basket streams in for each visitor. If you forget the `Suspense` boundary around `Basket`, the dev overlay warns you that the route is blocking and suggests the fix.


## Where cached data lives


This is the part of the model that depends most on where you deploy, so it is worth being clear about what is and is not guaranteed.

- Results computed **at build time** become part of the prerendered output and are reused by later requests.
- Results computed **at request time** are stored in memory by default. On a self-hosted Node.js server that memory persists between requests. On serverless platforms, each request may hit a different instance, so these entries often do not survive between requests.
- `"use cache: remote"` lets a platform plug in a shared cache, such as a key-value store, at the cost of a network round trip and, often, platform fees.
- **No** **`"use cache"`** **entry survives a new deployment**, because the build ID is part of every key.

Hosting providers can replace the default cache handler, and their behaviour varies. If request-time caching matters to your app, check your host's documentation rather than assuming it works like local development.


To see what is happening, run your app with `NEXT_PRIVATE_DEBUG_CACHE=1` for verbose cache logs. In development, logs from cached functions are prefixed with `Cache`.


## Version support

- **Next.js 16.0**: Cache Components, `"use cache"`, `cacheLife` and `cacheTag` became stable. The `unstable_cacheLife` and `unstable_cacheTag` imports are deprecated. `updateTag` arrived, and `revalidateTag` gained its profile argument.
- **Next.js 16.3**: `partialPrefetching` was introduced as a separate option that requires `cacheComponents`.
- **Next.js 15**: `"use cache"` existed only as an experimental feature behind flags. The APIs changed before 16, so code written against 15 needs updating.
- Static exports (`output: 'export'`) do not support `"use cache"`.

The Next.js docs say both `cacheComponents` and `partialPrefetching` will be on everywhere in the next major release and the options will be removed. Exact timing has not been announced, so plan for it rather than rely on a date.


## When not to use it

- **Per-user data.** Do not cache a whole component that shows private information unless the user identifier is an argument, and even then think about memory use. Often `Suspense` and a fresh read is the right answer.
- **Data that must always be current.** Account balances, stock levels at checkout and anything security-sensitive should not sit behind a cache lifetime. Leave them dynamic.
- **Cheap, fast reads.** Caching has overhead and adds something else to reason about. A quick query against a local database may not need it.
- **Request-time caching on serverless without a shared store.** If your host does not persist in-memory entries, caching at request time may give you little benefit. Measure before relying on it.
- **Apps that are not ready to migrate.** If you depend heavily on the old route segment options or the Edge runtime, the previous caching model still works with `cacheComponents` turned off. Migrate when you can plan it.

## Wrapping up

- With Cache Components, data is dynamic by default and you opt in to caching with `"use cache"` on a function, component or file.
- Arguments and captured variables form the cache key, so they must be serialisable, and request APIs like `cookies()` must be read outside and passed in.
- Call `cacheLife` in every cached scope, using a preset or your own named profile, so the lifetime is obvious.
- Tag entries with `cacheTag`, then use `updateTag` in Server Actions for instant updates and `revalidateTag` with `'max'` for background refreshes.
- Where request-time cache entries live depends on your host, so check its behaviour before relying on it.

## Related reading

- [Caching in Next.js](https://nextjs.org/docs/app/getting-started/caching)
- [use cache directive](https://nextjs.org/docs/app/api-reference/directives/use-cache)
- [cacheLife reference](https://nextjs.org/docs/app/api-reference/functions/cacheLife)
