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.
server/api/trpc/[trpc
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
})