Next.js Caching & Revalidation
Next.js caching is the feature that decides whether your page is served from a fast stored copy or rebuilt from scratch on every visit. When it works, users see instant pages and your database does less work. When it goes wrong, users see old data and wonder why their changes disappeared. This tutorial focuses on the newer Cache Components model in Next.js 16, because the caching rules changed significantly from earlier versions.
You will learn how to enable Cache Components in next.config.ts, mark a function as cacheable with the 'use cache' directive, control its lifetime with cacheLife, and invalidate it on demand with cacheTag and revalidateTag. You will also see how updateTag differs from revalidateTag for read-your-own-writes, and how to avoid the stale-data mistakes that catch most beginners.
If you are new to data fetching, read Next.js Data Fetching first. Caching builds directly on how and where you fetch. The mutation side, covered in Next.js Forms & Server Actions, is where invalidation usually happens.
Version note: The code and API names in this tutorial were written for Next.js 16 with the App Router. Cache Components became the recommended model starting with Next.js 16.4, and all new apps created with create-next-app now enable it by default . If you are on an earlier version, check the official docs for the correct flag and function names.
What Is Next.js Caching with Cache Components?
Next.js caching with Cache Components is an opt-in system where you mark specific functions or components with the 'use cache' directive. Next.js stores their return value and reuses it for future requests. You control how long the cache lives with cacheLife and how to invalidate it with cacheTag .
Here is the smallest useful example. It caches a database query for one hour:
// app/lib/users.ts
import { cacheLife } from 'next/cache';
export async function getUsers() {
'use cache';
cacheLife('hours');
return db.query('SELECT * FROM users');
}
Output: The first call runs the query and stores the result. Later calls within the cache lifetime return the stored result without touching the database. After the lifetime ends, the next request triggers a background refresh while serving the old result briefly.
How it works: The 'use cache' directive at the top of the function body marks the function as cacheable. Next.js creates a cache key from the function arguments and any values it reads from the parent scope. cacheLife('hours') applies a preset profile that controls how long the client can use the cached data, when the server refreshes it, and when it expires completely .
Enabling Cache Components in next.config.ts
Cache Components is not automatic in existing projects. You must enable it in next.config.ts with the cacheComponents flag .
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;
Output: After restarting the dev server, the 'use cache' directive, cacheLife, and cacheTag become available. Without this flag, the 'use cache' directive is not recognized.
How it works: The flag tells Next.js to use the Cache Components model instead of the older fetch-based caching options. When enabled, route segment configs like dynamic, revalidate, and fetchCache are replaced by use cache and cacheLife. If your project still exports those older configs, Next.js will report an error .
Controlling Cache Lifetime with cacheLife
cacheLife sets the lifetime of a cached function or component. You can use a preset profile like 'seconds', 'minutes', 'hours', 'days', 'weeks', or 'max', or pass an object with stale, revalidate, and expire values .
// app/lib/posts.ts
import { cacheLife } from 'next/cache';
export async function getLatestPosts() {
'use cache';
cacheLife({
stale: 60,
revalidate: 300,
expire: 3600,
});
return db.query('SELECT * FROM posts ORDER BY created_at DESC LIMIT 10');
}
Output: Clients can reuse the cached list for 60 seconds without checking the server. After 300 seconds, the next request triggers a background refresh. After 3600 seconds with no requests, the next request waits for fresh data.
How it works: The three values control different phases. stale is how long the client treats the data as fresh. revalidate is how often the server regenerates the cache in the background. expire is the hard limit after which stale content is no longer served and the next request blocks until fresh data is ready. The expire value must be longer than revalidate .
Tagging Cached Data with cacheTag
cacheTag assigns one or more string labels to a cached function or component. You can later invalidate every entry with that tag without knowing which functions or routes created them .
// app/lib/products.ts
import { cacheLife, cacheTag } from 'next/cache';
export async function getProducts() {
'use cache';
cacheLife('hours');
cacheTag('products');
return db.query('SELECT * FROM products');
}
Output: The product list is cached under the tag 'products'. When you call revalidateTag('products', 'max') or updateTag('products') from a Server Action, the next request for this data fetches fresh results.
How it works: Tags are case-sensitive and must be unique enough to avoid accidental collisions. You can pass multiple tags in one call: cacheTag('products', 'featured'). The same tag can be reused across many cached functions, so one invalidation refreshes all of them. Tags are idempotent; applying the same tag twice has no extra effect .
Time-Based vs On-Demand Revalidation
Revalidation is the process of updating cached data. There are two strategies: time-based, where the cache refreshes automatically after a set duration, and on-demand, where you trigger a refresh manually after a mutation .
| Strategy | How it works | Best for | API |
|---|---|---|---|
| Time-based | Cache refreshes automatically after a duration | Data that changes on a predictable schedule | cacheLife |
| On-demand (stale-while-revalidate) | Serves stale data briefly while fresh data loads | Blog posts, product catalogs, content where a short delay is fine | revalidateTag(tag, 'max') |
| On-demand (immediate) | Expires cache immediately; next request waits for fresh data | Read-your-own-writes after a user creates or updates something | updateTag(tag) in Server Actions |
How it works: Time-based revalidation is passive; you set it once and the cache maintains itself. On-demand revalidation is active; you call a function after a mutation. The two can be combined: use cacheLife for a baseline freshness guarantee, and revalidateTag or updateTag when you know something changed right now .
revalidateTag, updateTag, and revalidatePath
Next.js provides three on-demand functions, and choosing the right one matters for what the user sees after a mutation.
revalidateTag for stale-while-revalidate
// app/actions.ts
'use server';
import { revalidateTag } from 'next/cache';
export async function updateProduct(formData: FormData) {
const id = formData.get('id');
await db.query('UPDATE products SET name = $1 WHERE id = $2', [
formData.get('name'),
id,
]);
revalidateTag('products', 'max');
}
Output: The next visitor sees the old product list briefly while Next.js regenerates it in the background. After the background refresh finishes, new visitors see fresh data.
How it works: revalidateTag marks matching entries as stale. The second argument 'max' sets a long stale window, so requests are always served stale content while revalidation runs. This is the recommended profile for content where a small delay is acceptable . If you need immediate visibility, use updateTag instead.
updateTag for read-your-own-writes
// app/actions.ts
'use server';
import { updateTag } from 'next/cache';
import { redirect } from 'next/navigation';
export async function createPost(formData: FormData) {
const post = await db.query(
'INSERT INTO posts (title) VALUES ($1) RETURNING id',
[formData.get('title')]
);
updateTag('posts');
redirect(`/posts/${post.id}`);
}
Output: The user who created the post is redirected to the new post and sees fresh data immediately. The cache is expired synchronously, not in the background.
How it works: updateTag can only be called inside a Server Action. It immediately expires the cache for the tag and refreshes the calling route. Use it when the user must see their own change right away, such as after submitting a form or creating a resource . For webhooks and Route Handlers, use revalidateTag instead.
revalidatePath for path-based invalidation
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
export async function updateSettings(formData: FormData) {
await db.query('UPDATE settings SET theme = $1', [formData.get('theme')]);
revalidatePath('/settings');
}
Output: The /settings page cache is invalidated. The next visit renders with fresh data.
How it works: revalidatePath takes a path string and an optional type of 'page' or 'layout'. For dynamic routes, pass the route pattern and 'page': revalidatePath('/posts/[slug]', 'page'). Prefer tag-based invalidation when possible, because it is more precise and avoids refreshing pages that did not change .
Common Mistakes and Best Practices
- Caching user-specific data under a global tag. If
getUserProfile()is cached with the tag'profile'and no user ID in the cache key, one user's profile can be served to another. Include user-specific values as function arguments so they become part of the cache key, or avoid caching personalized data entirely. - Forgetting that
updateTagonly works in Server Actions. CallingupdateTagfrom a Route Handler throws the errorupdateTag can only be called from within a Server Action. UserevalidateTagin Route Handlers and webhooks . - Using
revalidateTagwhen the user must see their change immediately. With the'max'profile,revalidateTagserves stale data while refreshing. If the user just submitted a form, they will see old data. UseupdateTagin Server Actions for read-your-own-writes. - Mixing Cache Components with old route configs. When
cacheComponents: trueis set, exportingdynamic,revalidate, orfetchCachefrom a route segment causes an error. Remove the old configs and useuse cachewithcacheLifeinstead . - Caching without a
cacheLifecall. Next.js applies an implicit default profile, but it is better to be explicit. Pair every'use cache'with acacheLifecall so you know exactly how long the data lives .
Real-World Example: A Cached Product List with Invalidation
This example combines 'use cache', cacheLife, cacheTag, and a Server Action that invalidates the cache after creating a product.
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;
// app/lib/products.ts
import { cacheLife, cacheTag } from 'next/cache';
export type Product = {
id: number;
name: string;
price: number;
};
export async function getProducts(): Promise<Product[]> {
'use cache';
cacheLife('hours');
cacheTag('products');
const result = await db.query('SELECT id, name, price FROM products');
return result as Product[];
}
// app/actions.ts
'use server';
import { updateTag } from 'next/cache';
import { revalidatePath } from 'next/cache';
export async function addProduct(formData: FormData) {
const name = formData.get('name');
const price = formData.get('price');
if (typeof name !== 'string' || name.trim().length === 0) {
return { error: 'Name is required' };
}
await db.query('INSERT INTO products (name, price) VALUES ($1, $2)', [
name.trim(),
Number(price),
]);
updateTag('products');
revalidatePath('/products');
}
Line-by-line explanation:
next.config.tsenables Cache Components. Without this, the'use cache'directive is ignored.getProductsis marked with'use cache'and tagged'products'. The result is cached for the'hours'profile.addProductis a Server Action. It validates the name, inserts the product, and callsupdateTag('products').updateTagimmediately expires every cached entry tagged'products'. The next call togetProductsfetches fresh data.revalidatePath('/products')also refreshes the page route, so the user who submitted the form sees the new product without a manual reload.
If you need stale-while-revalidate instead of immediate expiration, replace updateTag('products') with revalidateTag('products', 'max'). That is better for background jobs or webhooks where a short delay is acceptable.
Summary
- Next.js caching with Cache Components is opt-in. Enable
cacheComponents: trueinnext.config.tsand mark cacheable functions with'use cache'. cacheLifecontrols cache duration with profiles or explicitstale,revalidate, andexpirevalues.cacheTaglabels cache entries so you can invalidate them later without knowing which functions created them.- Use
revalidateTag(tag, 'max')for stale-while-revalidate. UseupdateTag(tag)in Server Actions when the user must see their change immediately. revalidatePathinvalidates a specific route. Prefer tag-based invalidation when possible for precision.- Always include user-specific values in function arguments so they become part of the cache key and do not leak between users.
Now that your data is cached and fresh, the next step is making your images load just as fast. Continue with Next.js Image Optimization.
Frequently Asked Questions
Do I need to enable Cache Components to use use cache?
Yes. The 'use cache' directive is part of the Cache Components model, which requires cacheComponents: true in next.config.ts. Without the flag, Next.js does not recognize the directive and your functions run uncached. New projects created with create-next-app in recent versions have it enabled by default.
What is the difference between revalidateTag and updateTag?
revalidateTag marks cache entries as stale and serves old data while fresh data loads in the background. updateTag immediately expires the cache and makes the next request wait for fresh data. Use updateTag in Server Actions when a user must see their own change right away. Use revalidateTag for webhooks and background refreshes.
Can I call revalidateTag from a Client Component?
No. revalidateTag only works on the server. It can be called from Server Actions and Route Handlers, but not from Client Components or Proxy. If you need to trigger invalidation from the client, call a Server Action that runs revalidateTag or updateTag for you.
What happens if I cache data without calling cacheLife?
Next.js applies an implicit default profile. The data still gets a cache lifetime, but you do not control how long it lives or when it refreshes. For predictable behavior, always call cacheLife inside the cached function. This makes the cache duration explicit and easy to reason about when debugging stale data.
Why does my page still show old data after a mutation?
The page or data function is likely still cached and has not been invalidated. Check that you called updateTag or revalidateTag with the correct tag after the mutation. Also verify that the tag on the cached function matches the tag you invalidated. If you used revalidateTag with the 'max' profile, stale data is served briefly while the refresh happens in the background.
Practice Exercises
Easy: Enable Cache Components
Add the Cache Components flag to a next.config.ts file. Then create a cached function that returns a static list of three names and log the result.
Show solution
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;
// app/lib/names.ts
import { cacheLife } from 'next/cache';
export async function getNames() {
'use cache';
cacheLife('hours');
return ['Asha', 'Ravi', 'Meera'];
}
The flag makes 'use cache' available, and cacheLife('hours') sets the cache duration.
Easy: Tag a cached function
Add the tag 'team' to the getNames function from the previous exercise.
Show solution
// app/lib/names.ts
import { cacheLife, cacheTag } from 'next/cache';
export async function getNames() {
'use cache';
cacheLife('hours');
cacheTag('team');
return ['Asha', 'Ravi', 'Meera'];
}
cacheTag('team') labels the cache entry so it can be invalidated later with updateTag('team') or revalidateTag('team', 'max').
Medium: Invalidate a tag from a Server Action
Write a Server Action that adds a name to a database (simulated with a log) and immediately invalidates the 'team' tag with updateTag.
Show solution
// app/actions.ts
'use server';
import { updateTag } from 'next/cache';
export async function addName(formData: FormData) {
const name = formData.get('name');
if (typeof name !== 'string' || name.trim().length === 0) {
return { error: 'Name is required' };
}
console.log('Adding name:', name.trim());
updateTag('team');
}
updateTag('team') expires the cache immediately, so the next call to getNames fetches fresh data.
Challenge: Use revalidateTag for a webhook-style refresh
Create a Route Handler that accepts a tag as a query parameter and calls revalidateTag with the 'max' profile.
Show solution
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
import { type NextRequest } from 'next/server';
export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag');
if (!tag) {
return Response.json({ error: 'Missing tag' }, { status: 400 });
}
revalidateTag(tag, 'max');
return Response.json({ revalidated: true, tag });
}
revalidateTag works in Route Handlers, unlike updateTag. The 'max' profile serves stale content while the refresh happens in the background.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
