WebLog

app routerでsitemapを作る

2023/06/12 17:00

はじめに

以下の記事を参考にすればいいようです

Metadata Files: sitemap.xml | Next.js
Metadata Files: sitemap.xml | Next.js

Metadata Files: sitemap.xml | Next.js

API Reference for the sitemap.xml file.

静的な場合の例

app/sitemap.ts
1import { MetadataRoute } from "next";
2
3export default function sitemap(): MetadataRoute.Sitemap {
4 const baseUrl = process.env.NEXT_PUBLIC_URL ?? '';
5 const lastModified = new Date();
6
7 const staticPaths = [
8 {
9 url: `${baseUrl}`,
10 lastModified,
11 },
12 {
13 url: `${baseUrl}/about`,
14 lastModified,
15 },
16 ];
17
18 return staticPaths;
19}
20

動的な場合の例

app/sitemap.ts
1import { MetadataRoute } from "next";
2import { getArticles } from "../libs/article";
3
4export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
5 const baseUrl = process.env.NEXT_PUBLIC_URL ?? '';
6 const lastModified = new Date();
7
8 const staticPaths = [
9 {
10 url: `${baseUrl}`,
11 lastModified,
12 },
13 {
14 url: `${baseUrl}/about`,
15 lastModified,
16 },
17 ];
18
19 const articles = await getArticles();
20 const dynamicPaths = articles.map((article) => {
21 return {
22 url: `${baseUrl}/articles/${article.slug}`,
23 lastModified,
24 };
25 });
26
27 return [...staticPaths, ...dynamicPaths];
28}

テスト

以下のようなコマンドを実行し,http://localhost:3000/sitemap.xml にアクセスなどすれば OK です

1npm run build # next build
2npm start # npx serve@latest out

最新の投稿