Skip to content

Commit

Permalink
docs: update the cache page (#2087)
Browse files Browse the repository at this point in the history
  • Loading branch information
Barbapapazes authored Jan 17, 2024
1 parent 98cae74 commit aff7b5c
Showing 1 changed file with 49 additions and 38 deletions.
87 changes: 49 additions & 38 deletions docs/content/1.guide/5.cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
icon: ri:speed-line
---

# Cache API
# Cache

Nitro provides a powerful caching system built on top of the [storage layer](/guide/storage).

It stores the data in the `cache` mountpoint.
- In development, it will use the [FS driver](https://unstorage.unjs.io/drivers/fs) writting to `.nitro/cache` or `.nuxt/cache` if using [Nuxt](https://nuxt.com).
It stores the data in the `cache` mount point.

- In development, it will use the [filesystem driver](https://unstorage.unjs.io/drivers/fs) writing to `.nitro/cache` or `.nuxt/cache` if using [Nuxt](https://nuxt.com).
- In production, it will use the [memory driver](https://unstorage.unjs.io/drivers/memory) by default.

To overwrite the production storage, set the `cache` mountpoint using the `storage` option:
To overwrite the production storage, set the `cache` mount point using the `storage` option:

::code-group
```ts [nitro.config.ts]
Expand All @@ -37,55 +38,68 @@ export default defineNuxtConfig({
```
::

To overwrite the `cache` mountpoint in development, use the `devStorage` option to add the `cache` mountpoint.

## Usage
In development, you can also overwrite the cache mount point using the `devStorage` option:

::code-group
```ts [Router Handler]
// Cache an API handler
export default cachedEventHandler((event) => {
// My event handler
}, options);
```ts [nitro.config.ts]
export default defineNitroConfig({
devStorage: {
cache: {
driver: 'redis',
/* redis connector options */
}
}
})
```
```ts [Function]
const myFn = cachedFunction(() => {
// My function
}, options);
```ts [nuxt.config.ts]
export default defineNuxtConfig({
nitro: {
devStorage: {
cache: {
driver: 'redis',
/* redis connector options */
}
}
}
})
```
::

## Examples
## Usage

There is several way to use the cache layer.

If you come from [Nuxt](https://nuxt.com), all the examples below should be placed inside the `server/` directory.
You can wrap a function or an event handler or use the route rules. The cached data will be stored, in development, in `.nitro/cache`. You can create namespaces by using the `group` option. By default, it's `nitro/handlers` for handlers and `nitro/functions` for functions.

### Route Handler
### Cached Event Handler

Cache a route with [stale-while-revalidate](https://www.rfc-editor.org/rfc/rfc5861#section-3) behavior for 10 second:
To cache an event handler, you've just to use the `defineCachedEventHandler` function. It works like the `defineEventHandler` function but with an additional `options` parameter.

```ts [routes/cached.ts]
export default cachedEventHandler(async () => {
return `Response generated at ${new Date().toISOString()}`;
::code-group
```ts [Router Handler]
// Cache an API handler
export default defineCachedEventHandler((event) => {
// My event handler
}, {
maxAge: 10
maxAge: 60 * 60 // 1 hour
});
```

The response will be cached for 10 seconds and a stale value will be sent to the client while the cache is being updated in the background. If you want to immediately return the updated response set `swr: false`.
With this example, the response will be cached for 1 hour and a stale value will be sent to the client while the cache is being updated in the background. If you want to immediately return the updated response set `swr: false`.

The cached answer will be store in development inside `.nitro/cache/handlers/_/*.json`.
It's important to note that by default, all incoming request headers are dropped when handling cached responses. If you define the `varies` option, only the specified headers will be considered when caching and serving the responses.

::alert{type=primary}
By default, all incoming request headers are dropped when handling cached responses. If you define the `varies` option, only the specified headers will be considered when caching and serving the responses.
::
See the [options](#options) section for more details about the available options.

### Function

Cache for 1 hour the result of a function fetching the GitHub stars for a repository:
You can also cache a function using the `cachedFunction` function. This is useful to cache the result of a function that is not an event handler but a part of it and reuse it in multiple handlers.

For example, you could want to cache for 1 hour the result of an API call:

::code-group
```ts [utils/github.ts]
export const cachedGHStars = cachedFunction(async (repo: string) => {
export const cachedGHStars = definedCachedFunction(async (repo: string) => {
const data: any = await $fetch(`https://api.github.com/repos/${repo}`)

return data.stargazers_count
Expand All @@ -111,11 +125,9 @@ The stars will be cached in development inside **.nitro/cache/functions/ghStars/
{"expires":1677851092249,"value":43991,"mtime":1677847492540,"integrity":"ZUHcsxCWEH"}
```

### Route Rules

## Route Rules

This feature enables you to add caching routes based on a glob pattern directly in the main configuration file.

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.

::alert{type="primary"}
This feature is still experimental and may evolve in the future.
Expand Down Expand Up @@ -152,7 +164,7 @@ export default defineNuxtConfig({
```
::

If we want to use a custom storage mountpoint, we can use the `base` option. Let's store our cache result for the blog routes in a Redis storage for production:
If we want to use a custom storage mount point, we can use the `base` option. Let's store our cache result for the blog routes in a Redis storage for production:

::code-group
```ts [nitro.config.ts]
Expand Down Expand Up @@ -195,7 +207,6 @@ export default defineNuxtConfig({
```
::


## Options

The `cachedEventHandler` and `cachedFunction` functions accept the following options:
Expand All @@ -207,7 +218,7 @@ The `cachedEventHandler` and `cachedFunction` functions accept the following opt
- Default: `'nitro/handlers'` for handlers and `'nitro/functions'` for functions.
- `getKey`: A function that accepts the same arguments of the function and returns a cache key (`String`).
- Type: `Function`
- Default: If not provided, a built-in hash function will be used.
- Default: If not provided, a built-in hash function will be used that will generate a key based on the function arguments.
- `integrity`: A value that invalidates the cache when changed.
- Type: `String`
- Default: Computed from **function code**, used in development to invalidate the cache when the function code changes.
Expand Down

0 comments on commit aff7b5c

Please sign in to comment.