@schafevormfenster/caching
v0.1.1
Published
Unified cache configuration types and helpers
Readme
@schafevormfenster/caching
Unified caching configuration for REST APIs and Next.js applications with semantic cache categories, environment-based overrides, and CDN-friendly headers.
Purpose
Caching is critical for API performance, but managing cache configurations across multiple endpoints can be error-prone and inconsistent. This package provides:
- Single Source of Truth: Define cache TTLs once, use everywhere
- Semantic Categories: Name cache strategies by purpose, not duration
- Environment Flexibility: Override cache settings per environment without code changes
- CDN-Ready: Automatic
Cache-ControlandCDN-Cache-Controlheaders - Type Safety: Runtime validation with Zod schemas
- Next.js Integration: Works seamlessly with Next.js
cacheLifeconfig
Installation
pnpm add @schafevormfenster/cachingCache Categories
Each category represents a different caching strategy optimized for specific content types:
| Category | Use Case | Default Stale | Default Revalidate | Default Expire | |----------|----------|--------------|-------------------|----------------| | auth | Authentication tokens, sessions | 50 minutes | 5 minutes | 1 hour | | static | Static content, rarely changing data | 24 hours | 7 days | 7 days | | dynamic | Dynamic data, moderate change frequency | 4 hours | 1 day | 1 day | | config | Configuration, metadata, OpenAPI specs | 5 minutes | 1 hour | 1 hour | | health | Health checks, real-time status | 10 seconds | 0 (none) | 30 seconds | | error | Error responses | 1 second | 0 (none) | 2 seconds |
Cache Strategy
Each cache category follows a three-tier strategy:
- Stale Time: How long content is considered fresh and served immediately
- Revalidate Time: Background revalidation interval for stale content
- Expire Time: Absolute expiration time (used for
stale-if-error)
Basic Usage
Simple Endpoint with Caching
import { getCacheHeaders } from "@schafevormfenster/caching";
export async function GET() {
const data = await fetchData();
return Response.json(data, {
headers: getCacheHeaders('dynamic'),
});
}Get Cache TTL
import { getCacheTTL } from "@schafevormfenster/caching";
const ttl = getCacheTTL('static');
console.log(ttl); // 86400 (24 hours)Custom Cache Configuration
import { buildCacheControlHeader } from "@schafevormfenster/caching";
const customConfig = {
stale: 1800, // 30 minutes
revalidate: 3600, // 1 hour
expire: 7200, // 2 hours
};
const header = buildCacheControlHeader(customConfig);API Reference
Functions
getCacheHeaders(category)- Returns Cache-Control and CDN-Cache-Control headersgetCacheTTL(category)- Returns the stale value in secondsgetCacheControlHeader(category)- Returns Cache-Control header stringbuildCacheControlHeader(config)- Build custom cache control headergetCacheConfig(category)- Get full cache configuration with environment overridesgetFetchCacheOptions(category, tags?)- Get Next.js fetch cache options
Types
CacheCategory- Union type of all cache categoriesCacheLifeConfig- Cache configuration interfaceCacheLifeConfigSchema- Zod schema for validationCacheCategorySchema- Zod schema for category validation
Environment Configuration
Override cache settings per environment using environment variables:
# Development: shorter caches for faster iteration
CACHE_DYNAMIC_STALE=300 # 5 minutes instead of 4 hours
CACHE_STATIC_STALE=600 # 10 minutes instead of 24 hoursPattern: CACHE_{CATEGORY}_{PROPERTY} where:
{CATEGORY}is uppercase (AUTH, STATIC, DYNAMIC, CONFIG, HEALTH, ERROR){PROPERTY}is STALE, REVALIDATE, or EXPIRE
Documentation
- INSTRUCTIONS.md - Detailed usage guide with examples and best practices
- CONTRIBUTING.md - Development guidelines and contribution instructions
License
MIT
