Skip to content

Instantly share code, notes, and snippets.

@thanhnguyen2187
Created September 7, 2025 10:31
Show Gist options
  • Save thanhnguyen2187/111b31ec1ead1dc5403f3d4724dd033f to your computer and use it in GitHub Desktop.
Save thanhnguyen2187/111b31ec1ead1dc5403f3d4724dd033f to your computer and use it in GitHub Desktop.
Hono in-memory cache middleware
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);
}
});
@thanhnguyen2187
Copy link
Author

I created this as an alternative to hono/cache as the official solution doesn't work with NodeJS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment