getServerSideProps
ページから getServerSideProps
(サーバーサイドレンダリング)という関数をエクスポートすると、Next.jsはこのページを各リクエストごとに、getServerSideProps
が返すデータを使ってプリレンダリングします。頻繁に変更されるデータを取得し、最新のデータを表示するページを更新したい場合に便利です。
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetServerSideProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return repo.stargazers_count
}
export async function getServerSideProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}
export default function Page({ repo }) {
return repo.stargazers_count
}
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
オブジェクトはキーと値のペアで、各値はページコンポーネントによって受け取られます。シリアライズ可能なオブジェクトである必要があり、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 が導入されました。 |