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?

【Next.js】next-sitemap でサイトマップを自動生成する方法

Posted at

初めまして、ただの大学院生のわだです。
インプットだけでなくアウトプットも大事だなと最近思いはじめました。
実案件で詰まったところの解決方法を記事にしていきたいと思います。

Next.js で静的サイトを作っていると、SEO 対策として sitemap.xml を作成・出力したくなることがあります。

ですが、CMS を使っていたり、大規模なサイトになってくると、自分でサイトマップを管理・生成するのはだんだん面倒になってきますよね。

そこで今回は、実際の案件で導入した方法をもとに、next-sitemap を使って ビルド時に自動でサイトマップを生成する方法 を紹介します。

🎯 この記事でわかること

•	next-sitemap の導入方法
•	サイトマップと robots.txt の自動生成
•	next export にも対応した設定方法

✅ 使用環境

•	Node.js v20.18.1
•	Next.js v15.03
•	next-sitemap v4.2.3
•	静的サイト出力(next export)

🔧 パッケージのインストール

まずは next-sitemap を開発依存として追加します。

npm install --save-dev next-sitemap

✍️ next-sitemap.config.js を作成

module.exports = {
  siteUrl: "https://example.com/", //サイトurl
  generateRobotsTxt: true, // robots.txt も自動生成する場合
  exclude: ["/404"],       // 除外したいページがあればここに記載
};

⚙️ package.json にスクリプトを追加

{
  "scripts": {
    "build": "next build",
    "postbuild": "next-sitemap"
  }
}

postbuild スクリプトは、ビルドの後に自動で next-sitemap を実行してくれます。

🚀 ビルドしてみる

npm run build

すると public/ ディレクトリに以下のファイルが生成されます。
• public/sitemap.xml
• public/robots.txt

📝 まとめ

•	next-sitemap を使うと簡単に sitemap.xml を生成できる
•	postbuild を使えばcmsなどでページが自動追加されても対応可能
•	SEO 対策におすすめ

💬 コメント歓迎!

ご質問や補足があればコメントいただけると嬉しいです!

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?