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>
  )
}
export async function getServerSideProps() {
  // 从外部 API 获取数据
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo = await res.json()
  // 通过 props 将数据传递给页面
  return { props: { repo } }
}

export default function Page({ repo }) {
  return (
    <main>
      <p>{repo.stargazers_count}</p>
    </main>
  )
}

何时使用 getServerSideProps

如果您需要渲染依赖个性化用户数据或仅在请求时才能获取的信息的页面,应使用 getServerSideProps。例如 authorization 请求头或地理位置信息。

如果不需要在请求时获取数据,或希望缓存数据和预渲染的 HTML,建议使用 getStaticProps

行为

  • getServerSideProps 在服务端运行。
  • getServerSideProps 只能从 页面 中导出。
  • getServerSideProps 返回 JSON 数据。
  • 当用户访问页面时,getServerSideProps 会在请求时获取数据,并使用该数据渲染页面的初始 HTML。
  • 传递给页面组件的 props 可以在客户端作为初始 HTML 的一部分查看。这是为了让页面能够正确进行 hydration (注水)。请确保不要在 props 中传递任何不应在客户端可用的敏感信息。
  • 当用户通过 next/linknext/router 访问页面时,Next.js 会向服务端发送 API 请求,该请求会运行 getServerSideProps
  • 使用 getServerSideProps 时无需调用 Next.js 的 API 路由 来获取数据,因为该函数在服务端运行。您可以直接在 getServerSideProps 中调用 CMS、数据库或其他第三方 API。

须知:

错误处理

如果在 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 (增量静态再生) 是否更适合您的使用场景。