[Next.js] getStaticPaths関数とは

スポンサーリンク

概要

[id].tsxのようなダイナミックルーティングを行うページでgetStaticProps関数を使用する場合は、getStaticPaths関数を使用して「生成されるパスのリスト」を定義する必要がある。

getStaticPaths関数はgetStaticProps関数の前にコールされ関数で、パスの組み合わせpathsとフォールバックfallbackをreturnする。

import { NextPage, GetStaticProps, GetStaticPaths } from 'next'
import {ParsedUrlQuery} from "querystring";

type PostProps = {id: string}

const Post: NextPage<PostProps> = ({id}) => {
  return (
    <>
      <p>このページはSSGです。</p>
      <p>{id}</p>
    </>
  )
}
export const getStaticPaths: GetStaticPaths = async() => {
  const paths = [
    {
      params: {
        id: '1',
      },
    },
    {
      params: {
        id: '2',
      },
    }
  ]
  return {paths, fallback: false} // posts/1, posts/2以外は404ページを表示
}
// パラメータの型を定義
interface PostParams extends ParsedUrlQuery {
  id: string
}
export const getStaticProps: GetStaticProps<PostProps, PostParams> = async (context) => {
  return {
    props: {
      id: context.params!.id
    }
  }
}
export default Post

fallback

  • false
    getStaticPaths関数で指定されたパス以外は404ページが表示される。
  • true
    getStaticPaths関数で指定したパス以外の場合もページコンポーネントが表示される。

おすすめ書籍

コメント