All articles

Don't cache failures in Next.js 16 "use cache": throw, catch outside

In Next.js 16 with cacheComponents, anything a "use cache" function returns is stored as its result, including a fallback you return from a catch block. If the function catches an upstream error and returns null, an empty list or a "not found" marker, that failure is now cached for the whole cache life. The fix is to let the cached function throw, and do the try/catch in a plain, uncached function that calls it. A throw ends the cache entry's stream with an error, and a cache handler that discards errored entries stores nothing.

How an outage turned into cached 404s

The site is a decoupled Drupal back end with a Next.js 16 front end on the App Router. Every request for a content path first asks Drupal what that path is: the Decoupled Router module's translate-path endpoint resolves an alias to an entity and reports Drupal's cache tags for it. That answer barely changes, so the front end wraps the lookup in "use cache" and tags the entry with Drupal's cache tags, so a content edit in Drupal revalidates it.

The first version handled failure inside the cached function. If the translate-path call threw, it tagged the entry with a few catch-all tags, set a short cacheLife and returned a result marked as failed. The page then rendered a 404 for it.

That looks careful. The short cache life was there precisely so a failure wouldn't stick. But it still means a brief Drupal outage, or a single timeout, produces a cached "this path doesn't exist" for every path that happened to be requested during it, and those 404s keep being served after Drupal recovers, until the short timer runs out or a matching tag happens to be revalidated. For a site whose pages are otherwise cached for a long time, a stretch of cached 404s on real pages is the worst outcome available: users and crawlers both see content disappear.

The same pattern was hiding in a second place. A landing page fetched its list filters from Drupal, logged any error and returned whatever it had collected so far, usually an empty array. That ran inside the cached page data, so an error became a landing page with no filters, cached.

Why returning a fallback from "use cache" caches it

From the cache's point of view, a function that returns normally has succeeded. "use cache" serialises the return value and stores it with the tags and cache life collected during the call. It cannot tell an empty list that means "there are no filters" from an empty list that means "the request failed", because by the time it sees the value that distinction is gone. Any catch inside the cached scope converts an error into data.

A throw is different. When the function throws, Next.js still hands the entry to the cache handler, but the entry's value stream ends with an error instead of closing normally. The cacheHandlers documentation is explicit that a handler has to decide what to do with an interrupted value, and recommends discarding it. The Redis handler this site uses already did that: when reading the stream fails, it skips the write. So a thrown error leaves no entry behind, and the next request tries Drupal again.

If you rely on a cache handler you didn't write, check what it does with an errored stream before relying on this. The behaviour lives in the handler, not in the directive.

How to move the catch outside the cached function

Split the function in two: a cached inner function that throws on any failure, and an exported, uncached wrapper that catches and turns the error into whatever the caller needs. A minimal example:

import { cacheLife, cacheTag } from "next/cache";

type Resolved =
  | { kind: "found"; entityId: string }
  | { kind: "missing" }
  | { kind: "failed" };

// Uncached: an error here is handled per request and never stored.
export async function resolvePath(path: string): Promise<Resolved> {
  try {
    return await resolvePathCached(path);
  } catch (error) {
    console.error("Path lookup failed", path, error);
    return { kind: "failed" };
  }
}

async function resolvePathCached(path: string): Promise<Resolved> {
  "use cache";
  cacheTag(`path:${path}`);

  const res = await fetch(`${process.env.CMS_URL}/router/translate-path?path=${encodeURIComponent(path)}`);
  if (res.status === 404) {
    cacheLife("minutes");
    return { kind: "missing" };
  }
  if (!res.ok) throw new Error(`translate-path returned ${res.status}`);

  const body = await res.json();
  cacheTag(...body.cacheTags);
  return { kind: "found", entityId: body.entity.uuid };
}

Note what stays inside the cached function: a genuine 404 from the back end is a real answer and is cached, with a short life so a newly published page appears soon. Only failures, where the back end didn't give an answer at all, throw. The page can then treat failed differently from missing: render an error state or let the error boundary show, rather than a 404.

For the landing page filters the change was smaller still: keep the log line, then rethrow. The page data function that called it is cached, so the rethrow propagates out of the cached scope and nothing is stored.

What to check in your own cached functions

Search for "use cache" and read each function's error paths. The patterns to look for:

  • A catch that returns a value: null, [], {}, a default object or a "not found" flag.
  • A helper called from inside the cached function that swallows its own errors and returns something empty. The catch doesn't have to be in the cached function itself to cause this.
  • fetch calls whose non-2xx responses aren't checked, so a 500 or 503 body gets parsed and returned as data.
  • A short cacheLife used to make a cached failure "safe". It narrows the window but still serves the failure to everyone in it.

What I like about the split is that the caching rule becomes readable from the code's shape: everything inside the cached function is an answer worth keeping, and everything the wrapper adds is per-request. It also makes the failure visible in the logs on every failed request, rather than once per cache entry.

Key takeaways

  • A "use cache" function cannot tell a fallback from real data, so any value returned from a catch inside it is cached for the full cache life.
  • Let the cached function throw on failure and catch the error in an uncached wrapper that decides what the page shows.
  • A throw leaves the cache entry's stream errored, and whether that entry is stored is the cache handler's decision, so confirm your handler discards errored entries.
  • Keep a real "not found" answer inside the cache with a short life, and keep "the back end didn't answer" out of it entirely.

Written by Artem Shymko, a senior software engineer in Belgium working on Drupal, .NET and LLM features. Get in touch if you are working on something similar.

  • Next.js
  • Caching
  • Drupal
  • Decoupled