Cache
NuxtHub cache uses Cloudflare Workers KV to cache your server route responses or functions using Nitro's cachedEventHandler
and cachedFunction
.
Getting Started
Enable the cache storage in your NuxtHub project by adding the cache
property to the hub
object in your nuxt.config.ts
file.
export default defineNuxtConfig({
hub: {
cache: true
}
})
Once you deploy your project, you can access to the cache storage in the NuxtHub admin. You can manage your cache entries in the Cache
section of your project page.
Event Handlers Caching
Using the cachedEventHandler
function, you can cache the response of a server route. This function will cache the response of the server route into the NuxtHub cache storage.
import type { H3Event } from 'h3'
export default cachedEventHandler((event) => {
return {
success: true,
date: new Date().toISOString()
}
}, {
maxAge: 60 * 60, // 1 hour
getKey: (event: H3Event) => event.node.req.url
})
The above example will cache the response of the /api/cached-route
route for 1 hour. The getKey
function is used to generate the key for the cache entry.
Functions Caching
Using the cachedFunction
function, You can cache a function. This is useful to cache the result of a function that is not an event handler but a part of it and reuse it in multiple handlers.
import type { H3Event } from 'h3'
export const getRepoStarCached = defineCachedFunction(async (event: H3Event, repo: string) => {
const data: any = await $fetch(`https://api.github.com/repos/${repo}`)
return data.stargazers_count
}, {
maxAge: 60 * 60, // 1 hour
name: 'ghStars',
getKey: (event: H3Event, repo: string) => repo
})
The above example will cache the result of the getRepoStarCached
function for 1 hour.
event
argument should always be the first argument of the cached function. Nitro leverages event.waitUntil
to keep the instance alive while the cache is being updated while the response is sent to the client.Read more about this in the Nitro docs.