0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

generateStaticParamsを使って静的サイトを作成[Next.js/AppRouter]

Posted at

今回、個人ブログ用に作成した静的サイトで用いた
ビルド時にデータ取得を行い。静的なhtmlを生成したときの記述をメモしておきます。

静的エクスポートを有効にする

next.config.js に 下記の記述を追加。

const nextConfig = {
  output: "export",
  trailingSlash: true,
};
  • output: "export"
    静的なHTMLファイルを生成して出力するモードになる。

  • trailingSlash: true
    生成されるURLの末尾に、スラッシュ(/)を追加するかを指定。
    trueに設定すると、URLの末尾にスラッシュが自動的に追加される。
    例えば、/about のようなURLは、/about/ として扱われる。

一覧ページの作成

今回は簡単に、blog の一覧ページと詳細ページだけのシンプルな構成でやっていきます。
エンドポイントは、JSONPlaceholderからダミーデータを取得してきます。

src/app/blog/page.tsx

import Link from "next/link";

export default async function SG() {
  const ENDPOINT = "https://jsonplaceholder.typicode.com/posts";

  // データフェッチ
  const articles = await fetch(ENDPOINT, {
    cache: "force-cache", // キャッシュを有効に
    next: { revalidate: 10 }, // 10秒でリフレッシュ
  }).then((res) => res.json());

  return (
    <div>
      {articles.map((article) => (
        <div key={article.id}>
          <p>{article.title}</p>
          <Link href={`${article.id}`}>詳しくみる</Link>
        </div>
      ))}
    </div>
  );
}

(本当はコンポーネントに分割した方が良いのですが、メモ用なので省略!)

詳細ページの作成

  • ダイナミックルーティングで記事を取得
  • generateStaticParamsで静的生成

src/app/blog/[id]/page.tsx

const ENDPOINT = "https://jsonplaceholder.typicode.com/posts";

export default async function DetailPage({ params }) {
  // データフェッチ
  const article = await fetch(`${ENDPOINT}/${params.id}`, {
    cache: "force-cache", // キャッシュを有効に
  }).then((res) => res.json());

  return (
    <div>
      <h1>タイトル:{article.title}</h1>
      <h1>本文:{article.body}</h1>
    </div>
  );
}

// 静的生成
export async function generateStaticParams() {
  const articles = await fetch(ENDPOINT, {
    cache: "force-cache",
  }).then((res) => res.json());

  const staticPaths = articles.map((article) => {
    return {
      id: article.id.toString(), // 文字列に変換
    };
  });

  return staticPaths;
}

DetailPage コンポーネント

  • paramsオブジェクトからで記事IDを取得し、データフェッチ。
  • タイトルと本文を表示するコンポーネントを作成。

generateStaticParams 関数

  • ビルド時に指定したパスを元に静的ページを生成してくれる関数。
  • パスは、記事を全件データフェッチし、記事IDのみのオブジェクトを作成し、静的パスとして返す。
    ※ id は文字列でないとエラーになるので注意!

公式:https://nextjs.org/docs/app/api-reference/functions/generate-static-params


今回メモ程度に書いたので型を書いていないが、
TypeScriptで書く場合は、ちゃんと書かないとビルドエラーになるので注意。

簡単に高速なサイトを作れるので便利!
pageRouterの時より記述がシンプルになったので、理解しやすかったです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?