伺服器端渲染 (SSR)
也稱為「SSR」或「動態渲染」。
如果頁面使用伺服器端渲染,則頁面 HTML 會在每次請求時產生。
若要將伺服器端渲染用於頁面,您需要 export
一個名為 getServerSideProps
的 async
函式。此函式將由伺服器在每次請求時呼叫。
例如,假設您的頁面需要預先渲染頻繁更新的資料(從外部 API 擷取)。您可以撰寫 getServerSideProps
,它會擷取此資料並將其傳遞給如下所示的 Page
export default function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
如您所見,getServerSideProps
類似於 getStaticProps
,但不同之處在於 getServerSideProps
是在每次請求時執行,而不是在建置時執行。
若要深入瞭解 getServerSideProps
的運作方式,請查看我們的資料擷取文件。
這有幫助嗎?