Setup
NuxtHub Cache automatically configures Nitro's cache storage. It allows you to cache API routes, server functions, and pages in your application.
Getting Started
Enable cache storage in your project by setting cache: true in the NuxtHub config.
export default defineNuxtConfig({
hub: {
cache: true
}
})
Cache vs KV
NuxtHub provides both Cache and KV storage. Understanding when to use each helps you make the right architectural decisions.
| Use Case | Recommendation |
|---|---|
| Response caching | Cache |
| API route caching | Cache |
| Computed data caching | Cache |
| User sessions | KV |
| Feature flags | KV |
| Rate limiting counters | KV |
| Persistent configuration | KV |
When to Use Cache
Cache is ideal for data that can be recomputed and benefits from automatic expiration:
- TTL-based expiration: Cached data automatically expires after a specified duration
- Response caching: Use
cachedEventHandlerorcachedFunctionfor API responses - Computed data: Cache expensive computations with automatic invalidation
- No manual cleanup: Expired entries are removed automatically
export default cachedEventHandler(async () => {
const posts = await fetchPosts()
return posts
}, { maxAge: 60 * 60 }) // Cache for 1 hour
When to Use KV
KV is designed for data that must persist until explicitly deleted:
- Persistent data: Information that should not expire automatically
- Session storage: User sessions and authentication tokens
- Application state: Feature flags and configuration values
- Counters: Rate limiting and analytics counters
import { kv } from 'hub:kv'
export default defineEventHandler(async (event) => {
const sessionId = getCookie(event, 'session')
const session = await kv.get(`sessions:${sessionId}`)
return session
})
Automatic Configuration
NuxtHub automatically configures the cache storage driver based on your hosting provider.
When deploying to Vercel, it automatically configures Vercel Runtime Cache.
No configuration is necessary to enable the Vercel Runtime Cache.
When deploying to Cloudflare, configure Cloudflare Workers KV for caching by providing the namespace ID. NuxtHub auto-generates the wrangler bindings at build time.
export default defineNuxtConfig({
hub: {
cache: {
driver: 'cloudflare-kv-binding',
namespaceId: '<cache-namespace-id>'
}
}
})
When deploying to other providers, it automatically configures the filesystem.
Custom Driver
You can use any unstorage driver by providing a configuration object to cache.
export default defineNuxtConfig({
hub: {
cache: {
driver: 'redis',
url: 'redis://localhost:6379'
}
}
})