Nuxt & Universal SSR (50 Qs)•Part 3: Advanced Internals, Performance & Production (Senior / Staff)
High-Performance Caching in Nitro: `defineCachedEventHandler` and `defineCachedFunction`.
senior LevelMost AskedCode ExampleFormsPerformanceSystem Design
In Simple Words: Nitro provides built-in driver-agnostic caching (memory, Redis, filesystem) to cache HTTP handlers and expensive functions with Time-To-Live (TTL) and stale-while-revalidate policies.
typescript
// server/api/metrics.ts: Cache API response for 60 seconds
export default defineCachedEventHandler(
async (event) => {
const stats = await fetchDatabaseMetrics();
return { timestamp: Date.now(), stats };
},
{
maxAge: 60, // Cache for 60 seconds
name: 'api_metrics',
getKey: (event) => 'global_stats'
}
);