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 的一部分查看。这是为了允许页面正确地 hydration。请确保你没有在props
中传递任何不应在客户端上可用的敏感信息。 - 当用户通过
next/link
或next/router
访问页面时,Next.js 会向服务器发送 API 请求,服务器会运行getServerSideProps
。 - 使用
getServerSideProps
时,你不必调用 Next.js API 路由 来获取数据,因为该函数在服务器上运行。相反,你可以直接从getServerSideProps
内部调用 CMS、数据库或其他第三方 API。
须知
- 有关可以与
getServerSideProps
一起使用的参数和 props,请参阅getServerSideProps
API 参考。- 你可以使用 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 是否更适合你的用例。
这有帮助吗?