跳到內容
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 引數是一個包含以下鍵的物件

名稱描述
params如果此頁面使用動態路由,則 `params` 包含路由引數。如果頁面名稱為 `[id].js`,則 `params` 將類似於 `{ id: ... }`。
請求(req)`HTTP` IncomingMessage 物件,帶有一個額外的 `cookies` 屬性,它是一個將字串鍵對映到 cookie 字串值的物件。
響應(res)HTTP 響應物件.
查詢(query)一個表示查詢字串的物件,包括動態路由引數。
preview(已棄用,請使用 `draftMode`)如果頁面處於預覽模式,`preview` 為 `true`,否則為 `false`。
預覽資料(previewData)(已棄用,請使用 `draftMode`)由 `setPreviewData` 設定的預覽資料。
draftMode如果頁面處於草稿模式,`draftMode` 為 `true`,否則為 `false`。
解析後的 URL(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.0App Router 現已穩定,並簡化了資料獲取
v10.0.0添加了 `locale`、`locales`、`defaultLocale` 和 `notFound` 選項。
v9.3.0引入了 `getServerSideProps`。