跳至內容
API 參考函式getServerSideProps

getServerSideProps

當您從頁面匯出名為 getServerSideProps (伺服器端渲染) 的函式時,Next.js 會使用 getServerSideProps 回傳的資料,在每次請求時預先渲染此頁面。如果您想要提取經常變更的資料,並讓頁面更新以顯示最新資料,這將非常有用。

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 中編寫伺服器端程式碼**,包括從資料庫提取資料。

內容參數(Context parameter)

context 參數是一個物件,包含以下鍵值:

名稱說明
params如果此頁面使用動態路由params 會包含路由參數。如果頁面名稱是 [id].js,則 params 看起來會像 { id: ... }
reqHTTP IncomingMessage 物件,並新增一個 cookies 屬性,它是一個物件,其中的字串鍵值對應到 Cookie 的字串值。
resHTTP 回應物件.
query一個代表查詢字串的物件,包含動態路由參數。
preview(已棄用,改用 draftMode)如果頁面處於預覽模式,則 previewtrue,否則為 false
previewData(已棄用,改用 draftMode)由 setPreviewData 設定的預覽資料。
draftMode如果頁面處於草稿模式,則 draftModetrue,否則為 false
resolvedUrl請求 URL 的標準化版本,它會去除客戶端轉換的 _next/data 前綴,並包含原始查詢值。
locale包含目前使用的語系(如果已啟用)。
locales包含所有支援的語系(如果已啟用)。
defaultLocale包含設定的預設語系(如果已啟用)。

getServerSideProps 回傳值

getServerSideProps 函式應該回傳一個物件,其中包含**以下任一**屬性:

props

props 物件是一個鍵值對,其中每個值都由頁面組件接收。它應該是一個可序列化物件,以便任何傳遞的 props 都可以使用 JSON.stringify 進行序列化。

export async function getServerSideProps(context) {
  return {
    props: { message: `Next.js is awesome` }, // will be passed to the page component as props
  }
}

notFound

布林值 notFound 允許頁面返回 404 狀態和404 頁面。設定 notFound: true 時,即使之前已成功產生頁面,該頁面仍會返回 404。這是為了支援像是使用者產生的內容被其作者刪除的用例。

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
 
  if (!data) {
    return {
      notFound: true,
    }
  }
 
  return {
    props: { data }, // will be passed to the page component as props
  }
}

redirect

redirect 物件允許重新導向到內部和外部資源。它的形狀應符合 { destination: string, permanent: boolean }。在極少數情況下,您可能需要為較舊的 HTTP 用戶端指定自訂狀態碼才能正確重新導向。在這些情況下,您可以使用 statusCode 屬性代替 permanent 屬性,但不能同時使用兩者。

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
 
  if (!data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }
 
  return {
    props: {}, // will be passed to the page component as props
  }
}

版本歷史記錄

版本變更
v13.4.0應用程式路由器 現在已穩定,並簡化了資料提取
v10.0.0新增了 localelocalesdefaultLocalenotFound 選項。
v9.3.0引入了 getServerSideProps