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`パラメータは、次のキーを含むオブジェクトです。
名前 | 説明 |
---|---|
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 を導入しました。 |
役に立ちましたか?