コンテンツへスキップ
APIリファレンス関数getServerSideProps

getServerSideProps

ページから getServerSideProps (サーバーサイドレンダリング) という関数をエクスポートすると、Next.js は getServerSideProps によって返されたデータを使用して、リクエストごとにこのページをプリレンダリングします。これは、頻繁に変わるデータをフェッチし、ページを最新のデータに更新したい場合に役立ちます。

pages/index.tsx
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
 
type Repo = {
  name: string
  stargazers_count: number
}
 
export const getServerSideProps = (async () => {
  // Fetch data from external API
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo: Repo = await res.json()
  // Pass data to the page via 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 プロパティが含まれ、これはクッキーの文字列値をマッピングする文字列キーを持つオブジェクトです。
resHTTP レスポンスオブジェクト.
queryダイナミックルーティングパラメータを含むクエリ文字列を表すオブジェクト。
preview(draftMode により非推奨) ページが プレビューモード の場合は previewtrue、それ以外の場合は false です。
previewData(draftMode により非推奨) setPreviewData によって設定された プレビュー データ。
draftModeページが ドラフトモード の場合は draftModetrue、それ以外の場合は false です。
resolvedUrlクライアント遷移のために _next/data プレフィックスを削除し、元のクエリ値を含む、正規化されたリクエスト URL のバージョン。
localeアクティブなロケールが含まれます (有効な場合)。
localesサポートされているすべてのロケールが含まれます (有効な場合)。
defaultLocale設定されたデフォルトロケールが含まれます (有効な場合)。

getServerSideProps の戻り値

getServerSideProps 関数は、**以下のいずれかの**プロパティを持つオブジェクトを返すべきです

props

props オブジェクトはキーと値のペアであり、各値はページコンポーネントによって受け取られます。渡されたプロパティが シリアライズ可能なオブジェクト である必要があります。これにより、JSON.stringify でシリアライズできます。

export async function getServerSideProps(context) {
  return {
    props: { message: `Next.js is awesome` }, // will be passed to the page component as 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 }, // will be passed to the page component as 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: {}, // will be passed to the page component as props
  }
}

バージョン履歴

バージョン変更点
v13.4.0App Router が簡素化されたデータフェッチで安定版になりました
v10.0.0localelocalesdefaultLocale、および notFound オプションが追加されました。
v9.3.0getServerSideProps が導入されました。