Skip to content

Commit

Permalink
docs(cache): add a note for serverless environment
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Mar 21, 2024
1 parent d12aae1 commit dc83a2e
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion docs/1.guide/6.cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,38 @@ The stars will be cached in development inside **.nitro/cache/functions/ghStars/
You can also use the `cachedFunction` method as alias of `defineCachedFunction`.
::

### Serverless environment

In a serverless environment, the instance is destroyed after each request. Nitro uses `event.waitUntil` to keep the instance alive while the cache is being updated while the response is sent to the client.

To make sure your cached functions are working as expected in a serverless environment, you should always give the `event` as first argument to the function.

::code-group
```ts [utils/github.ts]
import type { H3Event } from 'h3'

export const cachedGHStars = defineCachedFunction(async (event: H3Event, repo: string) => {
const data: any = await $fetch(`https://api.github.com/repos/${repo}`)

return data.stargazers_count
}, {
maxAge: 60 * 60,
name: 'ghStars',
getKey: (event: H3Event, repo: string) => repo
})
```
```ts [api/stars/[...repo\\].ts]
export default defineEventHandler(async (event) => {
const repo = event.context.params.repo
const stars = await cachedGHStars(event, repo).catch(() => 0)

return { repo, stars }
})
```
::

This way, the function will be able to keep the instance alive while the cache is being updated without slowing down the response to the client.

## Caching route rules

This feature enables you to add caching routes based on a glob pattern directly in the main configuration file. This is especially useful to have a global cache strategy for a part of your application.
Expand Down Expand Up @@ -191,7 +223,6 @@ export default defineNuxtConfig({

The `cachedEventHandler` and `cachedFunction` functions accept the following options:


::field-group
::field{name="base" type="string"}
Name of the storage mountpoint to use for caching, default is `'cache'`.
Expand Down

0 comments on commit dc83a2e

Please sign in to comment.