npm package: @schafevormfenster/caching
Description: Unified cache configuration types and helpers
Latest version: 0.1.6

# @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-Control` and `CDN-Cache-Control` headers
- **Type Safety**: Runtime validation with Zod schemas
- **Next.js Integration**: Works seamlessly with Next.js `cacheLife` config

## Installation

```bash
pnpm add @schafevormfenster/caching
```

### TypeScript Sources (Optional)

For faster development with Vite, use TypeScript sources directly:

```typescript
// vite.config.ts - Requires tsconfig "target": "ES2022"+
export default defineConfig({
  resolve: { conditions: ['source', 'import', 'default'] }
});
```

Benefits: Faster HMR, direct debugging, better tree-shaking.

## Cache 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:

1. **Stale Time**: How long content is considered fresh and served immediately
2. **Revalidate Time**: Background revalidation interval for stale content
3. **Expire Time**: Absolute expiration time (used for `stale-if-error`)

## Basic Usage

### Simple Endpoint with Caching

```typescript
import { getCacheHeaders } from "@schafevormfenster/caching";

export async function GET() {
  const data = await fetchData();
  
  return Response.json(data, {
    headers: getCacheHeaders('dynamic'),
  });
}
```

### Get Cache TTL

```typescript
import { getCacheTTL } from "@schafevormfenster/caching";

const ttl = getCacheTTL('static');
console.log(ttl); // 86400 (24 hours)
```

### Custom Cache Configuration

```typescript
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 headers
- `getCacheTTL(category)` - Returns the stale value in seconds
- `getCacheControlHeader(category)` - Returns Cache-Control header string
- `buildCacheControlHeader(config)` - Build custom cache control header
- `getCacheConfig(category)` - Get full cache configuration with environment overrides
- `getFetchCacheOptions(category, tags?)` - Get Next.js fetch cache options

### Types

- `CacheCategory` - Union type of all cache categories
- `CacheLifeConfig` - Cache configuration interface
- `CacheLifeConfigSchema` - Zod schema for validation
- `CacheCategorySchema` - Zod schema for category validation

## Environment Configuration

Override cache settings per environment using environment variables:

```bash
# 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 hours
```

Pattern: `CACHE_{CATEGORY}_{PROPERTY}` where:
- `{CATEGORY}` is uppercase (AUTH, STATIC, DYNAMIC, CONFIG, HEALTH, ERROR)
- `{PROPERTY}` is STALE, REVALIDATE, or EXPIRE

## Documentation

- **[INSTRUCTIONS.md](./INSTRUCTIONS.md)** - Detailed usage guide with examples and best practices
- **[CONTRIBUTING.md](./CONTRIBUTING.md)** - Development guidelines and contribution instructions

## License

MIT