コンテンツへスキップ

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 () => {
  // 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 はいつ使用すべきですか?

パーソナライズされたユーザーデータや、リクエスト時にのみ判明する情報 (例: `authorization` ヘッダーやジオロケーション) に基づいてページをレンダリングする必要がある場合は、getServerSideProps を使用すべきです。

リクエスト時にデータをフェッチする必要がない場合、またはデータとプリレンダリングされたHTMLをキャッシュしたい場合は、getStaticProps の使用をお勧めします。

動作

  • getServerSideProps はサーバー上で実行されます。
  • getServerSideProps は**ページ**からのみエクスポートできます。
  • getServerSideProps はJSONを返します。
  • ユーザーがページにアクセスすると、getServerSideProps がリクエスト時にデータをフェッチするために使用され、そのデータはページの初期HTMLをレンダリングするために使用されます。
  • ページコンポーネントに渡される props は、初期HTMLの一部としてクライアントで表示できます。これは、ページが正しくハイドレーションされるようにするためです。クライアントで利用可能にすべきではない機密情報を props に渡さないように注意してください。
  • ユーザーが next/link または next/router を介してページにアクセスすると、Next.js はサーバーに API リクエストを送信し、そこで getServerSideProps が実行されます。
  • getServerSideProps はサーバー上で実行されるため、データフェッチに Next.js の API ルートを呼び出す必要はありません。代わりに、getServerSideProps 内から直接 CMS、データベース、または他のサードパーティAPIを呼び出すことができます。

知っておくと良いこと

エラーハンドリング

getServerSideProps 内でエラーがスローされた場合、pages/500.js ファイルが表示されます。500ページの作成方法については、ドキュメントを参照してください。開発中は、このファイルは使用されず、代わりに開発エラーオーバーレイが表示されます。

エッジケース

サーバーサイドレンダリング (SSR) でのキャッシング

getServerSideProps 内でキャッシングヘッダー (Cache-Control) を使用して、動的なレスポンスをキャッシュできます。例えば、stale-while-revalidateを使用するなどです。

// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=10, stale-while-revalidate=59'
  )
 
  return {
    props: {},
  }
}

しかし、cache-control を使う前に、代わりに getStaticPropsISR の組み合わせがあなたのユースケースにより適しているかどうかを検討することをお勧めします。