Nitro · NITRO0023

Cache upstream responses with defineCachedFunction

Report module-scope Maps and reassigned variables that server code uses as hand-rolled TTL caches for upstream responses.
NITRO0023vite-doctor/nitrocachewarnSuggestion

Run this rule

pnpm vite-doctor . --framework nitro --extends auto,nitro/strict --rules nitro/cache/no-module-scope-response-cache

Why it matters

A module-scope cache with an expiry check lives in one server instance or worker isolate. Each instance warms its own copy, entries for keys nobody asks for again are never evicted, and Nitro's cache storage, invalidation, and stale-while-revalidate cannot see it. The key is whatever the author remembered to include: when a request-scoped client, such as one authorized as the current user, fills the cache, the next caller with the same key gets that user's response.

Wrap the upstream call in defineCachedFunction() with a maxAge and a getKey that covers every input that changes the response, including the user or tenant when the client is authorized per request. Values that cannot be serialized to cache storage, such as compiled validators, can stay in memory; suppress the diagnostic with a comment that says why.

Example

Cache upstream responses with defineCachedFunction

Before

const labelCache = new Map<string, { labels: string[]; expiry: number }>()

export async function getLabels(group: string) {
  const cached = labelCache.get(group)
  if (cached && cached.expiry > Date.now()) return cached.labels
  const labels = await $fetch<string[]>(`/labels/${group}`)
  labelCache.set(group, { labels, expiry: Date.now() + 60_000 })
  return labels
}

After

export const getLabels = defineCachedFunction(
  (group: string) => $fetch<string[]>(`/labels/${group}`),
  { name: 'labels', maxAge: 60, getKey: (group: string) => group },
)
Copyright © 2026