getServerSideProps
當從頁面導出名為 getServerSideProps
(伺服器端渲染 (Server-Side Rendering)) 的函數時,Next.js 會使用 getServerSideProps
返回的資料在每次請求時預先渲染此頁面。這適用於您想獲取頻繁變更的資料,並讓頁面更新以顯示最新資料的情況。
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>
)
}
export async function getServerSideProps() {
// 從外部 API 獲取資料
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
// 透過 props 將資料傳遞給頁面
return { props: { repo } }
}
export default function Page({ repo }) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}
您可以在頂層作用域導入模組以在 getServerSideProps
中使用。使用的導入 不會被打包到客戶端。這意味著您可以直接在 getServerSideProps
中編寫 伺服器端程式碼,包括從資料庫獲取資料。
Context 參數
context
參數是一個包含以下鍵的物件:
名稱 | 描述 |
---|---|
params | 如果此頁面使用 動態路由,params 包含路由參數。如果頁面名稱為 [id].js ,則 params 會像 { id: ... } 。 |
req | HTTP IncomingMessage 物件,帶有一個額外的 cookies 屬性,這是一個鍵值對應到 cookie 字串值的物件。 |
res | HTTP 回應物件。 |
query | 表示查詢字串的物件,包括動態路由參數。 |
preview | (已棄用,改用 draftMode ) 如果頁面處於 預覽模式 (Preview Mode),preview 為 true ,否則為 false 。 |
previewData | (已棄用,改用 draftMode ) 由 setPreviewData 設定的 預覽 (preview) 資料。 |
draftMode | 如果頁面處於 草稿模式 (Draft Mode),draftMode 為 true ,否則為 false 。 |
resolvedUrl | 請求 URL 的標準化版本,移除了客戶端轉換的 _next/data 前綴並包含原始查詢值。 |
locale | 包含當前使用的語言環境 (如果啟用)。 |
locales | 包含所有支援的語言環境 (如果啟用)。 |
defaultLocale | 包含配置的預設語言環境 (如果啟用)。 |
getServerSideProps 返回值
getServerSideProps
函數應返回一個包含 以下任一屬性 的物件:
props
props
物件是一個鍵值對,其中每個值都會傳遞給頁面元件。它應該是一個 可序列化物件 (serializable object),以便任何傳遞的 props 都可以用 JSON.stringify
序列化。
export async function getServerSideProps(context) {
return {
props: { message: `Next.js is awesome` }, // 將作為 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 | App Router 現已穩定,並簡化了資料獲取流程 |
v10.0.0 | 新增 locale 、locales 、defaultLocale 和 notFound 選項。 |
v9.3.0 | 引入 getServerSideProps 。 |