Files
blog-nextjs/app/sitemap.ts
gbanyan b005f02b7b fix: use getTagSlug() for tag links to prevent empty tag pages
Tags containing both spaces and dashes (e.g. "Writings - 創作") produced
mismatched slugs: inline generation created "writings---創作" while
getTagSlug() collapsed dashes to "writings-創作", causing tag pages to
show no articles.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 20:42:45 +08:00

70 lines
1.8 KiB
TypeScript

import { MetadataRoute } from 'next';
import { allPosts, allPages } from 'contentlayer2/generated';
import { getTagSlug } from '@/lib/posts';
export default function sitemap(): MetadataRoute.Sitemap {
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
// Homepage
const homepage = {
url: siteUrl,
lastModified: new Date(),
changeFrequency: 'daily' as const,
priority: 1,
};
// Blog listing page
const blogPage = {
url: `${siteUrl}/blog`,
lastModified: new Date(),
changeFrequency: 'daily' as const,
priority: 0.9,
};
// Tags page
const tagsPage = {
url: `${siteUrl}/tags`,
lastModified: new Date(),
changeFrequency: 'weekly' as const,
priority: 0.7,
};
// All blog posts
const posts = allPosts
.filter((post) => post.status === 'published')
.map((post) => ({
url: `${siteUrl}${post.url}`,
lastModified: new Date(post.updated_at || post.published_at || post.created_at || Date.now()),
changeFrequency: 'weekly' as const,
priority: 0.8,
}));
// All pages
const pages = allPages
.filter((page) => page.status === 'published')
.map((page) => ({
url: `${siteUrl}${page.url}`,
lastModified: new Date(page.updated_at || page.published_at || page.created_at || Date.now()),
changeFrequency: 'monthly' as const,
priority: 0.6,
}));
// All unique tags
const allTags = Array.from(
new Set(
allPosts
.filter((post) => post.status === 'published' && post.tags)
.flatMap((post) => post.tags || [])
)
);
const tagPages = allTags.map((tag) => ({
url: `${siteUrl}/tags/${encodeURIComponent(getTagSlug(tag))}`,
lastModified: new Date(),
changeFrequency: 'weekly' as const,
priority: 0.5,
}));
return [homepage, blogPage, tagsPage, ...posts, ...pages, ...tagPages];
}