v(i)b(e)c(o)d(e)4u.com
Назад на форум vbcd4u.com
🔥 Нейросети2026-11-17T10:02:00.000Z▲ 0 upvotes

Caching in Next.js 15: fetch without default cache, revalidateTag and unstable_cache

@murdasoftРедакция vbcd4u · MurdaSoft
Открыть все обсуждения →

What changed when moving to 15

In Next.js 14, fetch in server components was cached by default. In 15 this behavior was reversed:

  • fetch is not cached unless you explicitly specify cache: 'force-cache' or next.revalidate.
  • GET handlers in Route Handlers are not cached by default.
  • Client Router Cache for pages no longer holds segments of 30 seconds: staleTime for dynamic pages is zero.

A typical story after an update: the load on the API or database has increased because every page request now retrieves data. Or vice versa: the data does not seem to be cached, but the page still shows the old one.

Trap: no fetch cache, but the page is static

If the route does not use dynamic APIs (cookies(), headers(), searchParams, connection()), Next.js will pre-render it at next build. Uncached fetch will be executed once at build time, and the result will remain in the HTML forever. In development mode, everything looks dynamic, so the problem only appears in production.

Check - output next build: ○ means static route, ƒ means dynamic.

Explicitly make the route dynamic:

// app/dashboard/page.tsx
import { connection } from "next/server";

export default async function Page() {
  await connection(); // дальше всё выполняется на каждый запрос
  const stats = await fetch("https://api.example.com/stats").then((r) => r.json());
  return <Stats data={stats} />;
}

Or vice versa, make the static route periodically updated via export const revalidate = 300 in the page file.

Caching fetch with tags

// lib/data/posts.ts
export async function getPosts() {
  const res = await fetch("https://cms.example.com/posts", {
    next: { revalidate: 3600, tags: ["posts"] },
  });
  if (!res.ok) throw new Error(`cms ${res.status}`);
  return res.json() as Promise<Post[]>;
}

export async function getPost(slug: string) {
  const res = await fetch(`https://cms.example.com/posts/${slug}`, {
    next: { revalidate: 3600, tags: ["posts", `post:${slug}`] },
  });
  if (res.status === 404) return null;
  return res.json() as Promise<Post>;
}

revalidate: 3600 - spare lifetime. The main mechanism is tag invalidation at the time of data change.

revalidateTag and revalidatePath

// app/admin/posts/actions.ts
"use server";
import { revalidatePath, revalidateTag } from "next/cache";

export async function publishPost(slug: string) {
  await requireEditor();          // проверка прав — первой строкой
  await cms.publish(slug);
  revalidateTag(`post:${slug}`);  // точечно: одна статья
  revalidateTag("posts");         // списки, где она может быть
  revalidatePath("/sitemap.xml");
}

Difference between functions:

  • revalidateTag(tag) marks as stale all data cache entries with this tag, no matter what pages they are used on.
  • revalidatePath(path) invalidates a specific route. For a dynamic segment, the template and type are indicated: revalidatePath("/blog/[slug]", "page") - all pages of articles, revalidatePath("/", "layout") - everything in general.

Tags are more precise: you invalidate the data, rather than guessing at which URLs it appears. revalidatePath is convenient when the data did not come through fetch (for example, from a database without a wrapper).

Both functions work in Server Actions and Route Handlers. For a webhook from a CMS, make a Route Handler with a secret check that calls revalidateTag.

unstable_cache for queries to the database

fetch is cached via next, but a request to Postgres via ORM is not. There is unstable_cache for it:

// lib/data/stats.ts
import { unstable_cache } from "next/cache";
import { db } from "@/lib/db";

export const getCategoryCounts = unstable_cache(
  async (locale: string) => {
    const { rows } = await db.query(
      "SELECT category, count(*)::int AS n FROM threads WHERE locale = $1 GROUP BY category",
      [locale]
    );
    return rows;
  },
  ["category-counts"],               // часть ключа; аргументы добавляются автоматически
  { revalidate: 600, tags: ["threads"] }
);

Restrictions: you cannot call cookies() and headers() inside a function - pass everything that depends on the request as arguments. The result must be serialized to JSON, so the Date objects will be returned as strings. The unstable_ prefix means that the API may change. In Next.js 16, the caching model has changed again (use cache directive and changes to revalidateTag), so check the documentation for your version when upgrading.

How to understand what is cached

  1. 1.Enable query logging in next.config.ts:
const nextConfig = { logging: { fetches: { fullUrl: true } } };
export default nextConfig;

The server console will display lines indicating a cache hit or miss for each fetch.

  1. 2.For self-hosted next start see the response header x-nextjs-cache: HIT, STALE or MISS for pages from the cache.
  1. 3.Check on the next build && next start build, not in next dev: in development mode the cache behaves differently.

Common mistakes

  • Expect revalidateTag to update data received without a tag. The tag is bound at the time of the request.
  • Invalidate from the client component. Functions from next/cache only work on the server.
  • Several instances next start behind the balancer. The default cache is in the file system of each instance, and revalidateTag on one will not affect the others. You need a generic cacheHandler (for example, on Redis).
  • Cache personal data under a common key. If the answer depends on the user, the user ID must be part of the key, and it is better not to cache such data at all.

When the cache is not needed

It’s easier to leave admin panels, personal accounts, and pages with real-time data completely dynamic. A cache is justified where the same data is read by many users more often than it is changed.

Обсуждение (0)

Ещё на vbcd4u.com