Skip to content
iD-SIGN

Auth errors and "use cache" in Next.js

Put "use cache" on a function that reads from an API, and a refused request becomes a trap: handled the obvious way, the 403 is either cached or lost. We show both traps, a small pattern that avoids them, and how to keep it that way with a lint rule, a test and a production build.

7 min readpublished 12/2026

In this article 8 chapters
  1. The setup
  2. The first trap is calling forbidden() inside the cache
  3. The second trap is classifying outside the cache
  4. Classify inside, decide outside
  5. A lint rule to keep it fixed
  6. Simulate the boundary in tests
  7. Verify on a production build
  8. Summary

Next.js Cache Components make data caching easy: put "use cache" at the top of a function and its result is stored. Then the API refuses a request, and things get subtle. The obvious ways of handling that refusal are either silently cached or silently broken, and neither is caught by a unit test or a type check. The first even looks correct in the browser.

This article covers both traps and a small pattern that avoids them.

The setup

We have a typed API client and a cached read:

javascript
class ApiError extends Error {
  constructor(public status: number) {
    super(`API responded ${status}`);
  }
}

async function loadInvoice(accountId: string, id: string) {
  "use cache";
  cacheLife("minutes");
  // throws ApiError(403) when the account may not see the invoice
  return api.get(`/accounts/${accountId}/invoices/${id}`);
}

When the API says 403, we want the page to render forbidden.tsx.

"use cache" needs cacheComponents: true in next.config. A shared cache can't read cookies() or headers(), so whatever identifies the caller goes in as an argument and becomes part of the cache key. The shared cache is used on purpose: "use cache: private" isn't kept on the server between requests in production, so it doesn't show the trap below.

Two consequences of the shared cache are easy to miss. The API call inside it can't use the user's session, so it needs a credential that doesn't vary per request; passing the user's token as an argument would put the token into the cache key. And successful reads are cached too: after access is revoked, the cached data is still served until the entry revalidates, so tag entries with cacheTag and revalidate them when permissions change.

The first trap is calling forbidden() inside the cache

javascript
async function loadInvoice(accountId: string, id: string) {
  "use cache";
  try {
    return await api.get(`/accounts/${accountId}/invoices/${id}`);
  } catch (e) {
    if (e instanceof ApiError && e.status === 403) forbidden(); // ❌
    throw e;
  }
}

The page shows the correct 403, so it looks fine. But forbidden(), notFound(), unauthorized() and redirect() are router errors. Next treats them as a normal way for a render to end, not as a failure, so the cache entry is written with the interrupt inside it and replayed for the entry's whole lifetime.

A permanent 403 being replayed is mostly harmless. Two cases are not. A 401 caused by a brief token problem is served to every caller with the same arguments. A 404 cached before a record existed keeps showing after the record is created, for example on the detail page you redirect to right after a create.

How long that lasts depends on the cache handler. In production, the default in-memory handler drops an entry once it is older than revalidate, which is 1 minute for the built-in minutes profile; next dev keeps it until expire. A custom handler that serves stale entries while it refreshes them can keep returning the error until expire (1 hour). On a production build the symptom is easy to see: the first refused render calls the API, and the later ones don't.

The second trap is classifying outside the cache

So we move the check one level up:

javascript
const invoice = await loadInvoice(accountId, id).catch((e) => {
  if (e instanceof ApiError && e.status === 403) forbidden(); // ❌ never true
  throw e;
});

Now the 403 turns into the generic error page. A "use cache" function is a serialization boundary, like a Server Component payload, and errors are serialized too. The class never makes it across; the only property that reliably survives is digest. On the outside you get a plain Error, so instanceof (or any isXxxError() helper) is always false. In next dev the error's name and message survive as well, so a check like e.message.includes("403") passes in development and fails in production.

So you can't raise the interrupt inside the cache, and you can't recognise the error outside it.

Classify inside, decide outside

Decide what happened inside, while the error still has its class. Send that verdict across the boundary in the one channel that survives, digest. Then raise the interrupt outside.

One detail matters: Next treats any error it doesn't recognise as one of its own as a failed cache fill. The custom digest only carries the verdict, so it must not reuse one of Next's digests. The default cache handler then stores nothing, and the read runs again on the next render. A custom cache handler (Redis and the like) is allowed to store a partial result that ended in an error, so check what yours does.

javascript
type Denial = "forbidden" | "unauthorized" | "notFound";

const DIGEST = {
  forbidden: "CACHED_READ_FORBIDDEN",
  unauthorized: "CACHED_READ_UNAUTHORIZED",
  notFound: "CACHED_READ_NOT_FOUND",
} as const satisfies Record<Denial, string>;

// Derived from the table above, so adding a verdict can't leave this side behind.
const DENIAL_BY_DIGEST = new Map<string, Denial>(
  Object.entries(DIGEST).map(([denial, digest]) => [digest, denial as Denial]),
);

function classify(error: unknown): Denial | null {
  if (!(error instanceof ApiError)) return null;
  if (error.status === 401) return "unauthorized";
  if (error.status === 403) return "forbidden";
  if (error.status === 404) return "notFound";
  return null;
}

Inside the cache, mark the error instead of ending the render:

javascript
export function markForOutside(error: unknown): never {
  const denial = classify(error);
  if (!denial) throw error; // anything else: rethrow as-is; the fill fails, nothing stored
  throw Object.assign(new Error(`Cached read denied: ${denial}`), {
    digest: DIGEST[denial],
  });
}

Outside the cache, turn the digest back into the interrupt:

javascript
export function decideOutside<T>(read: Promise<T>): Promise<T> {
  return read.catch((error: unknown) => {
    const digest = (error as { digest?: unknown })?.digest;
    const denial = typeof digest === "string" ? DENIAL_BY_DIGEST.get(digest) : undefined;
    if (denial === "forbidden") forbidden();
    if (denial === "unauthorized") unauthorized();
    if (denial === "notFound") notFound();
    throw error;
  });
}

forbidden() and unauthorized() need experimental.authInterrupts. Without it, map those verdicts to whatever ending you already use.

Put the marking into the client so no call site can forget it:

javascript
export const cachedGet = <T>(path: string) => api.get<T>(path).catch(markForOutside);

Usage then becomes:

javascript
async function loadInvoice(accountId: string, id: string) {
  "use cache";
  cacheLife("minutes");
  return cachedGet<Invoice>(`/accounts/${accountId}/invoices/${id}`);
}

export const getInvoice = (accountId: string, id: string) =>
  decideOutside(loadInvoice(accountId, id));

Wrap every cached read this way, including ones that "can't fail" today. A wrapper you skipped fails exactly the way this pattern is meant to prevent: silently.

Two rules keep the pattern intact:

  • Call decideOutside only from uncached code, such as a page, a layout or an uncached component. Inside another "use cache" scope it raises the interrupt there, and that scope caches it: the first trap again. A cached component has no place for the wrapper, so read the data in an uncached parent and pass it down.
  • Don't swallow a cached read's error inside another cached scope. An outer "use cache" function with try { return await loadInvoice(accountId, id) } catch { return null } completes normally, so its entry stores null and the denial is cached after all.

A lint rule to keep it fixed

A directive is an ExpressionStatement with a directive property, at the top of a function body (BlockStatement) or of a file (Program). One ESLint selector covers both and bans interrupts anywhere inside:

javascript
"no-restricted-syntax": ["error", {
  selector:
    ":matches(Program, BlockStatement):has(> ExpressionStatement[directive=/^use cache/]) " +
    "CallExpression[callee.name=/^(forbidden|notFound|unauthorized|redirect|permanentRedirect|decideOutside)$/]",
  message: "Interrupts inside a cached scope are stored and replayed. Decide outside the cache.",
}]

It catches functions, arrow functions, nested blocks and a file-level "use cache". It bans the outcome rather than one specific code path, so it also catches shapes nobody has written yet, and listing decideOutside catches the wrapper being called from a cached scope. It can't see calls made through a helper function, an alias or a namespace (nav.notFound()), so those still need code review. It also flags redirect() in an inline "use server" action inside a cached component; the action runs outside the cache, so disable the rule on that line.

Simulate the boundary in tests

A unit test that passes the original error straight to decideOutside proves nothing, because in production that error never arrives intact. Simulate what the boundary does:

javascript
// Outside a Next server, forbidden() throws a different error unless this flag is set.
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS = "true";

// The class is gone; only the digest survives.
const acrossCacheBoundary = (error: unknown) =>
  Object.assign(new Error("Server Components render error"), {
    digest: (error as { digest?: string }).digest ?? "123456",
  });

const thrownBy = (fn: () => unknown) => {
  try { fn(); } catch (e) { return e; }
};

it("ends a cached 403 with forbidden()", async () => {
  const marked = thrownBy(() => markForOutside(new ApiError(403)));
  await expect(decideOutside(Promise.reject(acrossCacheBoundary(marked)))).rejects.toMatchObject({
    digest: "NEXT_HTTP_ERROR_FALLBACK;403",
  });
});

Assert the digest, not the message: the digest is what Next acts on.

Verify on a production build

Use a production build: next build && next start. Make the API refuse a read, render the page several times, and count the requests the API receives, from its access log or a counter in a mock:

  • Broken: the API is called once, and every later render is served from the cache.
  • Fixed: the API is called on every render, and the page still shows forbidden.tsx.

Don't count log lines printed by the cached function, and don't measure in next dev. In dev, a cache hit replays the function's console.log output, so a cached entry looks like a fresh run.

Two costs to expect. In production Next logs every failed cache fill, so each refused cached read prints a stack trace on the server. And refusals are no longer cached, so every request for a missing id reaches the API.

Summary

  1. Never call forbidden(), notFound(), unauthorized(), redirect() or permanentRedirect() inside a "use cache" function; they get cached.
  2. Only digest survives the cache boundary, so classify inside, send the verdict as a custom digest, and raise the interrupt outside.
  3. Put the marking into your data client and the unmarking into one wrapper, called only from uncached code.
  4. Don't swallow a cached read's error inside another cached scope.
  5. Lint the cached body, simulate the boundary in tests, and verify on a production build by counting API requests.

Tags Backend, JavaScript, Next.js, TypeScript

Share LinkedIn Facebook

Need more than an article?

A few sentences about what you are dealing with are enough.