getServerSideProps

getServerSideProps 是 Next.js 的一个函数,可用于在请求时获取数据并渲染页面内容。

示例

您可以通过从页面组件中导出 getServerSideProps 来使用它。以下示例展示了如何在 getServerSideProps 中从第三方 API 获取数据,并将数据作为 props 传递给页面:

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 的一部分查看。这是为了让页面能够正确进行 hydrate。确保不要在 props 中传递任何不应在客户端可用的敏感信息。
  • 当用户通过 next/linknext/router 访问页面时,Next.js 会向服务器发送 API 请求,服务器会运行 getServerSideProps
  • 使用 getServerSideProps 时,您无需调用 Next.js 的 API 路由 来获取数据,因为该函数在服务器端运行。相反,您可以直接在 getServerSideProps 中调用 CMS、数据库或其他第三方 API。

须知:

错误处理

如果在 getServerSideProps 中抛出错误,将会显示 pages/500.js 文件。查看 500 页面 文档了解如何创建它。在开发环境中,不会使用此文件,而是会显示开发错误覆盖层。

边缘情况

边缘运行时 (Edge Runtime)

getServerSideProps 可与 Serverless 和 Edge 运行时 一起使用,并且您可以在两者中设置 props。

但是,目前在 Edge 运行时中,您无法访问响应对象。这意味着您不能在 getServerSideProps 中执行诸如添加 cookie 等操作。要访问响应对象,您应 继续使用 Node.js 运行时,这是默认的运行时。

您可以通过修改 config 在每页基础上显式设置运行时,例如:

pages/index.js
export const config = {
  runtime: 'nodejs', // 或 "edge"
}

export const getServerSideProps = async () => {}

服务端渲染 (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 之前,我们建议先查看 getStaticPropsISR 是否更适合您的用例。

On this page