getServerSideProps
getServerSideProps
是 Next.js 的一个函数,可用于在请求时获取数据并渲染页面内容。
示例
你可以通过从页面组件导出 getServerSideProps
来使用它。下面的示例展示了如何在 getServerSideProps
中从第三方 API 获取数据,并将数据作为 props 传递给页面:
pages/index.tsx
TypeScript
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>
)
}
何时使用 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
API 参考,了解可与getServerSideProps
一起使用的参数和 props。- 你可以使用 next-code-elimination 工具 验证 Next.js 从客户端捆绑包中消除了什么。
错误处理
如果在 getServerSideProps
内部抛出错误,将显示 pages/500.js
文件。查看 500 页面文档,了解如何创建它。在开发过程中,不会使用此文件,而是显示开发错误遮罩。
边缘情况
服务器端渲染(SSR)缓存
你可以在 getServerSideProps
中使用缓存标头(Cache-Control
)来缓存动态响应。例如,使用 stale-while-revalidate
。
// 这个值被认为在十秒内是新鲜的(s-maxage=10)。
// 如果在接下来的 10 秒内重复请求,之前缓存的值仍然是新鲜的。
// 如果在 59 秒之前重复请求,缓存的值将是陈旧的,但仍然会渲染(stale-while-revalidate=59)。
//
// 在后台,将发出重新验证请求以使用新值填充缓存。
// 如果刷新页面,你将看到新值。
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {},
}
}
但是,在使用 cache-control
之前,我们建议先看看 getStaticProps
配合 ISR 是否更适合你的用例。