伺服器端渲染 (Server-side Rendering)
也稱為「SSR」或「動態渲染 (Dynamic Rendering)」。
如果一個頁面使用了伺服器端渲染 (Server-side Rendering),該頁面的 HTML 會在每次請求時生成。
若要為頁面啟用伺服器端渲染,你需要 export
一個名為 getServerSideProps
的 async
函式。伺服器會在每次請求時呼叫此函式。
舉例來說,假設你的頁面需要預渲染頻繁更新的資料(從外部 API 獲取)。你可以撰寫如下所示的 getServerSideProps
來獲取資料並傳遞給 Page
:
export default function Page({ data }) {
// 渲染資料...
}
// 此函式會在每次請求時被呼叫
export async function getServerSideProps() {
// 從外部 API 獲取資料
const res = await fetch(`https://.../data`)
const data = await res.json()
// 透過 props 將資料傳遞給頁面
return { props: { data } }
}
如你所見,getServerSideProps
與 getStaticProps
相似,但區別在於 getServerSideProps
會在每次請求時執行,而非在建置階段。
要了解更多關於 getServerSideProps
的運作方式,請參閱我們的資料獲取文件。