Skip to content

defineCachedHandler has no way to override/extend response validation (e.g. exclude 3xx redirects from caching) #48

Closed

Description

@pi0x

Follow-up from #47 (Validate / Transform category), tracking nitrojs/nitro#3491 ("Can't override VALIDATE method on defineCachedEventHandler").

Problem

defineCachedFunction's validate option is fully user-overridable, async-capable, and receives call args (src/cache.ts:46, src/types.ts:91). But defineCachedHandler builds its own internal, hardcoded validate in src/http.ts:124-145:

validate: (entry) => {
  if (!entry.value) return false;
  if (_forbidsSharedCaching(entry.value.headers?.["cache-control"])) return false;
  if (entry.value.status >= 400) return false;
  if (entry.value.body === undefined) return false;
  if (entry.value.headers.etag === "undefined" || entry.value.headers["last-modified"] === "undefined") return false;
  return true;
},

CachedEventHandlerOptions<E> (src/types.ts:163-166) explicitly strips validate (and transform) from the public type via Omit<CacheOptions<...>, "transform" | "validate">, so there is no supported way to extend this logic. Notably status >= 400 never excludes 3xx responses, so a handler returning 301/302 with an SWR-style cache-control (e.g. s-maxage=3600, stale-while-revalidate=3600) gets cached and replayed indefinitely — the exact loop reported upstream.

Proposal

Give defineCachedHandler callers a way to add extra rejection conditions on top of the built-in checks, without letting them accidentally disable the built-ins that protect storage integrity (no-store/private honoring, malformed-entry guards). Options to consider:

  • An additive hook, e.g. shouldCache?: (entry: ResponseCacheEntry, event: E) => boolean | Promise<boolean>, ANDed with the existing internal checks (so users can reject e.g. 3xx, specific headers, etc. without needing to reimplement the base safety checks).
  • Or relax the Omit in CachedEventHandlerOptions to allow a user validate that runs in addition to (not instead of) the internal one.

Either way this should stay standalone (no h3/srvx/unstorage dependency) and compose with the existing internal validate rather than replace it, since the internal checks are load-bearing for correctness (e.g. _forbidsSharedCaching).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions