Next.jsMedium

How do you use cache tags in Next.js?

Attach tags to cached data, then invalidate by tag after changes. With Cache Components, call cacheTag("posts", "post:42") inside a "use cache" scope; in the previous model, pass next: { tags: [...] } to fetch or tags to unstable_cache. Invalidate with revalidateTag(tag, "max") or updateTag(tag).

Designing tags

  • Collection tags: "posts" for any list of posts.
  • Entity tags: "post:42" for one record.
  • Relationship tags: "user:7:posts" for one user's posts.
  • One cached function can have several tags, so updating post 42 can invalidate both "post:42" and "posts".

Rules

  • Tags are case-sensitive strings, up to 256 characters each.
  • A single cacheTag() call accepts up to 128 tags; extra or too-long tags are dropped with a warning.
  • cacheTag only works inside a cache scope. Calling it at module scope or in Proxy throws.
  • Tags can be computed from arguments or fetched data, for example tagging a product list with each product ID.

Choosing the invalidation function

  • updateTag in Server Functions when the user who made the change should see it immediately.
  • revalidateTag(tag, "max") from webhooks, cron jobs or for changes where a moment of staleness is fine.

Why tags beat paths

Data appears on many pages (a product shows up on its page, category lists, search and the home page). Invalidating by tag refreshes every place it is used without listing paths.

Debugging

In dev, logging the tags returned by your data functions helps. Platforms like Vercel show cache tag hits and purges in their dashboards.

Code example

tsx
1// lib/products.ts
2import { cacheLife, cacheTag } from "next/cache";
3import { db } from "@/lib/db";
4
5export async function getProduct(id: string) {
6 "use cache";
7 cacheLife("days");
8 cacheTag("products", `product:${id}`);
9 return db.product.findUnique({ where: { id } });
10}
11
12export async function getCategory(slug: string) {
13 "use cache";
14 cacheLife("hours");
15 const products = await db.product.findMany({ where: { category: slug } });
16 // Tag the list with every product it contains
17 cacheTag(`category:${slug}`, ...products.map((p) => `product:${p.id}`));
18 return products;
19}
20
21// app/admin/actions.ts
22// "use server";
23// export async function updateProduct(id: string, data: { price: number }) {
24// await db.product.update({ where: { id }, data });
25// updateTag(`product:${id}`); // refreshes the product page AND every category list containing it
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.

Open in study app