Cache API
Nitro provides a powerful caching system built on top of the storage layer.
It stores the data in the cache
mountpoint.
- In development, it will use the FS driver writting to
.nitro/cache
or.nuxt/cache
if using Nuxt. - In production, it will use the memory driver by default.
To overwrite the production storage, set the cache
mountpoint using the storage
option:
import { defineNitroConfig } from "nitropack/config";
export default defineNitroConfig({
storage: {
cache: {
driver: 'redis',
/* redis connector options */
}
}
})
To overwrite the cache
mountpoint in development, use the devStorage
option to add the cache
mountpoint.
Usage
// Cache an API handler
export default cachedEventHandler((event) => {
// My event handler
}, options);
Examples
If you come from Nuxt, all the examples below should be placed inside the server/
directory.
Route Handler
Cache a route with stale-while-revalidate behavior for 10 second:
export default cachedEventHandler(async () => {
return `Response generated at ${new Date().toISOString()}`;
}, {
swr: true, maxAge: 10
});
The response will be cached for 10 second and a stale value will be sent to the client while the cache is being updated in the background.
The cached answer will be store in development inside .nitro/cache/handlers/_/*.json
.
Function
Cache for 1 hour the result of a function fetching the GitHub stars for a repository:
export const cachedGHStars = cachedFunction(async (repo: string) => {
const data: any = await $fetch(`https://api.github.com/repos/${repo}`)
return data.stargazers_count
}, {
maxAge: 60 * 60,
name: 'ghStars',
getKey: (repo: string) => repo
})
The stars will be cached in development inside .nitro/cache/functions/ghStars/<owner>/<repo>.json with value
being the number of stars.
{"expires":1677851092249,"value":43991,"mtime":1677847492540,"integrity":"ZUHcsxCWEH"}
Route Rules
This feature enables you to add caching routes based on a glob pattern directly in the main configuration file.
Cache all the blog routes for 1 hour with stale-while-revalidate
behavior:
import { defineNitroConfig } from "nitropack/config";
export default defineNitroConfig({
routeRules: {
"/blog/**": {
swr: 60 * 60,
// or
cache: {
maxAge: 60 * 60
}
},
},
});
If we want to use a custom storage mountpoint, we can use the base
option. Let's store our cache result for the blog routes in a Redis storage for production:
import { defineNitroConfig } from "nitropack/config";
export default defineNitroConfig({
storage: {
redis: {
driver: "redis",
url: "redis://localhost:6379",
},
},
routeRules: {
"/blog/**": {
swr: 60 * 60,
cache: {
base: "redis",
},
},
},
});
Options
The cachedEventHandler
and cachedFunction
functions accept the following options:
name
: Handler name.- Type:
String
- Default: Guessed from function name if not provided and fallback to
_
otherwise.
- Type:
group
: Part of cache name. Useful to organize cache storage.- Type:
String
- Default:
'nitro/handlers'
for handlers and'nitro/functions'
for functions.
- Type:
getKey
: A function that accepts the same arguments of the function and returns a cache key (String
).- Type:
Function
- Default: If not provided, a built-in hash function will be used.
- Type:
integrity
: A value that invalidates the cache when changed.- Type:
String
- Default: Computed from function code, used in development to invalidate the cache when the function code changes.
- Type:
maxAge
: Maximum age that cache is valid in seconds.- Type:
Number
- Default:
1
(second).
- Type:
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.- Type:
Number
- Default:
0
(disabled).
- Type:
swr
: Enablestale-while-revalidate
behavior.- Default:
true
- Default:
base
: Name of the storage mountpoint to use for caching.- Default:
cache
.
- Default:
shouldInvalidateCache
: A function that returns aBoolean
to invalidate the current cache and create a new one.- Type:
Function
- Type:
shouldBypassCache
: A function that returns a boolean to bypass the current cache without invalidating the existing entry.- Type:
Function
- Type: