getServerSideProps

ページから getServerSideProps(サーバーサイドレンダリング (Server-Side Rendering))という関数をエクスポートすると、Next.jsはこのページを各リクエストごとに getServerSideProps が返すデータを使ってプリレンダリングします。頻繁に変更されるデータを取得し、最新のデータを表示するページを更新したい場合に便利です。

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 に記述できます。

context パラメータ

context パラメータは以下のキーを含むオブジェクトです:

名前説明
paramsこのページがダイナミックルートを使用している場合、params にはルートパラメータが含まれます。ページ名が [id].js の場合、params{ id: ... } のようになります。
reqHTTP IncomingMessage オブジェクトで、追加の cookies プロパティ(クッキーの文字列キーと値をマッピングしたオブジェクト)を含みます。
resHTTP レスポンスオブジェクト
queryクエリ文字列を表すオブジェクトで、ダイナミックルートパラメータを含みます。
previewdraftMode に非推奨)プレビューモードの場合 true、それ以外は false
previewDatadraftMode に非推奨)setPreviewData で設定されたプレビューデータ。
draftModeドラフトモードの場合 true、それ以外は false
resolvedUrlクライアント遷移用に _next/data プレフィックスを取り除き、元のクエリ値を含む正規化されたリクエスト URL
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 クライアントが適切にリダイレクトするためにカスタムステータスコードを割り当てる必要がある場合があります。そのような場合、permanent プロパティの代わりに statusCode プロパティを使用できますが、両方を同時に使用することはできません。

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.0App Router が安定版になり、データ取得が簡素化されました
v10.0.0localelocalesdefaultLocalenotFound オプションが追加されました。
v9.3.0getServerSideProps が導入されました。