Skip to main content
You can set Cache-Control headers on API responses by adding the cacheControl option to Sonamu’s @api decorator.

Basic Usage

Adding to @api Decorator

Result:

Configuration Methods

The simplest approach
Available presets:
  • noStore: No caching
  • noCache: Revalidate every time
  • shortLived: 1 minute
  • mediumLived: 5 minutes
  • longLived: 1 hour
  • private: Personalized data

Priority Order

Cache-Control settings are applied in the following order:
  1. @api decorator’s cacheControl (highest priority)
  2. cacheControlHandler return value
  3. Default (no Cache-Control header)

Example

Result: mediumLived applied (decorator takes priority)

Strategies by HTTP Method

GET Requests

Read APIs can be cached.

POST, PUT, DELETE Requests

Mutation requests should not be cached.
Why you should not cache mutation requests:
  • Sending the same POST request multiple times causes duplicate creations
  • Browser reuses previous response → appears as if nothing was actually created

Strategies by Data Characteristics

Public Data (public)

Same response for all users.
Characteristics:
  • Cached by browser + CDN
  • Minimizes network traffic
  • Reduces server load

Private Data (private)

Different response for each user.
Characteristics:
  • 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.
Effect:
  • 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:
CloudFront Support: AWS CloudFront supports stale-while-revalidate.

Vary Header

Uses different caches based on request headers.
Result:

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.
Effect:
  1. 0-60 seconds: Browser cache (no server request)
  2. 60 seconds - 10 minutes: Server request but uses BentoCache (no DB query)
  3. After 10 minutes: DB query → cache again

Precautions

Precautions when using API Cache-Control:
  1. Only cache GET: POST, PUT, DELETE must use noStore
  2. Private data must be private: Prevent CDN caching
  3. Short TTL for frequently changing data: Prevent stale data
  4. Be careful with authenticated APIs: Consider Authorization header

Next Steps

What is Cache-Control?

HTTP caching fundamentals

Cache Presets

Predefined cache configurations

Using in SSR

Apply Cache-Control to SSR pages