getServerSideProps

當從頁面導出名為 getServerSideProps (伺服器渲染 (SSR)) 的函數時,Next.js 會在每次請求時使用 getServerSideProps 返回的資料預渲染此頁面。這適用於需要獲取經常變動的資料,並讓頁面更新顯示最新資料的情況。

import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'

type Repo = {
  name: string
  stargazers_count: number
}

export const getServerSideProps = (async (context) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo = await res.json()
  return { props: { repo } }
}) satisfies GetServerSideProps<{
  repo: Repo
}>

export default function Page({
  repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return repo.stargazers_count
}

你可以在頂層作用域導入模組以用於 getServerSideProps。使用的導入內容 不會打包到客戶端。這意味著你可以直接在 getServerSideProps 中撰寫 伺服器端程式碼,包括從資料庫獲取資料。

Context 參數

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 非常棒` }, // 將作為 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 }, // 將作為 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: {}, // 將作為 props 傳遞給頁面元件
  }
}

版本歷史

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

On this page