getServerSideProps
ページから getServerSideProps
(サーバーサイドレンダリング) という関数をエクスポートすると、Next.js は getServerSideProps
によって返されたデータを使用して、リクエストごとにこのページをプリレンダリングします。これは、頻繁に変わるデータをフェッチし、ページを最新のデータに更新したい場合に役立ちます。
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 パラメータ
context
パラメータは、以下のキーを含むオブジェクトです
名前 | 説明 |
---|---|
params | このページが ダイナミックルーティング を使用している場合、params にはルーティングパラメータが含まれます。ページ名が [id].js の場合、params は { id: ... } のようになります。 |
req | HTTP の IncomingMessage オブジェクト。これに追加で cookies プロパティが含まれ、これはクッキーの文字列値をマッピングする文字列キーを持つオブジェクトです。 |
res | HTTP レスポンスオブジェクト. |
query | ダイナミックルーティングパラメータを含むクエリ文字列を表すオブジェクト。 |
preview | (draftMode により非推奨) ページが プレビューモード の場合は preview は true 、それ以外の場合は false です。 |
previewData | (draftMode により非推奨) setPreviewData によって設定された プレビュー データ。 |
draftMode | ページが ドラフトモード の場合は draftMode は true 、それ以外の場合は false です。 |
resolvedUrl | クライアント遷移のために _next/data プレフィックスを削除し、元のクエリ値を含む、正規化されたリクエスト URL のバージョン。 |
locale | アクティブなロケールが含まれます (有効な場合)。 |
locales | サポートされているすべてのロケールが含まれます (有効な場合)。 |
defaultLocale | 設定されたデフォルトロケールが含まれます (有効な場合)。 |
getServerSideProps の戻り値
getServerSideProps
関数は、**以下のいずれかの**プロパティを持つオブジェクトを返すべきです
props
props
オブジェクトはキーと値のペアであり、各値はページコンポーネントによって受け取られます。渡されたプロパティが シリアライズ可能なオブジェクト である必要があります。これにより、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.0 | App Router が簡素化されたデータフェッチで安定版になりました |
v10.0.0 | locale 、locales 、defaultLocale 、および notFound オプションが追加されました。 |
v9.3.0 | getServerSideProps が導入されました。 |
この情報は役に立ちましたか?