コンテンツにスキップ

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 は、ユーザー固有のデータやリクエスト時にのみ判明する情報(例: authorizationヘッダーやジオロケーション)に依存するページをレンダリングする必要がある場合に使用してください。

リクエスト時にデータを取得する必要がない場合、またはデータをキャッシュしてHTMLを事前レンダリングしたい場合は、getStaticPropsの使用をお勧めします。

動作

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

知っておくと良いこと

エラーハンドリング

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 がユースケースに適しているかどうかを確認することをお勧めします。