主题
getServerSideProps
getServerSideProps 是一个 Next.js 函数,可用于在请求时获取数据并渲染页面内容。
¥getServerSideProps is a Next.js function that can be used to fetch data and render the contents of a page at request time.
示例
¥Example
你可以通过从页面组件导出 getServerSideProps 来使用它。下面的示例展示了如何从 getServerSideProps 中的第 3 方 API 获取数据,并将数据作为 props 传递到页面:
¥You can use getServerSideProps by exporting it from a Page Component. The example below shows how you can fetch data from a 3rd party API in getServerSideProps, and pass the data to the page as props:
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?
¥When should I use getServerSideProps?
如果你需要渲染依赖于个性化用户数据或只能在请求时获知的信息的页面,则应使用 getServerSideProps。例如,authorization 标头或地理位置。
¥You should use getServerSideProps if you need to render a page that relies on personalized user data, or information that can only be known at request time. For example, authorization headers or a geolocation.
如果你不需要在请求时获取数据,或者希望缓存数据和预渲染 HTML,我们建议使用 getStaticProps。
¥If you do not need to fetch the data at request time, or would prefer to cache the data and pre-rendered HTML, we recommend using getStaticProps.
行为
¥Behavior
getServerSideProps在服务器上运行。¥
getServerSidePropsruns on the server.getServerSideProps只能从页面导出。¥
getServerSidePropscan only be exported from a page.getServerSideProps返回 JSON。¥
getServerSidePropsreturns JSON.当用户访问页面时,
getServerSideProps将用于在请求时获取数据,并且该数据用于渲染页面的初始 HTML。¥When a user visits a page,
getServerSidePropswill be used to fetch data at request time, and the data is used to render the initial HTML of the page.传递给页面组件的
props可以作为初始 HTML 的一部分在客户端上查看。这是为了让页面正确为 hydrated。确保你没有传递任何不应在props中的客户端上可用的敏感信息。¥
propspassed to the page component can be viewed on the client as part of the initial HTML. This is to allow the page to be hydrated correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client inprops.当用户通过
next/link或next/router访问页面时,Next.js 会向运行getServerSideProps的服务器发送 API 请求。¥When a user visits the page through
next/linkornext/router, Next.js sends an API request to the server, which runsgetServerSideProps.使用
getServerSideProps时,你不必调用 Next.js API 路由 来获取数据,因为该函数在服务器上运行。相反,你可以直接从getServerSideProps内部调用 CMS、数据库或其他第三方 API。¥You do not have to call a Next.js API Route to fetch data when using
getServerSidePropssince the function runs on the server. Instead, you can call a CMS, database, or other third-party APIs directly from insidegetServerSideProps.
需要了解:
¥Good to know:
请参阅
getServerSidePropsAPI 参考 了解可与getServerSideProps一起使用的参数和属性。¥See
getServerSidePropsAPI reference for parameters and props that can be used withgetServerSideProps.你可以使用 next-code-elimination 工具 来验证 Next.js 从客户端包中删除了哪些内容。
¥You can use the next-code-elimination tool to verify what Next.js eliminates from the client-side bundle.
错误处理
¥Error Handling
如果 getServerSideProps 内部抛出错误,则会显示 pages/500.js 文件。查看 500 页 的文档以了解有关如何创建它的更多信息。在开发过程中,将不会使用该文件,而是会显示开发错误覆盖图。
¥If an error is thrown inside getServerSideProps, it will show the pages/500.js file. Check out the documentation for 500 page to learn more on how to create it. During development, this file will not be used and the development error overlay will be shown instead.
边缘情况
¥Edge Cases
使用服务器端渲染 (SSR) 进行缓存
¥Caching with Server-Side Rendering (SSR)
你可以在 getServerSideProps 内使用缓存标头 (Cache-Control) 来缓存动态响应。例如,使用 stale-while-revalidate。
¥You can use caching headers (Cache-Control) inside getServerSideProps to cache dynamic responses. For example, using stale-while-revalidate.
但是,在选择 cache-control 之前,我们建议你先看看 getStaticProps 和 ISR 是否更适合你的用例。
¥However, before reaching for cache-control, we recommend seeing if getStaticProps with ISR is a better fit for your use case.