Next.jsプロジェクトにnext-sitemapを導入する

Next.jsプロジェクトにnext-sitemapを導入し、特定のページを除外(exclude)し、追加のパス(additionalPaths)を設定する方法を説明します。これにより、サイトマップに含めるページや除外するページを柔軟に管理できます

Next.jsプロジェクトにnext-sitemapを導入し、特定のページを除外(exclude)し、追加のパス(additionalPaths)を設定する方法を説明します。これにより、サイトマップに含めるページや除外するページを柔軟に管理できます。

#1. Next.js プロジェクトのセットアップ

Node.jsとnpmがインストールされている前提で、新しいNext.jsプロジェクトを作成します。

npx create-next-app@latest my-nextjs-app --typescript cd my-nextjs-app

#2. next-sitemap パッケージのインストール

next-sitemap パッケージを使用してサイトマップを自動生成します。以下のコマンドを使用してインストールします。

npm install next-sitemap # または yarn add next-sitemap

#3. next-sitemap.config.js 設定ファイルの作成

プロジェクトのルートディレクトリに next-sitemap.config.js ファイルを作成し、サイトマップの設定を行います。

touch next-sitemap.config.js

next-sitemap.config.js ファイルに以下のコードを追加します。

// next-sitemap.config.js /** @type {import('next-sitemap').IConfig} */ module.exports = { siteUrl: 'https://www.yoursite.com', // ここにあなたのサイトのURLを入れてください generateRobotsTxt: true, // robots.txtを生成するかどうか exclude: ['/admin/*', '/login'], // 除外するパス additionalPaths: async (config) => [ await config.transform(config, '/additional-path-1'), await config.transform(config, '/additional-path-2'), ], robotsTxtOptions: { policies: [ { userAgent: '*', allow: '/' }, { userAgent: '*', disallow: '/admin' }, ], }, };

設定オプションの詳細

  • siteUrl サイトの基本URLです。ここにはあなたのサイトのURLを入力します。
  • generateRobotsTxt trueに設定すると、robots.txtファイルが生成されます。
  • exclude サイトマップから除外するパスを配列で指定します。ワイルドカード()を使用して、特定のパターンに一致するパスを除外できます。
  • additionalPaths 追加のパスを設定するための非同期関数です。この関数は、サイトマップに含めたい追加のパスを返します。
  • robotsTxtOptions robots.txtファイルの設定です。ここでクロールポリシーを指定します。

#4. next.config.js ファイルの設定

next-sitemap コマンドを実行できるようにするため、next.config.js ファイルを編集します。

// next.config.js module.exports = { reactStrictMode: true, // その他の設定 }

#5. スクリプトの追加

package.json ファイルにスクリプトを追加し、サイトマップを生成するコマンドを設定します。

{ "scripts": { "build": "next build", "start": "next start", "dev": "next dev", "export": "next export", "postbuild": "next-sitemap" } }

この設定により、next build が実行された後に next-sitemap コマンドが実行され、サイトマップが生成されます。

#ステップ 6: サイトマップの生成

以下のコマンドを実行して、サイトマップを生成します。

npm run build

これにより、public ディレクトリに sitemap.xmlrobots.txt が生成されます。

localで生成したsitemap.xmlrobots.txt は本番時には不要なため、gitの管理対象外にします。.gitignore に以下を記述する。

#next-sitemap /public/robots.txt /public/sitemap*.xml

#8. 確認

ブラウザで http://localhost:3000/sitemap.xml にアクセスして、サイトマップが正しく生成されていることを確認します。また、http://localhost:3000/robots.txt にアクセスして、robots.txt ファイルも確認します。

#まとめ

これで、Next.jsプロジェクトにnext-sitemapを導入し、特定のページを除外したり、追加のパスを設定したりする方法がわかりました。サイトマップを導入することで、検索エンジンがサイトの構造を理解しやすくなり、SEOの向上に役立ちます。

#参考

タグ一覧