Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

isr.md

496 lines12.3 KB

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 )
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 },
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