getServerSideProps

当从页面导出一个名为 getServerSideProps(服务端渲染 (SSR))的函数时,Next.js 会在每次请求时使用该函数返回的数据预渲染此页面。如果您需要获取频繁变化的数据,并希望页面展示最新数据,这将非常有用。

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 中编写 服务端代码,包括从数据库获取数据。

Context 参数

context 参数是一个包含以下键的对象:

名称描述
params如果页面使用了 动态路由params 包含路由参数。如果页面名称为 [id].js,则 params 会形如 { id: ... }
reqHTTP IncomingMessage 对象,附带一个 cookies 属性,该属性是一个键值对对象,表示 cookie 内容。
resHTTP 响应对象
query表示查询字符串的对象,包含动态路由参数。
preview(已弃用,改用 draftMode)如果页面处于 预览模式 (Preview Mode),则 previewtrue,否则为 false
previewData(已弃用,改用 draftMode)由 setPreviewData 设置的 预览数据
draftMode如果页面处于 草稿模式 (Draft Mode),则 draftModetrue,否则为 false
resolvedUrl规范化后的请求 URL,移除了客户端跳转的 _next/data 前缀,并包含原始查询值。
locale包含当前活动的区域设置(如果启用)。
locales包含所有支持的区域设置(如果启用)。
defaultLocale包含配置的默认区域设置(如果启用)。

getServerSideProps 返回值

getServerSideProps 函数应返回一个包含 以下任一属性 的对象:

props

props 对象是一个键值对,每个值都会被页面组件接收。它应该是一个 可序列化对象,以便任何传递的 props 都可以通过 JSON.stringify 序列化。

export async function getServerSideProps(context) {
  return {
    props: { message: `Next.js is awesome` }, // 将作为 props 传递给页面组件
  }
}

notFound

notFound 布尔值允许页面返回 404 状态和 404 页面。即使之前成功生成了页面,notFound: true 也会使页面返回 404。这适用于诸如用户生成内容被作者删除等情况。

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }

  return {
    props: { data }, // 将作为 props 传递给页面组件
  }
}

redirect

redirect 对象允许重定向到内部或外部资源。其格式应为 { destination: string, permanent: boolean }。在极少数情况下,您可能需要为旧版 HTTP 客户端指定自定义状态码以实现正确重定向。此时可以使用 statusCode 属性代替 permanent 属性,但不能同时使用两者。

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  if (!data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }

  return {
    props: {}, // 将作为 props 传递给页面组件
  }
}

版本历史

版本变更
v13.4.0应用路由 (App Router) 现已稳定,数据获取更简化
v10.0.0新增 localelocalesdefaultLocalenotFound 选项。
v9.3.0引入 getServerSideProps

On this page