getServerSideProps

getServerSideProps 是 Next.js 的一個函數,可用於在請求時獲取資料並渲染頁面內容。

範例

您可以透過從頁面元件 (Page Component) 中匯出 getServerSideProps 來使用它。以下範例展示如何在 getServerSideProps 中從第三方 API 獲取資料,並將資料作為 props 傳遞給頁面:

import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'

type Repo = {
  name: string
  stargazers_count: number
}

export const getServerSideProps = (async () => {
  // 從外部 API 獲取資料
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo: Repo = await res.json()
  // 透過 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

如果您需要渲染依賴於個人化使用者資料或只能在請求時獲取的資訊(例如 authorization 標頭或地理位置)的頁面,則應使用 getServerSideProps

如果不需要在請求時獲取資料,或者希望快取資料和預先渲染的 HTML,我們建議使用 getStaticProps

行為

  • getServerSideProps 在伺服器端執行。
  • getServerSideProps 只能從 頁面 (page) 匯出。
  • getServerSideProps 回傳 JSON。
  • 當使用者訪問頁面時,getServerSideProps 會在請求時獲取資料,並使用該資料渲染頁面的初始 HTML。
  • 傳遞給頁面元件的 props 可以在客戶端作為初始 HTML 的一部分查看。這是為了讓頁面能夠正確地水合 (hydrate)。請確保不要在 props 中傳遞任何不應在客戶端顯示的敏感資訊。
  • 當使用者透過 next/linknext/router 訪問頁面時,Next.js 會向伺服器發送 API 請求,該請求會執行 getServerSideProps
  • 使用 getServerSideProps 時,不需要呼叫 Next.js 的 API 路由 (API Route) 來獲取資料,因為該函數在伺服器端執行。相反,您可以直接在 getServerSideProps 內部呼叫 CMS、資料庫或其他第三方 API。

重要須知:

錯誤處理

如果在 getServerSideProps 內部拋出錯誤,則會顯示 pages/500.js 檔案。請查看 500 頁面 的文件以了解如何建立它。在開發過程中,不會使用此檔案,而是會顯示開發錯誤覆蓋層。

特殊情況

伺服器渲染 (SSR) 的快取

您可以在 getServerSideProps 內部使用快取標頭 (Cache-Control) 來快取動態回應。例如,使用 stale-while-revalidate

// 此值在十秒內被視為新鮮的 (s-maxage=10)。
// 如果在接下來的 10 秒內重複請求,則先前快取的值仍將是新鮮的。
// 如果在 59 秒內重複請求,快取的值將過時但仍會渲染 (stale-while-revalidate=59)。
//
// 在背景中,將發出重新驗證請求以用新值填充快取。
// 如果您刷新頁面,您將看到新值。
export async function getServerSideProps({ req, res }) {
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=10, stale-while-revalidate=59'
  )

  return {
    props: {},
  }
}

不過,在考慮使用 cache-control 之前,我們建議先查看 getStaticPropsISR (增量靜態再生) 是否更適合您的使用案例。

On this page