getServerSideProps
当从页面导出名为 getServerSideProps
(服务器端渲染)的函数时,Next.js 将使用 getServerSideProps
返回的数据在每个请求上预渲染此页面。如果你想要获取经常更改的数据并更新页面以显示最新数据,这非常有用。
¥When exporting a function called getServerSideProps
(Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps
. This is useful if you want to fetch data that changes often, and have the page update to show the most current data.
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
中编写服务器端代码,包括从数据库中获取数据。
¥You can import modules in top-level scope for use in getServerSideProps
. Imports used will not be bundled for the client-side. This means you can write server-side code directly in getServerSideProps
, including fetching data from your database.
上下文参数
¥Context parameter
context
参数是一个包含以下键的对象:
¥The context
parameter is an object containing the following keys:
名称 | 描述 |
---|---|
params | 如果该页面使用 动态路由,params 包含路由参数。如果页面名称是 [id].js ,那么 params 将看起来像 { id: ... } 。 |
req | HTTP IncomingMessage 对象,还有一个额外的 cookies 属性,它是一个字符串键映射到 cookie 字符串值的对象。 |
res | HTTP 响应对象。 |
query | 表示查询字符串的对象,包括动态路由参数。 |
preview | (draftMode 已弃用)如果页面位于 预览模式 中,则 preview 为 true ,否则为 false 。 |
previewData | (draftMode 已弃用)preview 数据由 setPreviewData 设置。 |
draftMode | 如果页面位于 草稿模式 中,则 draftMode 为 true ,否则为 false 。 |
resolvedUrl | 请求 URL 的规范化版本,去除客户端转换的 _next/data 前缀并包含原始查询值。 |
locale | 包含活动区域设置(如果启用)。 |
locales | 包含所有支持的区域设置(如果启用)。 |
defaultLocale | 包含配置的默认区域设置(如果启用)。 |
getServerSideProps 返回值
¥getServerSideProps return values
getServerSideProps
函数应返回具有以下任一属性的对象:
¥The getServerSideProps
function should return an object with any one of the following properties:
props
props
对象是一个键值对,其中每个值都由页面组件接收。它应该是 可序列化对象,这样任何传递的 props 都可以用 JSON.stringify
序列化。
¥The props
object is a key-value pair, where each value is received by the page component. It should be a serializable object so that any props passed, could be serialized with JSON.stringify
.
notFound
notFound
布尔值允许页面返回 404
状态和 404 页面。对于 notFound: true
,即使之前已经成功生成过页面,页面也会返回 404
。这是为了支持用户生成的内容被作者删除等用例。
¥The notFound
boolean allows the page to return a 404
status and 404 Page. With notFound: true
, the page will return a 404
even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author.
redirect
redirect
对象允许重定向到内部和外部资源。它应该与 { destination: string, permanent: boolean }
的形状相匹配。在极少数情况下,你可能需要为较旧的 HTTP
客户端分配自定义状态代码才能正确重定向。在这些情况下,你可以使用 statusCode
属性而不是 permanent
属性,但不能同时使用两者。
¥The redirect
object allows redirecting to internal and external resources. It should match the shape of { destination: string, permanent: boolean }
. In some rare cases, you might need to assign a custom status code for older HTTP
clients to properly redirect. In these cases, you can use the statusCode
property instead of the permanent
property, but not both.
版本历史
¥Version History
版本 | 更改 |
---|---|
v13.4.0 | 应用路由 现已稳定并简化了数据获取 |
v10.0.0 | 添加了 locale 、locales 、defaultLocale 和 notFound 选项。 |
v9.3.0 | getServerSideProps 已引入。 |