Automatic Site Maps in Svelte
Autogenerate a sitemap
// src/routes/sitemap.xml/+server.js
import { readdirSync, statSync } from 'fs';
import { join, relative } from 'path';
function getRoutes(dir) {
const baseDir = join(process.cwd(), 'src', 'routes');
const routes = [];
function traverse(currentDir) {
const files = readdirSync(currentDir);
files.forEach(file => {
const filePath = join(currentDir, file);
const stat = statSync(filePath);
if (stat.isDirectory()) {
traverse(filePath);
} else if (file === '+page.svelte') {
let route = '/' + relative(baseDir, currentDir)
.split('\\')
.join('/');
// Handle index routes
route = route === '/.' ? '/' : route;
routes.push(route);
}
});
}
traverse(baseDir);
return routes;
}
export async function GET() {
const routes = getRoutes('src/routes');
const body = `
<?xml version="1.0" encoding="UTF-8" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${routes.map(route => `
<url>
<loc>https://example.com${route}</loc>
</url>
`).join('')}
</urlset>
`.trim();
return new Response(body, {
headers: {
'Content-Type': 'application/xml'
}
});
}Handling Dynamic Content
Automating Updates
Last updated