next.jsで作ったwebサイトをさくっと検索エンジンにインデックスさせる手順。sitemap.xmlというファイルにwebサイトのサイトマップを記述し、Google Serch Consoleから登録する必要がある。
sitemap.xmlを生成するAPI
sitemapのフォーマットについてはドキュメントを参照
sitemap.xmlを生成
// Example
type post = {
date: number
slug: string
}
const generateSitemap = (posts: post[], location: string): string => {
let xml: string = "";
posts.map(post => {
const postDate: string = getDateStr(post.date);
const projectURL = location + post.slug;
xml += `<url>
<loc>${projectURL}</loc>
<lastmod>${postDate}</lastmod>
<priority>0.50</priority>
</url>`;
});
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${xml}
</urlset>`;
};
Next.jsのAPIを使いたい場合
{project}/pages/api/sitemap.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default async (req: NextApiRequest, res: NextApiResponse) => {
// Replace your code
const location = "https://{domain}/"
const posts = await getPosts()
const sitemap: string = generateSitemap(posts, location)
res.setHeader('content-type', 'application/xml');
res.write(sitemap);
res.end();
}
http://{domain}/api/sitemap
にGETリクエストでsitemapを生成して返すapiが出来る。
Next.jsのGetServerSidePropsを使いたい場合
{project}/pages/{dir}/sitemap.ts
import { GetServerSideProps } from 'next'
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
// Replace your code
const location = "https://{domin}/{dir}/"
const posts = await getPosts()
const sitemap: string = generateSitemap(posts, location)
res.setHeader('content-type', 'application/xml');
res.write(sitemap);
res.end();
return { props: {} }
}
const sitemap = () => null
export default sitemap
http://{domain}/blog/sitemap
にGETリクエストでsitemapを生成して返すapiが出来る。
Google Serch Consoleからsitemapを追加する
Google Serch Consoleの管理画面から追加する。sitemap.xmlが正しければ、URLを検出してインデックスされるはず。
おまけ robots.txtを書いて配置する
robots.txtは、Googlebotなどのクローラーに対して、クロールの制御をするためのファイル。sitemap.xmlのパスを記述することで、適切にクロールしてもらえる。
記述例
Sitemap: http://{domain}/api/sitemap
User-agent: *
Allow: /*
Disallow: /api/*
next.jsではこのファイルをProject/public/robots.txt
に配置する。
https://{your_domain}/robots.txt
で取得できればok