Skip to content

Commit

Permalink
docs: add response caching page
Browse files Browse the repository at this point in the history
  • Loading branch information
wobsoriano committed Aug 23, 2023
1 parent 8e893a2 commit 9808375
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions docs/content/1.get-started/5.tips/6.response-caching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
title: Response Caching
---

Your server responses must [satisfy some criteria](https://vercel.com/docs/concepts/functions/serverless-functions/edge-caching) in order for them to be cached (i.e. by Vercel's Edge Network). Please refer to [this section of the tRPC.io documentation](https://trpc.io/docs/caching) for more information.

The createNuxtApiHandler` function conveniently allows you to specify a `responseMeta` function.

```ts [server/api/trpc/[trpc].ts]
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](https://nitro.unjs.io/guide/cache#cache-api) if doing server-side calls:

```ts
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
})
```

1 comment on commit 9808375

@vercel
Copy link

@vercel vercel bot commented on 9808375 Aug 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

trpc-nuxt – ./

trpc-nuxt.vercel.app
trpc-nuxt-git-main-wobsoriano.vercel.app
trpc-nuxt-wobsoriano.vercel.app

Please sign in to comment.