Member-only story
Automatically generate sitemap.xml in SvelteKit

For SEO a sitemap.xml is crucial, however manually creating one only once is already a very annoying task, which is even worst if your website get more and more pages often.
Required Packages
For this to work we will need to install some npm packages first:
npm install directory-tree
npm install typescript
npm install tsx
Sitemap Generator Script
In your project root, create a directory scripts with the file generate-sitemap.ts:
import dirTree from 'directory-tree';
import * as fs from "fs";
let baseRoute = "/";
let routes: string[] = [baseRoute]
let date = new Date().toISOString().split('T')[0]
function getSitemapXML(domain: string, routes: string[]) {
let sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
sitemap += "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"
routes.forEach(route => {
sitemap += getSitemapUrl(domain + route)
})
sitemap += "\n</urlset>"
return sitemap;
}
function getSitemapUrl(location: string) {
let url =
"<url>\n" +
`<loc>${location}</loc>\n` +
`<lastmod>${date}</lastmod>\n` +
"</url>";
return url
}
function getEndpoints(tree: dirTree.DirectoryTree, route: string) {
tree.children!.forEach(child => {
if (child.children != undefined && child.children.length != 0) {
let childRoute = route + child.name;
if (child.children.some(e => e.name === '+page.svelte')) {
routes.push(childRoute)
}
getEndpoints(child, childRoute + "/");
}
})
}
const tree = dirTree("./src/routes")
getEndpoints(tree, baseRoute);
// YOUR_DOMAIN should be like https://example.com
const sitemap = getSitemapXML("YOUR_DOMAIN", routes)
// If you use the script in postbuild mode use
// For vercel deployment use:
//fs.writeFileSync('.vercel/output/static/sitemap.xml', sitemap);
fs.writeFileSync('.svelte-kit/output/client/sitemap.xml', sitemap);
// If you use the script in prebuild mode use
//fs.writeFileSync('static/sitemap.xml', sitemap);
Automatically create sitemap.xml after build
In your package.json add:
"scripts": {
...
"postbuild": "npx tsx ./scripts/generate-sitemap.ts"
}
or
"scripts": {
...
"prebuild": "npx tsx ./scripts/generate-sitemap.ts"
}
That’s it! Leave a like if you find it useful!
Don’t forget to visit my website https://www.alexschnabl.com/ for more content!