Nuxt ISR
This rendering mode operates similarly to SWR (Stale-While-Revalidate), with the primary distinction being that the response is cached on a CDN (Content Delivery Network). There are two potential settings for caching:
- No TTL (Time To Live): This implies that the response is cached permanently. To enable this mode, set up a route rule in
nuxt.configas follows:
export default defineNuxtConfig({
routeRules: {
"/isr_no_ttl": { isr: true },
},
})- TTL Set: In this case, the response is cached until the TTL expires. To enable this mode, set up a route rule in
nuxt.configas follows:
export default defineNuxtConfig({
routeRules: {
"/isr_ttl": { isr: 60 },
},
})Note: ISR in Nuxt 3 differs significantly from ISR in Next.js in terms of HTML generation. In Nuxt 3, ISR generates HTML on demand, while in Next.js, ISR typically generates HTML during the build time by default.
當你的網站有數以千計以上的頁面文章或產品,你可能會預先選染這些頁面,來降低使用者瀏覽頁面的等待時間,但如果你的這些頁面因為新增或變動時,你可能就要重新建構一次網站做全靜態的渲染,這顯然非常花費時間。
ISR (Incremental Static Regeneration) 是靜態產生 SSG (Static Site Generation) 技術的改良,它可以在伺服器中定時的重新產生這些被變動或新增的頁面,以確保頁面資料的新鮮程度。
舉例來說,網站中存在一個 /top100-products 的頁面,這個頁面的資料用來呈現前 100 個熱門的商品,它會隨著時間與銷量而進行變化,如果我們只對這個頁面單純的做 SSG 那麼將無法取得最新的排名狀況,而單純使用 SSR 則可能每次請求都需要等待渲染這個頁面的時間。
我們可以配置在 Nuxt Config 中的 routeRules 添加 isr 的選項來使用 ISR,讓 /top100-products 頁面可以在伺服器中定時的渲染,{ isr: 1800 } 表示每半小時重新渲染一次。
export default defineNuxtConfig({
routeRules: {
'/top100-products': { isr: 1800 }
}
})如此一來使用者下一次所取得的頁面資料,便是會隨著時間所更新的新排名,同時也保持著如靜態網頁的載入速度。
總結來說,ISR (Incremental Static Regeneration) 的核心概念,當頁面內容有調整或新增時,這些頁面不必再次的重新建構做預渲染,這些路由的頁面會在支援 ISR 的伺服器或雲端服務中定時重新渲染頁面,當使用者瀏覽頁面時就能保有靜態頁面的載入速度,又能看到定時更新後的新內容。
Note that all the above mentioned rendering modes, except for ISR, can be easily tested in a local environment by building and previewing the app. ISR, however, relies on a CDN network for its functionality, which means it requires a CDN for proper testing. For example, deploying to Vercel would be necessary to test ISR effectively.
Reference
Comparing Nuxt 3 Rendering Modes: SWR, ISR, SSR, SSG, SPA - RisingStack Engineering