Setup
Configure Nitro cache storage with hosting-aware defaults for local, Vercel, and Cloudflare deployments.
ViteHub Cache configures Nitro's built-in cache storage mount. Register the integration to get the default experience, and add a cache config object only when you need to override the driver.
Getting started
Install the package
Terminal
pnpm add https://pkg.pr.new/nuxt-hub/agent/@vitehub/cache@main
Terminal
pnpm add https://pkg.pr.new/nuxt-hub/agent/@vitehub/cache@main
Terminal
pnpm add https://pkg.pr.new/nuxt-hub/agent/@vitehub/cache@main
Choose an integration surface
nuxt.config.ts
export default defineNuxtConfig({
modules: ['@vitehub/cache/nuxt'],
})
nitro.config.ts
import { defineNitroConfig } from 'nitro/config'
export default defineNitroConfig({
modules: ['@vitehub/cache/nitro'],
cache: {
driver: 'cloudflare-kv-binding',
namespaceId: '<cache-namespace-id>',
},
})
Cache a route
server/api/posts.get.ts
export default cachedEventHandler(async () => {
return {
generatedAt: new Date().toISOString(),
}
}, {
maxAge: 60 * 60,
getKey: () => 'posts',
})
Automatic configuration
When Nitro builds the app, ViteHub resolves the cache driver in this order:
- explicit
driver - Cloudflare hosting
- Vercel hosting
- local filesystem fallback
If no hosted environment is detected, ViteHub falls back to the local filesystem driver and stores cache data in .data/cache.
Cache vs KV
Use Cache for data that can expire and be recomputed. Use KV for values that should persist until you delete them yourself.
| Use case | Recommendation |
|---|---|
| API response caching | Cache |
| Expensive computed data | Cache |
| Route rules cache | Cache |
| Sessions | KV |
| Feature flags | KV |
| Persistent configuration | KV |
Manual configuration
You can use any Unstorage driver by configuring cache with a driver and its options.
nitro.config.ts
import { defineNitroConfig } from 'nitro/config'
export default defineNitroConfig({
modules: ['@vitehub/cache/nitro'],
cache: {
driver: 'redis',
url: 'redis://localhost:6379',
},
})
Public API
| Function | Use it for |
|---|---|
cachedEventHandler(handler, options) | Cache a route response in the cache storage mount. |
defineCachedFunction(fn, options) | Cache a reusable server function shared across routes. |