Skip to content

Instantly share code, notes, and snippets.

@shinokada
Created May 22, 2024 05:10
Show Gist options
  • Save shinokada/adaf50e55f960bbd4c086284354cf83f to your computer and use it in GitHub Desktop.
Save shinokada/adaf50e55f960bbd4c086284354cf83f to your computer and use it in GitHub Desktop.
SvelteKit simple sitemap component
// src/routes/sitemap.xml/+server.ts
import { generateSitemap } from '$lib'
/** @type {import('./$types').RequestHandler} */
interface Page {
loc: string;
changefreq?: string;
priority?: string;
lastmod?: string;
}
const site = 'https://svelte-5-ui-lib.codewithshin.com';
const pages: Page[] = [
{
loc: '',
changefreq: 'weekly',
priority: '0.5',
lastmod: '2024-05-20'
},
{
loc: 'components/alert',
changefreq: 'weekly',
priority: '0.5',
},
{
loc: 'components/avatar',
changefreq: 'weekly',
priority: '0.5',
},
{
loc: 'typography/list',
changefreq: 'weekly',
priority: '0.5',
},
{
loc: 'typography/paragraph',
changefreq: 'weekly',
priority: '0.5',
}
];
export async function GET({ url }) {
const body = generateSitemap(site, pages);
const response = new Response(body);
response.headers.set('Cache-Control', 'max-age=0, s-maxage=3600');
response.headers.set('Content-Type', 'application/xml');
return response;
}
// Simple sveltekit sitemap codes
// src/lib/index.ts
interface Page {
loc: string;
changefreq?: string;
priority?: string;
lastmod?: string;
}
export const generateSitemap = (site: string, pages: Page[]) => {
// Existing sitemap logic here
return `<?xml version="1.0" encoding="UTF-8" ?>
<urlset
xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:news="https://www.google.com/schemas/sitemap-news/0.9"
xmlns:xhtml="https://www.w3.org/1999/xhtml"
xmlns:mobile="https://www.google.com/schemas/sitemap-mobile/1.0"
xmlns:image="https://www.google.com/schemas/sitemap-image/1.1"
xmlns:video="https://www.google.com/schemas/sitemap-video/1.1"
>
${pages
.map(
({ loc, changefreq, priority, lastmod }) => `
<url>
<loc>${site}/${loc}</loc>
${changefreq ? `<changefreq>${changefreq}</changefreq>` : ''}
${priority ? `<priority>${priority}</priority>` : ''}
${lastmod ? `<lastmod>${lastmod}</lastmod>` : ''}
</url>
`
)
.join('')}
</urlset>`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment