getServerSideProps
getServerSideProps
是一個 Next.js 函式,可用於在請求時擷取資料並渲染頁面的內容。
範例
您可以透過從頁面元件匯出 getServerSideProps
來使用它。以下範例顯示如何在 getServerSideProps
中從第三方 API 擷取資料,並將資料作為 props 傳遞到頁面
pages/index.tsx
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps = (async () => {
// Fetch data from external API
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo: Repo = await res.json()
// Pass data to the page via props
return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}
什麼時候應該使用 getServerSideProps
?
如果您需要渲染依賴個人化使用者資料或僅能在請求時才知道的資訊的頁面,則應該使用 getServerSideProps
。例如,authorization
標頭或地理位置。
如果您不需要在請求時擷取資料,或者希望快取資料和預渲染的 HTML,我們建議您使用 getStaticProps
。
行為。請確保您不要在 props
中傳遞任何不應該在客戶端上可用的敏感資訊。
next/link
或 next/router
造訪頁面時,Next.js 會向伺服器發送 API 請求,伺服器會運行 getServerSideProps
。getServerSideProps
時,您不必呼叫 Next.js 的 API 路由 來擷取資料,因為該函式在伺服器上運行。您可以直接從 getServerSideProps
內部呼叫 CMS、資料庫或其他第三方 API。注意事項
- 請參閱
getServerSideProps
API 參考,瞭解可與getServerSideProps
一起使用的參數和屬性。- 您可以使用 next-code-elimination 工具
來驗證 Next.js 從客戶端套件中刪除了哪些內容。
錯誤處理
如果在 getServerSideProps
內拋出錯誤,它會顯示 pages/500.js
檔案。查看500 頁面的說明文件,以瞭解更多關於如何建立它的資訊。在開發過程中,不會使用此檔案,而是會顯示開發錯誤覆蓋。
邊緣案例
使用伺服器端渲染 (SSR) 進行快取
您可以在 getServerSideProps
內使用快取標頭 (Cache-Control
) 來快取動態回應。例如,使用 stale-while-revalidate
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {},
}
}
然而,在使用 cache-control
之前,我們建議您先看看使用 ISR 的 getStaticProps
是否更適合您的使用案例。
這有幫助嗎?