-
Notifications
You must be signed in to change notification settings - Fork 355
feat(universal-cache): add universal cache middleware package #1764
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lord007tn
wants to merge
12
commits into
honojs:main
Choose a base branch
from
lord007tn:feat/universal-cache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6d0ef1e
feat(universal-cache): address review feedback
lord007tn 29d3e05
test(universal-cache): validate cloudflare workers runtime
lord007tn 544fd62
Merge remote-tracking branch 'upstream/main' into feat/universal-cache
lord007tn 2be0e50
fix(universal-cache): harden cache behavior and adopt pnpm
lord007tn b3a7f87
fix(universal-cache): complete release validation
lord007tn 5b19385
ci: apply automated fixes
autofix-ci[bot] a9edb13
fix(universal-cache): address review feedback
lord007tn a57cd3d
Merge remote-tracking branch 'origin/feat/universal-cache' into feat/…
lord007tn 734d599
Merge remote-tracking branch 'upstream/main' into feat/universal-cache
lord007tn 7f60b4d
fix(universal-cache): harden cache behavior
lord007tn ce27706
fix(universal-cache): harden concurrent cache operations
lord007tn a4ebbfb
fix(universal-cache): align bundled dependencies
lord007tn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| --- | ||
| '@hono/universal-cache': minor | ||
| --- | ||
|
|
||
| Add `@hono/universal-cache`, a universal cache toolkit for Hono with: | ||
|
|
||
| - `cacheMiddleware()` for response caching | ||
| - `cacheDefaults()` for scoped defaults | ||
| - `cacheFunction()` for caching async function results | ||
| - stale-while-revalidate support | ||
| - storage/default accessors (`set/getCacheStorage`, `set/getCacheDefaults`) | ||
| - custom keying, serialization, validation, and invalidation hooks |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| # @hono/universal-cache |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| # @hono/universal-cache | ||
|
|
||
| [](https://codecov.io/github/honojs/middleware) | ||
|
|
||
| Storage-agnostic response and function caching for Hono. | ||
|
|
||
| ## Features | ||
|
|
||
| - Response caching with `cacheMiddleware()` | ||
| - Function result caching with `cacheFunction()` | ||
| - Request-scoped defaults with `cacheDefaults()` | ||
| - Stale-while-revalidate and in-flight request deduplication | ||
| - Custom storage, keys, integrity values, serialization, and validation | ||
| - Explicit bypass, invalidation, and manual revalidation hooks | ||
| - Node.js, Bun, Deno, and Cloudflare Workers-compatible Web APIs | ||
|
|
||
| ## Installation | ||
|
|
||
| ```sh | ||
| pnpm add @hono/universal-cache | ||
| ``` | ||
|
|
||
| ## Response caching | ||
|
|
||
| ```ts | ||
| import { Hono } from 'hono' | ||
| import { cacheMiddleware } from '@hono/universal-cache' | ||
|
|
||
| const app = new Hono() | ||
|
|
||
| app.get('/items', cacheMiddleware(60), (c) => c.json({ ok: true })) | ||
| ``` | ||
|
|
||
| Passing a number is shorthand for `{ maxAge: number }`. `GET` and `HEAD` are cached by default. | ||
|
|
||
| ## Storage and defaults | ||
|
|
||
| The default storage is an in-memory `unstorage` instance scoped to the current process or isolate. Configure a persistent or distributed driver for multi-instance deployments. | ||
|
|
||
| ```ts | ||
| import { Hono } from 'hono' | ||
| import { cacheDefaults, cacheMiddleware } from '@hono/universal-cache' | ||
| import { createStorage } from 'unstorage' | ||
| import redisDriver from 'unstorage/drivers/redis' | ||
|
|
||
| const app = new Hono() | ||
|
|
||
| app.use( | ||
| '/api/*', | ||
| cacheDefaults({ | ||
| storage: createStorage({ driver: redisDriver({ url: process.env.REDIS_URL }) }), | ||
| maxAge: 60, | ||
| staleMaxAge: 30, | ||
| swr: true, | ||
| }) | ||
| ) | ||
|
|
||
| app.get('/api/items', cacheMiddleware(), (c) => c.json({ ok: true })) | ||
| ``` | ||
|
|
||
| `cacheDefaults()` applies defaults to downstream cache middleware for the current request. Use `setCacheDefaults()` and `setCacheStorage()` for process-wide defaults, including `cacheFunction()`. | ||
|
|
||
| Route-local options override request-scoped and process-wide defaults: | ||
|
|
||
| ```ts | ||
| app.get( | ||
| '/api/items', | ||
| cacheMiddleware({ | ||
| config: { maxAge: 120 }, | ||
| staleMaxAge: 60, | ||
| }), | ||
| handler | ||
| ) | ||
| ``` | ||
|
|
||
| ## Cache keys | ||
|
|
||
| Default response keys include: | ||
|
|
||
| - HTTP method and origin | ||
| - URL path and query | ||
| - request body for explicitly enabled non-`GET`/`HEAD` methods | ||
| - configured `varies` headers | ||
| - `authorization` and `cookie` headers when present | ||
|
|
||
| Use `getKey` when the cache identity depends on application-specific context: | ||
|
|
||
| ```ts | ||
| cacheMiddleware({ | ||
| getKey: (c) => `${c.req.param('tenant')}:${c.req.query('page') ?? '1'}`, | ||
| maxAge: 60, | ||
| }) | ||
| ``` | ||
|
|
||
| `getKey` replaces the complete default key. Include every relevant tenant, authorization, cookie, method, body, and variation value when providing one. | ||
|
|
||
| When a response uses `Vary`, list the corresponding request headers in `varies`. Responses with `Vary: *` are never cached. | ||
|
|
||
| ## Manual revalidation | ||
|
|
||
| Manual revalidation is disabled by default. Enable it with a private header name and gate it with `shouldRevalidate`: | ||
|
|
||
| ```ts | ||
| cacheMiddleware({ | ||
| revalidateHeader: 'x-my-cache-revalidate', | ||
| shouldRevalidate: (c) => c.req.header('authorization') === `Bearer ${process.env.CACHE_TOKEN}`, | ||
| }) | ||
| ``` | ||
|
|
||
| A request with `x-my-cache-revalidate: 1` refreshes the entry only when `shouldRevalidate` allows it. Do not expose an ungated revalidation header on public endpoints. | ||
|
|
||
| ## Bypass and invalidation | ||
|
|
||
| ```ts | ||
| cacheMiddleware({ | ||
| shouldBypassCache: (c) => c.req.header('cache-control') === 'no-cache', | ||
| shouldInvalidateCache: (c) => c.req.query('refresh') === '1', | ||
| keepPreviousOn5xx: true, | ||
| }) | ||
| ``` | ||
|
|
||
| - `shouldBypassCache` skips both cache reads and writes. | ||
| - `shouldInvalidateCache` skips the current entry and refreshes it. | ||
| - `keepPreviousOn5xx` preserves the previous entry when an invalidation refresh returns a 5xx response. It preserves function entries when the wrapped function throws. | ||
|
|
||
| ## Stale-while-revalidate | ||
|
|
||
| ```ts | ||
| cacheMiddleware({ | ||
| maxAge: 60, | ||
| staleMaxAge: 300, | ||
| swr: true, | ||
| }) | ||
| ``` | ||
|
|
||
| After `maxAge`, stale entries remain usable for `staleMaxAge` seconds. Use `staleMaxAge: -1` for unlimited stale storage. | ||
|
|
||
| Standard runtimes serve the stale response and perform a deduplicated background self-fetch. Cloudflare Workers refresh stale middleware entries synchronously because background self-fetch behaves differently under `workerd`. Function caches refresh stale values in the background on every runtime. | ||
|
|
||
| ## Function caching | ||
|
|
||
| ```ts | ||
| import { cacheFunction } from '@hono/universal-cache' | ||
|
|
||
| const getStats = cacheFunction(async (id: string) => ({ id, ts: Date.now() }), { | ||
| maxAge: 60, | ||
| getKey: (id) => id, | ||
| }) | ||
| ``` | ||
|
|
||
| Without `getKey`, arguments are deterministically serialized and hashed. Default argument serialization supports JSON-compatible values and `Date`. Provide `getKey` for values such as `Map`, `Set`, `BigInt`, cyclic structures, or class instances. | ||
|
|
||
| Concurrent calls for the same storage, key, and integrity value share one in-flight operation. Different storage instances remain isolated. | ||
|
|
||
| ## Custom serialization and validation | ||
|
|
||
| `serialize`, `deserialize`, and `validate` can adapt stored entries or reject obsolete data. Custom response serializers must return the `CachedResponseEntry` shape, including `encoding: 'base64'`. Use `integrity` to invalidate entries when their schema or behavior changes. | ||
|
|
||
| ## API | ||
|
|
||
| - `cacheMiddleware(options | maxAge)` | ||
| - `cacheDefaults(options)` | ||
| - `cacheFunction(fn, options | maxAge)` | ||
| - `createCacheStorage()` | ||
| - `setCacheStorage(storage)` / `getCacheStorage()` | ||
| - `setCacheDefaults(options)` / `getCacheDefaults()` | ||
| - `stableStringify(value)` | ||
|
|
||
| Exported types include `CacheBaseOptions`, `CacheConfigOptions`, `CacheDefaults`, `CacheMiddlewareOptions`, `CacheFunctionOptions`, `CachedResponseEntry`, and `CachedFunctionEntry`. | ||
|
|
||
| ## Response safety | ||
|
|
||
| The middleware does not cache: | ||
|
|
||
| - responses outside the 2xx range or HTTP 206 partial responses | ||
| - responses containing `set-cookie` | ||
| - responses marked `private`, `no-store`, or `no-cache` | ||
| - responses containing `Vary: *` | ||
| - malformed persisted entries | ||
|
|
||
| Cached responses exclude `set-cookie`, `content-length`, and other hop-by-hop headers. | ||
|
|
||
| ## Author | ||
|
|
||
| Raed B. <https://github.com/lord007tn> | ||
|
|
||
| ## License | ||
|
|
||
| MIT |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| "name": "@hono/universal-cache", | ||
| "version": "0.0.0", | ||
| "license": "MIT", | ||
| "exports": { | ||
| ".": "./src/index.ts" | ||
| }, | ||
| "imports": { | ||
| "hono": "jsr:@hono/hono@^4.8.3" | ||
| }, | ||
| "publish": { | ||
| "include": ["deno.json", "README.md", "src/**/*.ts"], | ||
| "exclude": ["src/**/*.test.ts"] | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| { | ||
| "name": "@hono/universal-cache", | ||
| "version": "0.0.0", | ||
| "description": "Universal cache middleware and helpers for Hono", | ||
| "sideEffects": false, | ||
| "type": "module", | ||
| "main": "./dist/index.cjs", | ||
| "module": "./dist/index.mjs", | ||
| "types": "./dist/index.d.cts", | ||
| "files": [ | ||
| "dist" | ||
| ], | ||
| "scripts": { | ||
| "build": "pnpm -w run build:pkg", | ||
| "lint": "eslint", | ||
| "typecheck": "tsc -b tsconfig.json", | ||
| "test": "vitest", | ||
| "test:workerd": "vitest --config vitest.workerd.config.ts", | ||
| "version:jsr": "pnpm -w run version:set $npm_package_version" | ||
| }, | ||
| "exports": { | ||
| ".": "./src/index.ts", | ||
| "./package.json": "./package.json" | ||
| }, | ||
| "license": "MIT", | ||
| "publishConfig": { | ||
| "registry": "https://registry.npmjs.org", | ||
| "access": "public", | ||
| "provenance": true, | ||
| "exports": { | ||
| ".": { | ||
| "import": "./dist/index.mjs", | ||
| "require": "./dist/index.cjs" | ||
| }, | ||
| "./package.json": "./package.json" | ||
| } | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/honojs/middleware.git", | ||
| "directory": "packages/universal-cache" | ||
| }, | ||
| "homepage": "https://github.com/honojs/middleware", | ||
| "peerDependencies": { | ||
| "hono": ">=4.0.0" | ||
| }, | ||
| "dependencies": { | ||
| "ohash": "^2.0.11", | ||
| "unstorage": "^1.17.0" | ||
| }, | ||
| "devDependencies": { | ||
| "@cloudflare/vitest-pool-workers": "^0.16.10", | ||
| "@cloudflare/workers-types": "^4.20250612.0", | ||
| "hono": "^4.11.5", | ||
| "tsdown": "^0.22.3", | ||
| "typescript": "^6.0.3", | ||
| "vitest": "^4.1.7" | ||
| }, | ||
| "engines": { | ||
| "node": ">=16.0.0" | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.