跳到主要內容

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

行為

  • getServerSideProps 在伺服器上執行。
  • getServerSideProps 只能從頁面匯出。
  • getServerSideProps 回傳 JSON。
  • 當使用者訪問頁面時,將會使用 getServerSideProps 在請求時獲取資料,並且資料會被用來渲染頁面的初始 HTML。
  • 傳遞到頁面元件的 props 在客戶端可以被視為初始 HTML 的一部分。這是為了允許頁面正確地 hydration。請確保您不要在 props 中傳遞任何不應該在客戶端上可用的敏感資訊。
  • 當使用者透過 next/linknext/router 訪問頁面時,Next.js 會發送 API 請求到伺服器,伺服器會執行 getServerSideProps
  • 當使用 getServerSideProps 時,您不必呼叫 Next.js API 路由 來獲取資料,因為該函數在伺服器上執行。相反地,您可以直接從 getServerSideProps 內部呼叫 CMS、資料庫或其他第三方 API。

須知

錯誤處理

如果在 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 之前,我們建議您先看看 getStaticPropsISR 是否更適合您的使用案例。