@web-widget/shared-cache
v2.1.0
Published
Standards-compliant HTTP cache implementation for server-side JavaScript with RFC 7234 compliance and cross-runtime support
Downloads
806
Maintainers
Readme
SharedCache
A standards-compliant HTTP cache implementation for server-side applications.
SharedCache is an HTTP caching library that follows Web Standards and HTTP specifications. It implements a cache interface similar to the Web Cache API but optimized for server-side shared caching scenarios.
📋 Table of Contents
- ✨ Key Features
- 🤔 Why SharedCache?
- ⚡ Quick Decision Guide
- 📦 Installation
- 🚀 Quick Start
- 📋 Standards Compliance
- ☁️ Cloudflare Comparison
- 📖 Documentation
- 🤝 Who's Using SharedCache
- 🙏 Acknowledgments
- 📄 License
✨ Key Features
- 📋 RFC Compliance: Supports RFC 5861 directives like
stale-if-errorandstale-while-revalidate - 🎯 Smart Caching: Handles complex HTTP scenarios including
Varyheaders, proxy revalidation, and authenticated responses - 🔧 Flexible Storage: Pluggable storage backend supporting memory, Redis, or any custom key-value store
- 🚀 Enhanced Fetch: Extends the standard
fetchAPI with caching capabilities while maintaining full compatibility - 🔌 Middleware Origin:
createCacheHandlerfor in-process handlers (e.g. middlewarenext()) - 🎛️ Custom Cache Keys: Cache key customization supporting device types, cookies, headers, and URL components
- ⚡ Shared Cache Optimization: Prioritizes
s-maxageovermax-agefor shared cache performance - 🌍 Universal Runtime: Compatible with WinterCG environments including Node.js, Deno, Bun, and Edge Runtime
🤔 Why SharedCache?
While the Web fetch API has become ubiquitous in server-side JavaScript, existing browser Cache APIs are designed for single-user scenarios. Server-side applications need shared caches that serve multiple users efficiently.
SharedCache provides:
- Server-Optimized Caching: Designed for multi-user server environments
- Standards Compliance: Follows HTTP specifications and server-specific patterns
- Production Ready: Battle-tested patterns from CDN and proxy implementations
⚡ Quick Decision Guide
✅ Use SharedCache When:
- Node.js environments - Native
cachesAPI not available - API response caching - Need to reduce backend load and improve response times
- Cross-runtime portability - Want consistent caching across Node.js, Deno, Bun
- Custom storage backends - Need Redis, database, or distributed caching solutions
- Meta-framework development - Building applications that deploy to multiple environments
❌ Don't Use SharedCache When:
- Edge runtimes with native caches - Cloudflare Workers, Vercel Edge already provide
cachesAPI - Browser applications - Use the native Web Cache API instead (unless you need HTTP cache control directives support)
- Simple in-memory caching - Consider lighter alternatives like
lru-cachedirectly - Single-request caching - Basic memoization might be sufficient
📦 Installation
npm install @web-widget/shared-cache# Using yarn
yarn add @web-widget/shared-cache
# Using pnpm
pnpm add @web-widget/shared-cache🚀 Quick Start
import {
CacheStorage,
createFetch,
type KVStorage,
} from '@web-widget/shared-cache';
import { LRUCache } from 'lru-cache';
const createLRUCache = (): KVStorage => {
const store = new LRUCache<string, any>({ max: 1024 });
return {
async get(cacheKey: string) {
return store.get(cacheKey);
},
async set(cacheKey: string, value: any, ttl?: number) {
store.set(cacheKey, value, { ttl });
},
async delete(cacheKey: string) {
return store.delete(cacheKey);
},
};
};
const caches = new CacheStorage(createLRUCache());
async function example() {
const cache = await caches.open('api-cache-v1');
const fetch = createFetch(cache, {
defaults: {
cacheControlOverride: 's-maxage=300',
ignoreRequestCacheControl: true,
},
});
const response1 = await fetch(
'https://httpbin.org/response-headers?cache-control=max-age%3D604800'
); // First request: network
const response2 = await fetch(
'https://httpbin.org/response-headers?cache-control=max-age%3D604800'
); // Second request: cache
console.log(response2.headers.get('x-cache-status')); // "HIT"
}
example();Core APIs
| Export | Purpose |
| ------------------------ | ------------------------------------ |
| createFetch | Outbound HTTP fetch with caching |
| createCacheHandler | In-process origin (middleware / SSR) |
| CacheStorage / Cache | Cache storage and operations |
| KVStorage | Pluggable storage backend interface |
Every response includes an x-cache-status header (HIT, MISS, UPDATING, STALE, …) for debugging. See the configuration guide for the full status table.
📋 Standards Compliance
SharedCache is built for production HTTP caching with full adherence to web standards:
| Standard | Status | Coverage |
| ----------------------------------------------------------------------- | ------------------ | --------------------------------------- |
| RFC 7234 (HTTP Caching) | ✅ Fully Compliant | 100% |
| RFC 5861 (stale-* extensions) | ✅ Fully Compliant | 100% |
| Web Cache API | ✅ Subset | Core methods (match, put, delete) |
| WinterCG | ✅ Fully Supported | 100% |
Highlights:
- RFC 7234: Cache-Control directives, GET/HEAD caching, Vary processing, conditional requests
- RFC 5861:
stale-while-revalidateandstale-if-errorviacreateFetch - Web Cache API: Core methods with HTTP semantics;
match()/delete()supportignoreMethod(same subset as Cloudflare Workers Cache API) - Security: Requests with
Authorizationheaders are not cached unless the response explicitly allows it (public,s-maxage, etc.)
Powered by http-cache-semantics for RFC-compliant cache policy evaluation.
→ Full standards compliance guide — Web Cache API details, security notes, and implementation status.
☁️ Cloudflare Comparison
SharedCache is designed for origin-side caching (application servers with pluggable KVStorage such as Redis or S3), not as a replacement for Cloudflare's global edge cache. Where it helps to align with Cloudflare semantics, the library mirrors familiar patterns from the CDN and Workers Cache API:
- Cache Key — public
cacheKeyRules(search,header,cookie,device) vs Cloudflare Cache Rules - Cache Status —
x-cache-status(HIT,MISS,UPDATING,STALE, …) vsCF-Cache-Status - Workers Cache API —
match()/delete()withignoreMethodonly; noignoreSearch/ignoreVary - Storage —
KVStorageat the origin vs platform-managed edge / Workers cache
→ Full comparison guide — quick reference table and detailed notes.
📖 Documentation
| Guide | Description |
| ------------------------------------------------------------ | -------------------------------------------------------------------- |
| Examples | Redis, multi-tenant, authentication, and custom storage patterns |
| Configuration | Global setup, sharedCache options, cache key rules, and monitoring |
| API Reference | Complete API signatures and type definitions |
| Logging | Logger setup, log levels, and debugging techniques |
| FAQ | Storage backends, edge runtimes, Vary performance, and more |
| Standards Compliance | RFC details, Web Cache API subset, and security notes |
| Cloudflare Comparison | Mapping to Cloudflare Cache Rules and Workers Cache API |
🤝 Who's Using SharedCache
- Web Widget Meta Framework: Cache middleware
- InsMind.com: Page Cache
- Gaoding.com: Page Cache (Million-level URLs)
🙏 Acknowledgments
SharedCache draws inspiration from industry-leading caching implementations:
- Cloudflare Cache Key - Cache key customization patterns
- Next.js Data Cache - Server-side caching strategies
- nodejs/undici - Web Standards implementation
- http-cache-lru - HTTP cache semantics
- Cloudflare Miniflare - Edge runtime patterns
- Cloudflare Workers SDK - Worker environment optimizations
- ultrafetch - Fetch API extensions
- island.is Cache Middleware - Production caching patterns
- make-fetch-happen - HTTP caching with retry and offline support
📄 License
MIT License - see LICENSE file for details.