getServerSideProps
getServerSideProps
是 Next.js 的一个函数,可用于在请求时获取数据并渲染页面内容。
示例
您可以通过从页面组件中导出 getServerSideProps
来使用它。以下示例展示了如何在 getServerSideProps
中从第三方 API 获取数据,并将数据作为 props 传递给页面:
何时使用 getServerSideProps
?
如果您需要渲染依赖个性化用户数据或只能在请求时获取的信息的页面,则应使用 getServerSideProps
。例如,authorization
头信息或地理位置信息。
如果您不需要在请求时获取数据,或者希望缓存数据和预渲染的 HTML,我们建议使用 getStaticProps
。
行为
getServerSideProps
在服务器端运行。getServerSideProps
只能从 页面 中导出。getServerSideProps
返回 JSON。- 当用户访问页面时,
getServerSideProps
会在请求时获取数据,并将数据用于渲染页面的初始 HTML。 - 传递给页面组件的
props
可以在客户端作为初始 HTML 的一部分查看。这是为了让页面能够正确进行 hydrate。确保不要在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 从客户端 bundle 中移除了哪些内容。
错误处理
如果在 getServerSideProps
中抛出错误,将会显示 pages/500.js
文件。查看 500 页面 文档了解如何创建它。在开发环境中,不会使用此文件,而是会显示开发错误覆盖层。
边缘情况
边缘运行时 (Edge Runtime)
getServerSideProps
可与 Serverless 和 Edge 运行时 一起使用,并且您可以在两者中设置 props。
但是,目前在 Edge 运行时中,您无法访问响应对象。这意味着您不能在 getServerSideProps
中执行诸如添加 cookie 等操作。要访问响应对象,您应 继续使用 Node.js 运行时,这是默认的运行时。
您可以通过修改 config
在每页基础上显式设置运行时,例如:
服务端渲染 (SSR) 缓存
您可以在 getServerSideProps
中使用缓存头 (Cache-Control
) 来缓存动态响应。例如,使用 stale-while-revalidate
。
但是,在考虑使用 cache-control
之前,我们建议先查看 getStaticProps
与 ISR 是否更适合您的用例。