Skip to main content

Import

Usage

Options

The cache middleware accepts an options object:
string | ((c: Context) => string | Promise<string>)
required
The name of the cache. Can be used to store multiple caches with different identifiers. Can be a static string or a function that returns the cache name dynamically.
boolean
default:false
Whether 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.
string
A string of directives for the Cache-Control header. Will be appended to existing directives.
string | string[]
Sets the Vary header in the response. If the original response already contains a Vary header, the values are merged, removing duplicates.
(c: Context) => string | Promise<string>
Generates keys for every request in the cacheName store. Useful for caching data based on request parameters or context parameters. Defaults to using the request URL.
number[]
An array of status codes that can be cached. Only responses with these status codes will be stored in the cache.

Signature

Examples

Basic caching

Custom cache key based on query params

Dynamic cache name

Vary header for conditional caching

Cache multiple status codes

For Deno (with wait)

Behavior

  • Returns cached response immediately if available
  • Only caches responses with status codes in cacheableStatusCodes (default: 200)
  • Skips caching if response has:
    • Vary: * header
    • Cache-Control with private, no-store, or no-cache
    • Set-Cookie header
  • Appends specified Cache-Control directives without duplicating existing ones
  • Merges Vary headers and removes duplicates
  • Uses Cache API (caches.open()) which must be available in the runtime
  • If Cache API is not available, middleware becomes a no-op