getServerSideProps
ページから getServerSideProps
(サーバーサイドレンダリング (Server-Side Rendering))という関数をエクスポートすると、Next.jsはこのページを各リクエストごとに getServerSideProps
が返すデータを使ってプリレンダリングします。頻繁に変更されるデータを取得し、最新のデータを表示するページを更新したい場合に便利です。
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps = (async () => {
// 外部APIからデータを取得
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo: Repo = await res.json()
// データをprops経由でページに渡す
return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}
export async function getServerSideProps() {
// 外部APIからデータを取得
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
// データをprops経由でページに渡す
return { props: { repo } }
}
export default function Page({ repo }) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}
getServerSideProps
で使用するモジュールはトップレベルスコープでインポートできます。使用したインポートはクライアント側にバンドルされません。つまり、データベースからのデータ取得を含むサーバーサイドコードを直接 getServerSideProps
に記述できます。
context パラメータ
context
パラメータは以下のキーを含むオブジェクトです:
名前 | 説明 |
---|---|
params | このページがダイナミックルートを使用している場合、params にはルートパラメータが含まれます。ページ名が [id].js の場合、params は { id: ... } のようになります。 |
req | HTTP IncomingMessage オブジェクトで、追加の cookies プロパティ(クッキーの文字列キーと値をマッピングしたオブジェクト)を含みます。 |
res | HTTP レスポンスオブジェクト。 |
query | クエリ文字列を表すオブジェクトで、ダイナミックルートパラメータを含みます。 |
preview | (draftMode に非推奨)プレビューモードの場合 true 、それ以外は false 。 |
previewData | (draftMode に非推奨)setPreviewData で設定されたプレビューデータ。 |
draftMode | ドラフトモードの場合 true 、それ以外は false 。 |
resolvedUrl | クライアント遷移用に _next/data プレフィックスを取り除き、元のクエリ値を含む正規化されたリクエスト URL 。 |
locale | 有効なロケールが含まれます(有効な場合)。 |
locales | サポートされているすべてのロケールが含まれます(有効な場合)。 |
defaultLocale | 設定されたデフォルトロケールが含まれます(有効な場合)。 |
getServerSideProps の戻り値
getServerSideProps
関数は以下のいずれかのプロパティを含むオブジェクトを返す必要があります:
props
props
オブジェクトはキーと値のペアで、各値はページコンポーネントによって受け取られます。シリアライズ可能なオブジェクトである必要があり、渡されるすべての props は JSON.stringify
でシリアライズ可能でなければなりません。
export async function getServerSideProps(context) {
return {
props: { message: `Next.js is awesome` }, // ページコンポーネントに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 }, // ページコンポーネントに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: {}, // ページコンポーネントにpropsとして渡される
}
}
バージョン履歴
バージョン | 変更点 |
---|---|
v13.4.0 | App Router が安定版になり、データ取得が簡素化されました |
v10.0.0 | locale 、locales 、defaultLocale 、notFound オプションが追加されました。 |
v9.3.0 | getServerSideProps が導入されました。 |