コンテンツにスキップ

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 はいつ使うべきですか?

パーソナライズされたユーザーデータ、またはリクエスト時にのみ認識できる情報 (例: 認証ヘッダーやジオロケーション) に基づいてページをレンダリングする必要がある場合に、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を使用する前に、ISRを使用したgetStaticPropsがユースケースにより適しているかどうかを確認することをお勧めします。