Skip to content

shouldBypassCache option in defineCachedHandler is silently ignored #4168

@psd-coder

Description

@psd-coder

Environment

nitro: 3.0.260311-beta
ocache: 0.1.4
Node.js: v22.x

Reproduction

https://stackblitz.com/github/psd-coder/nitro-isr-bypass-cache-bug

Steps:

  1. Open the StackBlitz, wait for nitro dev to start
  2. Send GET /api to populate cache
  3. Send GET /api with header x-bypass-cache: true
  4. Observe: cached response returned, "shouldBypassCache called" never appears in terminal
  5. Compare with shouldInvalidateCache: it is called on every call

Describe the bug

The shouldBypassCache callback passed to defineCachedHandler is never invoked. The root cause is in ocache@0.1.4: when defineCachedHandler calls cachedFunction, the hardcoded shouldBypassCache is placed after the ...opts spread, always overriding any user-provided callback:

const _opts: CacheOptions<ResponseCacheEntry> = {
  ...opts,                             // user's shouldBypassCache is here
  shouldBypassCache: (event) => {      // ...then always overwritten
    return event.req.method !== "GET" && event.req.method !== "HEAD";
  },
};

shouldInvalidateCache is not affected since it passes through via ...opts.

Suggested fix (in ocache):

shouldBypassCache: opts.shouldBypassCache ?? ((event) => {
  return event.req.method !== "GET" && event.req.method !== "HEAD";
}),

Additional context

The TypeScript types correctly expose shouldBypassCache in CachedEventHandlerOptions, so the API surface suggests this option is supported. The issue is purely in the runtime implementation in ocache.

If this should be tracked in https://github.com/unjs/ocache instead, happy to move it there.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions