getServerSideProps
getServerSideProps 是一个 Next.js 函数,用于在请求时获取数据并渲染页面内容。
示例
您可以从页面组件中导出 getServerSideProps 来使用它。下面的示例展示了如何在 getServerSideProps 中从第三方 API 获取数据,并将数据作为 props 传递给页面。
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。例如,authorization 标头或地理位置。
如果您不需要在请求时获取数据,或者更喜欢缓存数据和预渲染的 HTML,我们建议使用 getStaticProps。
行为
getServerSideProps在服务器上运行。getServerSideProps只能从页面中导出。getServerSideProps返回 JSON。- 当用户访问页面时,
getServerSideProps将在请求时用于获取数据,这些数据将用于渲染页面的初始 HTML。 - 传递给页面组件的
props可作为初始 HTML 的一部分在客户端上查看。这是为了使页面能够正确地 水合。请确保不要在props中传递任何不应在客户端上可用的敏感信息。 - 当用户通过
next/link或next/router访问页面时,Next.js 会向服务器发送一个 API 请求,该请求会运行getServerSideProps。 - 由于函数在服务器上运行,因此在使用
getServerSideProps时,您无需调用 Next.js API 路由来获取数据。相反,您可以直接从getServerSideProps内部调用 CMS、数据库或其他第三方 API。
须知
- 有关可与
getServerSideProps一起使用的参数和 props,请参阅getServerSidePropsAPI 参考。- 您可以使用 next-code-elimination 工具 来验证 Next.js 从客户端包中消除了哪些内容。
错误处理
如果在 getServerSideProps 内部抛出错误,它将显示 pages/500.js 文件。查看 500 页面的文档,了解如何创建它。在开发过程中,此文件将不被使用,而是显示开发错误叠加层。
边界情况
服务器端渲染 (SSR) 的缓存
您可以在 getServerSideProps 内部使用缓存头 (Cache-Control) 来缓存动态响应。例如,使用 stale-while-revalidate。
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {},
}
}然而,在考虑使用 cache-control 之前,我们建议您查看 getStaticProps 结合 ISR 是否更适合您的用例。
这有帮助吗?