Basic Structure
cacheControlHandler
A function that dynamically generates Cache-Control headers for each request. Type:(req: CacheControlRequest) => string | undefined
Request Types
type:"assets"- Static files (JS, CSS, images, etc.)"api"- API endpoints"ssr"- SSR pages"csr"- CSR entry point (index.html)
GET, POST, PUT, DELETE, etc.)
path: Request path (/api/user/list, /assets/main.js, etc.)
CachePresets
Predefined caching strategies provided by Sonamu.Available Presets
CachePresets.noCache- Always verify latest version from origin server
- Use for: Real-time data, APIs requiring authentication
- Cache for 1 minute
- Use for: Frequently changing data, CSR entry point
- Cache for 5 minutes
- Use for: Data that changes at moderate intervals
- Cache for 1 hour
- Use for: Rarely changing static data
- Cache for 1 year, never changes
- Use for: Build files with hash in filename
- Cache for 10 seconds, refresh in background
- Use for: SSR pages
Basic Examples
Simple Configuration
Detailed Assets Configuration
Permanent cache for files with hash, regular cache for others:Path-based API Caching
Cache only GET requests selectively:Practical Examples
Standard Web App
CDN Optimization
Development vs Production
Custom Cache-Control
You can also return header values directly instead of using presets:Understanding Cache-Control
Key Directives
public- Can be cached by CDN and intermediate proxies
- Suitable for static files, public APIs
- Can only be cached by browser
- Suitable for personalized data
- Cache but always verify with origin
- Conditional requests (304 Not Modified) possible
- Donβt cache anywhere
- Use for sensitive data
- Fresh state for N seconds
- Use cache without revalidation during this period
- Will never change
- Browser skips revalidation
- Optimal for hash-based files
- Return stale version for N seconds after expiration
- Refresh in background
- Useful for SSR pages
Example Combinations
Returning undefined
Returnundefined if you donβt want to set the header:
Important Notes
1. APIs Requiring Authentication
2. Donβt Cache POST/PUT/DELETE
3. Detecting Hash-based Files
Next Steps
After completing Cache-Control configuration:- cache - Server-side caching (BentoCache)
- compress - Response compression settings
- advanced-features/ssr - Using Cache-Control in SSR