1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

はじめに

Next.jsでsitemap.xmlを設定するのに苦戦したのでまとめていきます

問題

以下のライブラリを利用して設定を行いました

next-sitemap.config.js
/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: 'https://example.com',
  generateRobotsTxt: true,
  sitemapSize: 7000,
}

これでnpm run buildをしたところなぜかsitempa.xmlsitemap-0.xmlが出力されます。
また、デプロイしてGoogle Search Consoleに登録したところ以下のようなエラーが出ました

image.png

ローカルでもアクセスして確認したところlocalhost:3000/sitemap.xml404エラーとなっていました。

次に以下の記事を見つけました

ここでsitemap.xmlとsitemap-0.xmlの情報をうまいことまとめるようにスクリプトを追加しました

sitemap-replace.js
const replaceSitemap = async (fileName) => {
  const fs = require('fs/promises')
  const appRoot = require('app-root-path')
  const subDirectory = 'fugafuga' // ここディレクトリを変更する
  const filePath = `${appRoot}/public/${subDirectory}/${fileName}`

  const original = await fs.readFile(filePath, 'utf8')
  const replacedData = original.replace(
    /https\:\/\/hoge\.jp\/sitemap/g,  // ここドメインを変更する
    `https://hoge.jp/${subDirectory}/sitemap`  // ここドメインを変更する
  )

  await fs.writeFile(filePath, replacedData, 'utf8')
}

;(async () => {
  await replaceSitemap('robots.txt')
  await replaceSitemap('sitemap.xml')
})()

しかし、アクセスしても404エラーでした

解決方法

ここでひらめきました。これはAppRouteを使っているのが問題なのでは?と思い、調べたところ以下の記事で解決しました

以下のスクリプトを追加しました

app/sitemap.ts
import { MetadataRoute } from "next";

export default function sitemap(): MetadataRoute.Sitemap {
  const baseUrl = "https://himaria.jp";
  const lastModified = new Date();

  const staticPaths = [
    {
      url: `${baseUrl}/`,
      lastModified,
    },
    {
      url: `${baseUrl}/about`,
      lastModified,
    },
    {
      url: `${baseUrl}/news`,
      lastModified,
    },
    {
      url: `${baseUrl}/coffee`,
      lastModified,
    },
    {
      url: `${baseUrl}/terms`,
      lastModified,
    },
    {
      url: `${baseUrl}/contact`,
      lastModified,
    },
  ];

  return staticPaths;
}

追加したら以下のコマンドを実行します

$ npm run build
$ npm run start 

startで起動しないと本番のoutに出力したファイルを見ないので404になってしまいます。startで起動して確認しましょう

アクセスもうまくいき、Google Search Consoleの登録もうまくいきました

image.png

おわりに

SEO対策をするまではsitemapについて何も知りませんでしたが、今回調べることで深く学ぶことができました

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?