NNext.js 中文网 GitHub

getServerSideProps

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

小知识:

错误处理#

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

边缘情况#

使用服务端渲染(SSR)进行缓存#

你可以在 getServerSideProps 中使用缓存头(Cache-Control)来缓存动态响应。例如,使用 stale-while-revalidate。

jsx
// 该值在十秒内被认为是新鲜的(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 是否更适合你的用例。

Next.js 中文网