作成日: 2023-4-23
更新日: 2023-9-28
※この記事ではNext.js12以前のPages RouterでのSSGの実装方法について解説しています。
スタティックサイトジェネレーションの略です。
ビルド時にデータ取得、HTMLの生成を行い、サーバにキャッシュします。
ユーザからリクエストがあった場合、キャッシュされたHTMLを返却します。
このレンダリング方法のメリットは、
が挙げられます。
デメリットとしては、
が挙げられます。
Next.jsはパフォーマンスの観点からSSGでのレンダリングを推奨しています。
まずSSGを行いたいページでgetStaticPropsをexportします。
そうすることでgetStaticPropsがビルド時に最初に動きます。
getStaticPropsは非同期関数として定義する必要があるので、asyncを定義します。
getStaticPropsの型はnextからimportできます。pages/index.tsx
import type { GetStaticProps } from 'next'
export const getStaticProps: GetStaticProps = async (context) => {
}
getStaticPropsの引数には、contextが与えられます。
contextには以下の要素が含まれています。
GetStaticPropsの型引数に最終的にページに渡したいpropsの型を渡しておくと、returnの型チェックができます。
import type { GetStaticProps } from 'next'
type SSGResponse = {
response: blogResponse
// test: stringを追加すると下の関数をビルドした時に型エラーが発生する
// returnするpropsはresponseの他にtestが必要になるため
}
export const getStaticProps: GetStaticProps<SSGResponse> = async (context) => {
const response: blogResponse = await fetcher(`${baseUrl}/api/v1/blogs`)
return {
props: {
response
}
}
}
SSGで取得したデータをレンダリングしたいページにpropsで引き渡すことができます。
import type { GetStaticProps } from 'next'
type SSGResponse = {
response: blogResponse
// test: stringを追加すると下の関数をビルドした時に型エラーが発生する
// returnするpropsはresponseの他にtestが必要になるため
}
export const getStaticProps: GetStaticProps<SSGResponse> = async (context) => {
const response: blogResponse = await fetcher(`${baseUrl}/api/v1/blogs`)
return {
props: {
response
}
}
}
const Home: NextPage<SSGResponse> = (props) => {
const { response } = props;
return (
<>
<Top articles={response} />
</>
)
}
export default Home
これでSSGに実装は完了です。
一部コンポーネントと型のインポートは省略しています。
今回は、SSGの概要と実装方法について解説しました。
次回はSSGでの動的なページ生成について解説します。