← Back to Docs
Recipe

SWR Data Fetching Patterns

Stale-while-revalidate strategies for instant UI with background freshness.

Core Pattern

Serve cached data immediately, then revalidate in the background. The user sees stale content for milliseconds while fresh data streams in — no spinners, no layout shift.

// fetch with SWR headers
const res = await fetch('/api/session', {
  headers: {
    'Cache-Control': 'max-age=0',
    'x-swr': '1'
  }
})

// response carries stale-while-revalidate
// Cache-Control: max-age=5, stale-while-revalidate=30

Edge Caching

Vercel Edge Network respects stale-while-revalidate. Set it on your API route and every request after the first hits the edge cache while a single origin revalidation runs.

res.setHeader(
  'Cache-Control',
  'public, max-age=10, stale-while-revalidate=60'
)

Client Hydration

Pair SWR with a client-side store. On navigation, read from the store instantly. Fire a background fetch that updates the store and triggers a reactive re-render only when data actually changed.

  • Instant paint from memory cache
  • Background revalidation with deduplication
  • Optimistic mutations with rollback