Skip to content

web-widget/shared-cache

Repository files navigation

SharedCache

CI npm version TypeScript License: MIT codecov Node.js Deno Bun WinterCG RFC Compliant

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

  • πŸ“‹ RFC Compliance: Supports RFC 5861 directives like stale-if-error and stale-while-revalidate
  • 🎯 Smart Caching: Handles complex HTTP scenarios including Vary headers, proxy revalidation, and authenticated responses
  • πŸ”§ Flexible Storage: Pluggable storage backend supporting memory, Redis, or any custom key-value store
  • πŸš€ Enhanced Fetch: Extends the standard fetch API with caching capabilities while maintaining full compatibility
  • πŸ”Œ Middleware Origin: createCacheHandler for in-process handlers (e.g. middleware next())
  • πŸŽ›οΈ Custom Cache Keys: Cache key customization supporting device types, cookies, headers, and URL components
  • ⚑ Shared Cache Optimization: Prioritizes s-maxage over max-age for 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 caches API 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 caches API
  • 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-cache directly
  • 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-revalidate and stale-if-error via createFetch
  • Web Cache API: Core methods with HTTP semantics; match() / delete() support ignoreMethod (same subset as Cloudflare Workers Cache API)
  • Security: Requests with Authorization headers 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, …) vs CF-Cache-Status
  • Workers Cache API β€” match() / delete() with ignoreMethod only; no ignoreSearch / ignoreVary
  • Storage β€” KVStorage at 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

πŸ™ Acknowledgments

SharedCache draws inspiration from industry-leading caching implementations:

πŸ“„ License

MIT License - see LICENSE file for details.

About

πŸš€ Standards-compliant HTTP cache implementation for server-side JavaScript with RFC 7234 compliance and cross-runtime support

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors