Created
September 7, 2025 10:31
-
-
Save thanhnguyen2187/111b31ec1ead1dc5403f3d4724dd033f to your computer and use it in GitHub Desktop.
Hono in-memory cache middleware
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
| const CACHE_TIMEOUT_MS = 5 * 60 * 1000; | |
| const cacheData = new Map<string, unknown>(); | |
| const cacheMiddleware = createMiddleware(async (c, next) => { | |
| if (c.req.method !== "GET") { | |
| await next(); | |
| return; | |
| } | |
| const key = c.req.url; | |
| if (cacheData.has(key)) { | |
| // biome-ignore lint/style/noNonNullAssertion: checked null above | |
| return c.json(cacheData.get(key)!); | |
| } else { | |
| await next(); | |
| const data = await c.res.clone().json(); | |
| cacheData.set(key, data); | |
| setTimeout(() => { | |
| cacheData.delete(key); | |
| }, CACHE_TIMEOUT_MS); | |
| } | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I created this as an alternative to
hono/cacheas the official solution doesn't work with NodeJS.