Open History to see the last commit
1---
2id: isr
3title: Incremental Static Regeneration (ISR)
4---
5β
6Incremental Static Regeneration (ISR) allows you to serve statically generated content from a CDN while periodically regenerating it in the background. This gives you the performance benefits of static sites with the freshness of dynamic content.
7β
8## How ISR Works in TanStack Start
9β
10TanStack Start's approach to ISR is flexible and leverages standard HTTP cache headers that work with any CDN. Unlike framework-specific ISR implementations, this approach gives you full control over caching behavior at both the page and data level.
11β
12The core concept is simple:
13β
141. **Static Prerendering**: Pages are generated at build time
152. **CDN Caching**: Cache headers control how long CDNs cache the HTML
163. **Revalidation**: After the cache expires, the next request triggers regeneration
174. **Stale-While-Revalidate**: Serve stale content while fetching fresh data in the background
18β
19## Cache Header Strategies
20β
21### Time-Based Revalidation
22β
23The most common ISR pattern uses the `Cache-Control` header with `max-age` and `s-maxage` directives:
24β
25<!-- ::start:tabs variant="bundler" -->
26β
27# Vite
28β
29```ts title="vite.config.ts"
30import { tanstackStart } from '@tanstack/react-start/plugin/vite'
31import { defineConfig } from 'vite'
32β
33export default defineConfig({
34 plugins: [
35 tanstackStart({
36 prerender: {
37 routes: ['/blog', '/blog/posts/*'],
38 crawlLinks: true,
39 },
40 }),
41 ],
42})
43```
44β
45# Rsbuild
46β
47```ts title="rsbuild.config.ts"
48import { defineConfig } from '@rsbuild/core'
49import { pluginReact } from '@rsbuild/plugin-react'
50import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
51β
52export default defineConfig({
53 plugins: [
54 pluginReact(),
55 tanstackStart({
56 prerender: {
57 routes: ['/blog', '/blog/posts/*'],
58 crawlLinks: true,
59 },
60 }),
61 ],
62})
63```
64β
65<!-- ::end:tabs -->
66β
67```tsx
68// routes/blog/posts/$postId.tsx
69import { createFileRoute } from '@tanstack/react-router'
70β
71export const Route = createFileRoute('/blog/posts/$postId')({
72 loader: async ({ params }) => {
73 const post = await fetchPost(params.postId)
74 return { post }
75 },
76 headers: () => ({
77 // Cache at CDN for 1 hour, allow stale content for up to 1 day
78 'Cache-Control':
79 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
80 }),
81})
82β
83export default function BlogPost() {
84 const { post } = Route.useLoaderData()
85 return (
86 <article>
87 <h1>{post.title}</h1>
88 <div>{post.content}</div>
89 </article>
90 )
91}
92```
93β
94### Understanding Cache-Control Directives
95β
96- **`public`**: Response can be cached by any cache (CDN, browser, etc.)
97- **`max-age=3600`**: Content is fresh for 3600 seconds (1 hour)
98- **`s-maxage=3600`**: Overrides max-age for shared caches (CDNs)
99- **`stale-while-revalidate=86400`**: Serve stale content while revalidating in background for up to 24 hours
100- **`immutable`**: Content never changes (use for hash-based assets)
101β
102## ISR with Server Functions
103β
104Server functions can also set cache headers for dynamic data endpoints:
105β
106```tsx
107// routes/api/products/$productId.ts
108import { createFileRoute } from '@tanstack/react-router'
109β
110export const Route = createFileRoute('/api/products/$productId')({
111 server: {
112 handlers: {
113 GET: async ({ params, request }) => {
114 const product = await db.products.findById(params.productId)
115β
116 return Response.json(
117 { product },
118 {
119 headers: {
120 'Cache-Control':
121 'public, max-age=300, stale-while-revalidate=600',
122 'CDN-Cache-Control': 'max-age=3600', // Cloudflare-specific
123 },
124 },
125 )
126 },
127 },
128 },
129})
130```
131β
132### Using Middleware for Cache Headers
133β
134For API routes, you can use middleware to set cache headers:
135β
136```tsx
137// routes/api/products/$productId.ts
138import { createFileRoute } from '@tanstack/react-router'
139import { createMiddleware } from '@tanstack/react-start'
140β
141const cacheMiddleware = createMiddleware().server(async ({ next }) => {
142 const result = await next()
143β
144 // Add cache headers to the response
145 result.response.headers.set(
146 'Cache-Control',
147 'public, max-age=3600, stale-while-revalidate=86400',
148 )
149β
150 return result
151})
152β
153export const Route = createFileRoute('/api/products/$productId')({
154 server: {
155 middleware: [cacheMiddleware],
156 handlers: {
157 GET: async ({ params }) => {
158 const product = await db.products.findById(params.productId)
159 return Response.json({ product })
160 },
161 },
162 },
163})
164```
165β
166For page routes, it's simpler to use the `headers` property directly:
167β
168```tsx
169// routes/blog/posts/$postId.tsx
170import { createFileRoute } from '@tanstack/react-router'
171β
172export const Route = createFileRoute('/blog/posts/$postId')({
173 loader: async ({ params }) => {
174 const post = await fetchPost(params.postId)
175 return { post }
176 },
177 headers: () => ({
178 'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
179 }),
180})
181```
182β
183## On-Demand Revalidation
184β
185While time-based revalidation works well for most cases, you may need to invalidate specific pages immediately (e.g., when content is updated):
186β
187```tsx
188// routes/api/revalidate.ts
189import { createFileRoute } from '@tanstack/react-router'
190β
191export const Route = createFileRoute('/api/revalidate')({
192 server: {
193 handlers: {
194 POST: async ({ request }) => {
195 const { path, secret } = await request.json()
196β
197 // Verify secret token
198 if (secret !== process.env.REVALIDATE_SECRET) {
199 return Response.json({ error: 'Invalid token' }, { status: 401 })
200 }
201β
202 // Trigger CDN purge via your CDN's API
203 await fetch(
204 `https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/purge_cache`,
205 {
206 method: 'POST',
207 headers: {
208 Authorization: `Bearer ${CF_API_TOKEN}`,
209 'Content-Type': 'application/json',
210 },
211 body: JSON.stringify({
212 files: [`https://yoursite.com${path}`],
213 }),
214 },
215 )
216β
217 return Response.json({ revalidated: true })
218 },
219 },
220 },
221})
222```
223β
224## CDN-Specific Configuration
225β
226### Cloudflare Workers
227β
228Cloudflare respects standard `Cache-Control` headers and provides additional control:
229β
230```tsx
231export const Route = createFileRoute('/products/$id')({
232 headers: () => ({
233 'Cache-Control': 'public, max-age=3600',
234 // Cloudflare-specific header for finer control
235 'CDN-Cache-Control': 'max-age=7200',
236 }),
237})
238```
239β
240### Netlify
241β
242Netlify uses `Cache-Control` headers and also supports `_headers` files:
243β
244```plaintext
245# public/_headers
246/blog/*
247 Cache-Control: public, max-age=3600, stale-while-revalidate=86400
248β
249/api/*
250 Cache-Control: public, max-age=300
251```
252β
253### Vercel
254β
255When deploying to Vercel, use their Edge Network cache headers:
256β
257```tsx
258export const Route = createFileRoute('/posts/$id')({
259 headers: () => ({
260 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',
261 }),
262})
263```
264β
265## Combining ISR with Client-Side Caching
266β
267TanStack Router's built-in cache control works alongside CDN caching:
268β
269```tsx
270export const Route = createFileRoute('/posts/$postId')({
271 loader: async ({ params }) => {
272 return fetchPost(params.postId)
273 },
274 // CDN caching (via headers)
275 headers: () => ({
276 'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
277 }),
278 // Client-side caching (via TanStack Router)
279 staleTime: 60_000, // Consider data fresh for 60 seconds on client
280 gcTime: 5 * 60_000, // Keep in memory for 5 minutes
281})
282```
283β
284This creates a multi-tier caching strategy:
285β
2861. **CDN Edge**: 1 hour cache, stale-while-revalidate for 24 hours
2872. **Client**: 60 seconds of fresh data, 5 minutes in memory
288β
289## Common ISR Patterns
290β
291### Blog Posts
292β
293```tsx
294export const Route = createFileRoute('/blog/$slug')({
295 loader: async ({ params }) => fetchPost(params.slug),
296 headers: () => ({
297 // Cache for 1 hour, allow stale for 7 days
298 'Cache-Control': 'public, max-age=3600, stale-while-revalidate=604800',
299 }),
300 staleTime: 5 * 60_000, // 5 minutes client-side
301})
302```
303β
304### E-commerce Product Pages
305β
306```tsx
307export const Route = createFileRoute('/products/$id')({
308 loader: async ({ params }) => fetchProduct(params.id),
309 headers: () => ({
310 // Shorter cache due to inventory changes
311 'Cache-Control': 'public, max-age=300, stale-while-revalidate=3600',
312 }),
313 staleTime: 30_000, // 30 seconds client-side
314})
315```
316β
317### Marketing Landing Pages
318β
319```tsx
320export const Route = createFileRoute('/landing/$campaign')({
321 loader: async ({ params }) => fetchCampaign(params.campaign),
322 headers: () => ({
323 // Long cache for stable content
324 'Cache-Control': 'public, max-age=86400, stale-while-revalidate=604800',
325 }),
326 staleTime: 60 * 60_000, // 1 hour client-side
327})
328```
329β
330### User-Specific Pages
331β
332```tsx
333export const Route = createFileRoute('/dashboard')({
334 loader: async () => fetchUserData(),
335 headers: () => ({
336 // Private cache, no CDN caching
337 'Cache-Control': 'private, max-age=60',
338 }),
339 staleTime: 30_000,
340})
341```
342β
343## Best Practices
344β
345### 1. Start Conservative
346β
347Begin with shorter cache times and increase as you understand your content update patterns:
348β
349```tsx
350// Start here
351'Cache-Control': 'public, max-age=300, stale-while-revalidate=600'
352β
353// Then move to
354'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400'
355```
356β
357### 2. Use ETags for Validation
358β
359ETags help CDNs efficiently revalidate content:
360β
361```tsx
362import { createMiddleware } from '@tanstack/react-start'
363import crypto from 'crypto'
364β
365const etagMiddleware = createMiddleware().server(async ({ next }) => {
366 const result = await next()
367β
368 // Generate ETag from response content
369 const etag = crypto
370 .createHash('md5')
371 .update(JSON.stringify(result.data))
372 .digest('hex')
373β
374 result.response.headers.set('ETag', `"${etag}"`)
375β
376 return result
377})
378```
379β
380### 3. Vary Cache by Query Parameters
381β
382When content varies by query params, include them in cache keys:
383β
384```tsx
385export const Route = createFileRoute('/search')({
386 headers: () => ({
387 'Cache-Control': 'public, max-age=300',
388 Vary: 'Accept, Accept-Encoding',
389 }),
390})
391```
392β
393### 4. Monitor Cache Hit Rates
394β
395Track CDN performance to optimize cache times:
396β
397```tsx
398const cacheMonitoringMiddleware = createMiddleware().server(
399 async ({ next }) => {
400 const result = await next()
401β
402 // Log cache status (from CDN headers)
403 console.log('Cache Status:', result.response.headers.get('cf-cache-status'))
404β
405 return result
406 },
407)
408```
409β
410### 5. Combine with Static Prerendering
411β
412Prerender at build time for instant first load, then use ISR for updates:
413β
414<!-- ::start:tabs variant="bundler" -->
415β
416# Vite
417β
418```ts title="vite.config.ts"
419import { tanstackStart } from '@tanstack/react-start/plugin/vite'
420import { defineConfig } from 'vite'
421β
422export default defineConfig({
423 plugins: [
424 tanstackStart({
425 prerender: {
426 routes: ['/blog', '/blog/posts/*'],
427 crawlLinks: true,
428 },
429 }),
430 ],
431})
432```
433β
434# Rsbuild
435β
436```ts title="rsbuild.config.ts"
437import { defineConfig } from '@rsbuild/core'
438import { pluginReact } from '@rsbuild/plugin-react'
439import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
440β
441export default defineConfig({
442 plugins: [
443 pluginReact(),
444 tanstackStart({
445 prerender: {
446 routes: ['/blog', '/blog/posts/*'],
447 crawlLinks: true,
448 },
449 }),
450 ],
451})
452```
453β
454<!-- ::end:tabs -->
455β
456## Debugging ISR
457β
458### Check Cache Headers
459β
460Use browser DevTools or curl to inspect cache headers:
461β
462```bash
463curl -I https://yoursite.com/blog/my-post
464β
465# Look for:
466# Cache-Control: public, max-age=3600, stale-while-revalidate=86400
467# Age: 1234 (time in cache)
468# X-Cache: HIT (from CDN)
469```
470β
471### Test Revalidation
472β
473Force cache misses to test regeneration:
474β
475```bash
476# Cloudflare: Bypass cache
477curl -H "Cache-Control: no-cache" https://yoursite.com/page
478β
479# Or use CDN-specific cache purge APIs
480```
481β
482### Monitor Performance
483β
484Track key metrics:
485β
486- **Cache Hit Rate**: Percentage of requests served from cache
487- **Revalidation Time**: Time to regenerate stale content
488- **Time to First Byte (TTFB)**: Should be low for cached content
489β
490## Related Resources
491β
492- [Static Prerendering](./static-prerendering.md) - Build-time page generation
493- [Hosting](./hosting.md) - CDN deployment configurations
494- [Server Functions](./server-functions.md) - Creating dynamic data endpoints
495- [Data Loading](/router/latest/docs/guide/data-loading) - Client-side cache control
496- [Middleware](./middleware.md) - Request/response customization