Skip to content

Commit 859b4d4

Browse files
jaysin586claude
andcommitted
feat(docs): add dynamic sitemap.xml route
Generates sitemap from page routes with lastmod from manifest, priority by section, and monthly changefreq. Fixes 404 referenced by robots.txt. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent dca416e commit 859b4d4

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { env } from '$env/dynamic/public'
2+
import manifestData from '$lib/sitemap-manifest.json'
3+
import type { RequestHandler } from '@sveltejs/kit'
4+
5+
const manifest: Record<string, string> = manifestData
6+
7+
const pageFiles = Object.keys(
8+
import.meta.glob('/src/routes/**/+page.{svelte,svx,md}', { eager: false })
9+
)
10+
11+
function toPath(file: string): string {
12+
const p = file.replace('/src/routes', '').replace(/\/\+page\.(svelte|svx|md)$/i, '')
13+
return p === '' ? '/' : p
14+
}
15+
16+
function getPriority(path: string): string {
17+
if (path === '/') return '1.0'
18+
if (path === '/docs/getting-started' || path.startsWith('/docs/api/')) return '0.9'
19+
if (path.startsWith('/docs/guides/')) return '0.8'
20+
if (path.startsWith('/examples')) return '0.7'
21+
return '0.5'
22+
}
23+
24+
function getChangefreq(path: string): string {
25+
if (path === '/') return 'weekly'
26+
return 'monthly'
27+
}
28+
29+
export const GET: RequestHandler = async ({ url }) => {
30+
const base = (env.PUBLIC_SITE_URL || `${url.origin}`).replace(/\/$/, '')
31+
32+
const routes = [...new Set(pageFiles.map(toPath))]
33+
.filter((p) => !/\/_(?:.*)|\/(?:\+|__)/.test(p))
34+
.sort()
35+
36+
const today = new Date().toISOString().slice(0, 10)
37+
const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${routes
38+
.map(
39+
(p) =>
40+
` <url>\n <loc>${base}${p}</loc>\n <lastmod>${manifest[p] || today}</lastmod>\n <changefreq>${getChangefreq(p)}</changefreq>\n <priority>${getPriority(p)}</priority>\n </url>`
41+
)
42+
.join('\n')}\n</urlset>`
43+
44+
return new Response(xml, {
45+
headers: {
46+
'Content-Type': 'application/xml',
47+
'Cache-Control': 'max-age=0, s-maxage=3600'
48+
}
49+
})
50+
}

0 commit comments

Comments
 (0)