Setup

Configure caching in your Nuxt application, including setup for pages, API routes, and serverless functions to improve performance and reduce load.

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.

nuxt.config.ts
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 CaseRecommendation
Response cachingCache
API route cachingCache
Computed data cachingCache
User sessionsKV
Feature flagsKV
Rate limiting countersKV
Persistent configurationKV

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 cachedEventHandler or cachedFunction for API responses
  • Computed data: Cache expensive computations with automatic invalidation
  • No manual cleanup: Expired entries are removed automatically
server/api/posts.ts
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
server/api/session.ts
import { kv } from 'hub:kv'

export default defineEventHandler(async (event) => {
  const sessionId = getCookie(event, 'session')
  const session = await kv.get(`sessions:${sessionId}`)
  return session
})
As a general rule, use Cache for data that can be recomputed, and use KV for data that must persist.

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.

Custom Driver

You can use any unstorage driver by providing a configuration object to cache.

nuxt.config.ts
export default defineNuxtConfig({
  hub: {
    cache: {
      driver: 'redis',
      url: 'redis://localhost:6379'
    }
  }
})
You can find the driver list on unstorage documentation with their configuration.