typescriptintermediate
Dynamic Sitemap Generation
Generate dynamic XML sitemaps from data sources with priority, changefreq, and sitemap index support.
typescriptPress ⌘/Ctrl + Shift + C to copy
// app/sitemap.ts
import { MetadataRoute } from 'next';
const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'https://example.com';
// Simulated data fetchers
async function getAllCategories() {
return [
{ slug: 'react', updatedAt: '2024-01-15' },
{ slug: 'nodejs', updatedAt: '2024-01-14' },
{ slug: 'python', updatedAt: '2024-01-13' },
];
}
async function getAllSnippets() {
return [
{ category: 'react', slug: 'use-fetch-hook', updatedAt: '2024-01-15' },
{ category: 'react', slug: 'error-boundary', updatedAt: '2024-01-14' },
{ category: 'nodejs', slug: 'jwt-verify', updatedAt: '2024-01-13' },
];
}
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const [categories, snippets] = await Promise.all([
getAllCategories(),
getAllSnippets(),
]);
// Static pages
const staticPages: MetadataRoute.Sitemap = [
{
url: BASE_URL,
lastModified: new Date(),
changeFrequency: 'daily',
priority: 1.0,
},
{
url: `${BASE_URL}/search`,
lastModified: new Date(),
changeFrequency: 'weekly',
priority: 0.5,
},
];
// Category pages
const categoryPages: MetadataRoute.Sitemap = categories.map((cat) => ({
url: `${BASE_URL}/${cat.slug}`,
lastModified: new Date(cat.updatedAt),
changeFrequency: 'weekly' as const,
priority: 0.8,
}));
// Snippet pages (highest priority — money pages)
const snippetPages: MetadataRoute.Sitemap = snippets.map((s) => ({
url: `${BASE_URL}/${s.category}/${s.slug}`,
lastModified: new Date(s.updatedAt),
changeFrequency: 'monthly' as const,
priority: 0.9,
}));
return [...staticPages, ...categoryPages, ...snippetPages];
}
// app/robots.ts
// import { MetadataRoute } from 'next';
// export default function robots(): MetadataRoute.Robots {
// return {
// rules: { userAgent: '*', allow: '/', disallow: '/api/' },
// sitemap: `${BASE_URL}/sitemap.xml`,
// };
// }Use Cases
- Automated sitemap generation
- SEO crawl optimization
- Search engine indexing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Dynamic Sitemap Generation
Generate a comprehensive sitemap.xml from dynamic routes and database content.
Best for: SEO optimization
#nextjs#sitemap
typescriptadvanced
Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.
Best for: Social media sharing
#og-image#seo
typescriptbeginner
Reusable Metadata Factory
Factory function to generate consistent SEO metadata across all pages with Open Graph and canonical URLs.
Best for: Consistent page SEO
#seo#metadata
typescriptadvanced
Next.js Dynamic OG Image Generation
Generate dynamic Open Graph images at build time using next/og for social media sharing.
Best for: Dynamic social media preview images
#nextjs#og-image