Cache Middleware
The Cache middleware uses the Web Standards' Cache API.
The Cache middleware currently supports Cloudflare Workers projects using custom domains and Deno projects using Deno 1.26+. Also available with Deno Deploy.
Cloudflare Workers respects the Cache-Control
header and return cached responses. For details, refer to Cache on Cloudflare Docs. Deno does not respect headers, so if you need to update the cache, you will need to implement your own mechanism.
See Usage below for instructions on each platform.
Import
import { Hono } from 'hono'
import { cache } from 'hono/cache'
Usage
app.get(
'*',
cache({
cacheName: 'my-app',
cacheControl: 'max-age=3600',
})
)
// Must use `wait: true` for the Deno runtime
app.get(
'*',
cache({
cacheName: 'my-app',
cacheControl: 'max-age=3600',
wait: true,
})
)
Options
required cacheName: string
| (c: Context) => string
| Promise<string>
The name of the cache. Can be used to store multiple caches with different identifiers.
optional wait: boolean
A boolean indicating if Hono should wait for the Promise of the cache.put
function to resolve before continuing with the request. Required to be true for the Deno environment. The default is false
.
optional cacheControl: string
A string of directives for the Cache-Control
header. See the MDN docs for more information. When this option is not provided, no Cache-Control
header is added to requests.
optional vary: string
| string[]
Sets the Vary
header in the response. If the original response header already contains a Vary
header, the values are merged, removing any duplicates. Setting this to *
will result in an error. For more details on the Vary header and its implications for caching strategies, refer to the MDN docs.
optional keyGenerator: (c: Context) => string | Promise<string>
Generates keys for every request in the cacheName
store. This can be used to cache data based on request parameters or context parameters. The default is c.req.url
.