mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 12:14:40 +01:00
1.4 KiB
1.4 KiB
title
| title |
|---|
| Response Caching |
Response Caching
Your server responses must satisfy some criteria in order for them to be cached (i.e. by Vercel's Edge Network). Please refer to this section of the tRPC.io documentation for more information.
The createNuxtApiHandler function conveniently allows you to specify a responseMeta function.
import { createNuxtApiHandler } from 'trpc-nuxt'
import { appRouter } from '~/server/trpc/routers'
export default createNuxtApiHandler({
router: appRouter,
/**
* @link https://trpc.io/docs/caching#api-response-caching
*/
responseMeta(opts) {
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
return {
headers: {
'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
},
})
You can also take advantage of Nitro's Cache API if doing server-side calls:
import { appRouter } from '@/server/trpc/routers'
const caller = appRouter.createCaller({})
export default cachedEventHandler(async (event) => {
const { name } = getQuery(event)
const greeting = await caller.greeting({ name })
return {
greeting
}
}, {
swr: true, maxAge: 10
})