getStaticProps
もしあなたがgetStaticPropsという機能を export するなら(Static Site Generation からのページ)、 Next.js はこのページを build の時にgetStaticPropsから返される props を使用して事前にレンダリングします。
import type { InferGetStaticPropsType, GetStaticProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getStaticProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetStaticProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count
}
export async function getStaticProps() {
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
}
type に関係なく、任意の
propsはページ component に渡され、 初期の HTML で client 側で表示することができます。これは、ページが 適切に水和化される ためのものです。propsで client 側で利用可能であるべきではない機密情報を渡さないように注意してください。
When should I use getStaticProps?
getStaticPropsを使用すべき場合:
- ページを render するために必要なデータは、ユーザーの request より前の build 時間で利用可能です。
- データはヘッドレス CMS から提供されています
- このページは事前にレンダリングする必要があります(SEO 用)で、非常に早い反応速度が求められます -
getStaticPropsはHTMLとJSONの両方のファイルを生成し、パフォーマンスのために CDN でキャッシュすることができます。 - データは公開キャッシュ(ユーザー固有ではない)できます。この条件は、特定の状況で Middleware を使用して path を rewrite することにより回避することができます。
When does getStaticProps run
getStaticPropsは常に server 上で実行され、never 上では決して実行されません。あなたはこのツール でgetStaticProps内に書かれた code が client サイドのバンドルから削除されることを検証することができます。
getStaticPropsは常にnext buildの間に実行されますgetStaticPropsは、fallback: trueを使用しているときにバックグラウンドで実行されます。getStaticPropsは、fallback: blockingを使用して初期の render の前に呼び出されます。getStaticPropsはrevalidateを使用するときにバックグラウンドで実行されますgetStaticPropsは、revalidate()を使用するときにバックグラウンドでオンデマンドで実行されます。
Incremental Static Regenerationと組み合わせると、getStaticPropsは stale ページが再検証されている間にバックグラウンドで実行され、新鮮なページがブラウザに提供されます。
getStaticPropsは静的な HTML を生成するため、入力される request (例えば query パラメータや HTTP headers )にアクセスできません。ページの request にアクセスが必要な場合は、getStaticPropsに加えて、Middlewareを検討してみてください。
Using getStaticProps to fetch data from a CMS
次の例は、CMS からブログ投稿のリストを fetch する方法を示しています。
// posts will be populated at build time by getStaticProps()
export default function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://.../posts')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
// posts will be populated at build time by getStaticProps()
export default function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://.../posts')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
getStaticProps API referenceは、getStaticPropsで使用できるすべてのパラメータと props をカバーしています。
Write server-side code directly
getStaticPropsは server-side でのみ実行されるため、client サイドで実行されることは never ありません。それはブラウザの JS バンドルにさえ含まれないので、データベースへの直接のクエリをブラウザに送信されることなく書くことができます。
これは、getStaticProps(それ自体が外部の source からデータをフェッチします)からAPI routeをフェッチする代わりに、getStaticProps内に直接 server-side code を書くことができるということを意味します。
次の例をご覧ください。 API route は、CMS からデータを fetch するために使用されます。その API route は、次にgetStaticPropsから直接呼び出されます。これにより余分な呼び出しが発生し、パフォーマンスが低下します。代わりに、CMS からデータを取得するためのロジックはlib/ディレクトリを使用して共有できます。そしてそれはgetStaticPropsと共有することができます。
// The following function is shared
// with getStaticProps and API routes
// from a `lib/` directory
export async function loadPosts() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts/')
const data = await res.json()
return data
}
// pages/blog.js
import { loadPosts } from '../lib/load-posts'
// This function runs only on the server side
export async function getStaticProps() {
// Instead of fetching your `/api` route you can call the same
// function directly in `getStaticProps`
const posts = await loadPosts()
// Props returned will be passed to the page component
return { props: { posts } }
}
あるいは、もしあなたが APIroutes を使ってデータをフェッチしないのであれば、fetch() API は直接getStaticPropsでデータをフェッチするために使うことができます。
Client サイドのバンドルから Next.js が何を除去するかを確認するために、next-code-elimination tool を使用できます。
Statically generates both HTML and JSON
getStaticPropsが含まれるページが build 時に事前にレンダリングされると、ページの HTML ファイルに加えて、Next.js はgetStaticPropsの実行結果を保持する JSON ファイルを生成します。
この JSON ファイルは、next/linkまたはnext/routerを通じた Client サイドルーティングで使用されます。 getStaticPropsを使用して事前にレンダリングされたページに移動すると、Next.js はこの JSON ファイル(build 時に事前に計算された)をフェッチし、ページの component の props として使用します。これは、Client サイドのページ遷移ではgetStaticPropsは呼び出されないことを意味し、export された JSON のみが使用されることを意味します。
Incremental Static Generation を使用すると、getStaticPropsがバックグラウンドで実行され、クライアントサイドナビゲーションに必要な JSON を生成します。これは、同じページに対して複数のリクエストが行われる形式で表示されるかもしれませんが、これは意図的なものであり、エンドユーザーのパフォーマンスには影響を与えません。
Where can I use getStaticProps
getStaticPropsはページからのみエクスポートできます。非ページファイル、_app、_document、または_errorから export することはできません。
この制限の理由の一つは、ページがレンダリングされる前に React が必要な全てのデータを持っている必要があるからです。
また、export getStaticPropsを独立した関数として使用する必要があります - ページの component のプロパティとしてgetStaticPropsを追加すると動作しません。
Good to know:カスタム アプリを作成した場合は、リンクされたドキュメントに示されているように
pagePropsをページ component に渡すことを確認してください。そうしないと、プロップスは空になります。
Runs on every request in development
development (next dev)では、getStaticProps はすべての request ごとに呼び出されます。
Preview Mode
あなたは一時的に静的生成を回避し、Preview Modeを使用して build の時間ではなく、request 時間に render してページを表示できます。たとえば、ヘッドレス CMS を使用していて、公開前に preview して下書きを確認したい場合などです。