Skip to main content
Sonamu can automatically set HTTP Cache-Control headers to control caching behavior in browsers and CDNs. You can apply appropriate caching strategies for each resource type including API responses, static files, and SSR pages.

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)
method: HTTP method (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
CachePresets.shortLived (1 minute)
  • Cache for 1 minute
  • Use for: Frequently changing data, CSR entry point
CachePresets.mediumLived (5 minutes)
  • Cache for 5 minutes
  • Use for: Data that changes at moderate intervals
CachePresets.longLived (1 hour)
  • Cache for 1 hour
  • Use for: Rarely changing static data
CachePresets.immutable (1 year)
  • Cache for 1 year, never changes
  • Use for: Build files with hash in filename
CachePresets.ssr (10 seconds)
  • 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
private
  • Can only be cached by browser
  • Suitable for personalized data
no-cache
  • Cache but always verify with origin
  • Conditional requests (304 Not Modified) possible
no-store
  • Don’t cache anywhere
  • Use for sensitive data
max-age=N
  • Fresh state for N seconds
  • Use cache without revalidation during this period
immutable
  • Will never change
  • Browser skips revalidation
  • Optimal for hash-based files
stale-while-revalidate=N
  • Return stale version for N seconds after expiration
  • Refresh in background
  • Useful for SSR pages

Example Combinations

Returning undefined

Return undefined 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: