Nitro provides a powerful caching system built on top of the storage layer.
const cachedFn = cachedEventHandler(fn, options);
name
: Handler name. It will be guessed from function name if not provided and fallback to _
otherwise.group
: Part of cache name. Useful to organize cache storage.getKey
: A function that accepts same arguments of normal function and should generate cache key. If not provided, a built-in hash function will be used.integrity
: A value that changing it, will invalidate all caches for function. By default will be computed from function code.maxAge
: Maximum age that cache is valid in seconds. Default is 1
second.staleMaxAge
: Maximum age that a stale cache is valid in seconds. If set to -1
a stale value will still be sent to the client, while updating the cache in the background.swr
: Enable Stale-While-Revalidate behavior. Enabled by default.base
: Name of the storage mointpoint to use for caching (/cache
by default)shouldInvalidateCache
: A function that returns a boolean to invalidate the current cache and create a new one.shouldBypassCache
: A function that returns a boolean to bypass the current cache without invalidating the existing entry.Example: Cache an API handler
// routes/cached.tsconst myFn = cachedEventHandler( async () => { new Promise((resolve) => setTimeout(resolve, 1000)); return `Response generated at ${new Date().toISOString()}`; }, { swr: true, });
Example: Cache a utility function
// utils/index.tsconst myFn = cachedFunction( async () => { new Promise((resolve) => setTimeout(resolve, 1000)); return Math.random(); }, { swr: true, });
Example: Enable Cache on a group of routes (🧪 Experimental!)
// nitro.config.tsimport { defineNitroConfig } from "nitropack";export default defineNitroConfig({ routeRules: { "/blog/**": { swr: true, }, },});
Example: Set cache storage mountpoint for a group of routes (🧪 Experimental!)
// nitro.config.tsimport { defineNitroConfig } from "nitropack";export default defineNitroConfig({ storage: { "my-custom-storage": { driver: "redis", url: "redis://localhost:6379", }, }, routeRules: { "/blog/**": { swr: true, cache: { base: "/my-custom-storage", }, }, },});