cacheControl option to Sonamu’s @api decorator.
Basic Usage
Adding to @api Decorator
Configuration Methods
- Using Presets
- Custom Configuration
- Global Handler
The simplest approachAvailable presets:
noStore: No cachingnoCache: Revalidate every timeshortLived: 1 minutemediumLived: 5 minuteslongLived: 1 hourprivate: Personalized data
Priority Order
Cache-Control settings are applied in the following order:- @api decorator’s cacheControl (highest priority)
- cacheControlHandler return value
- Default (no Cache-Control header)
Example
mediumLived applied (decorator takes priority)
Strategies by HTTP Method
GET Requests
Read APIs can be cached.- Frequently Changed
- Occasionally Changed
- Rarely Changed
POST, PUT, DELETE Requests
Mutation requests should not be cached.Strategies by Data Characteristics
Public Data (public)
Same response for all users.- Cached by browser + CDN
- Minimizes network traffic
- Reduces server load
Private Data (private)
Different response for each user.- Cached only in browser (not CDN)
- Prevents exposure to other users
Sensitive Data (no-store)
Data that should not be cached.Practical Examples
1. E-commerce API
2. Blog API
3. User API
CDN Optimization
Using s-maxage
You can apply different TTLs for browser and CDN.- Browser: Requests CDN every minute
- CDN: Requests server every 5 minutes
- Minimizes server load
Stale-While-Revalidate
CDN returns stale response immediately while updating in background:stale-while-revalidate.
Vary Header
Uses different caches based on request headers.Global Handler
You can apply Cache-Control to all APIs at once.Using API Object
Using with BentoCache
Combining server cache with HTTP cache provides maximum performance.- 0-60 seconds: Browser cache (no server request)
- 60 seconds - 10 minutes: Server request but uses BentoCache (no DB query)
- After 10 minutes: DB query → cache again