コンテンツにスキップ

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 パラメータ

The context parameter is an object containing the following keys

名前説明
paramsこのページが 動的ルート を使用している場合、params にはルートパラメータが含まれます。ページ名が [id].js の場合、params{ id: ... } のようになります。
reqHTTP IncomingMessage オブジェクトに、追加の cookies プロパティがあり、これは文字列キーと文字列値のクッキーのマッピングオブジェクトです。HTTP IncomingMessage オブジェクト
resHTTP レスポンスオブジェクト.
queryクエリ文字列を表すオブジェクト。動的ルートパラメータも含まれます。
preview(draftMode のために非推奨) preview は、ページが プレビューモード にある場合は true、そうでない場合は false です。
previewData(draftMode のために非推奨) setPreviewData によって設定された プレビュー データ。
draftModeページが ドラフトモード にある場合は draftModetrue、そうでない場合は false です。
resolvedUrlリクエスト URL を正規化したバージョン。クライアント遷移のために _next/data プレフィックスが削除され、元のクエリ値が含まれます。
localeアクティブなロケール(有効な場合)が含まれます。
localesすべてのサポートされているロケール(有効な場合)が含まれます。
defaultLocale設定されたデフォルトロケール(有効な場合)が含まれます。

getServerSideProps の返り値

getServerSideProps 関数は、次のいずれかのプロパティを持つオブジェクトを返す必要があります。

props

props オブジェクトはキーと値のペアで、各値はページコンポーネントによって受け取られます。JSON.stringify を使用してシリアル化できる、シリアル化可能なオブジェクト である必要があります。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.0localelocalesdefaultLocalenotFound オプションが追加されました。
v9.3.0getServerSideProps が導入されました。