Sveltekit - Generating Sitemap

How to implement a dynamic sitemap.xml file on Sveltkit and improve your SEO.

Sveltekit - Generating Sitemap
Photo by GeoJango Maps / Unsplash

The sitemap.xml file is utilized to list and provide information about all the pages within a website. He is important for SEO, helping us on indexing our site structure, improving visibility, and much more.

Sveltekit is an awesome server-side framework (SPA, MPA, and SSG too), using Svelte and Vite to improve from build until page loads.

This trick can be used too for other frameworks SSR (Next’s, Nuxt, etc).

So, let's start!
First, we need to create a new route for the sitemap, so in your `routes` folder let's create a new folder called sitemap.xml and inside a file called  +server.ts (If you use JS just change it).
In the file let's put this code:

export async function GET({ url }: { url: URL }) {
  const posts = [
    {
      id: 713,
      slug: "post-teste1",
      title: "Janell",
      content:
        "Enim esse laborum dolore fugiat excepteur nisi enim mollit sit esse ipsum.",
    },
    {
      id: 58,
      slug: "post-teste2",
      title: "Elvia",
      content: "Est culpa dolore culpa ut tempor qui nisi nulla.",
      updated_at: "25-06-2023",
    },
    {
      id: 950,
      slug: "post-teste3",
      title: "Mendez",
      content: "Eu consequat exercitation occaecat et ut sit ea eu.",
      updated_at: "25-06-2023",
    },
    {
      id: 880,
      slug: "post-teste4",
      title: "Jenny",
      content:
        "Officia voluptate enim eiusmod magna duis exercitation magna ut labore et pariatur eiusmod quis.",
      updated_at: "25-06-2023",
    },
  ];

  let xml = '<?xml version="1.0" encoding="UTF-8"?>';
  xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

  posts.forEach((post) => {
    xml += `<url>`;
    xml += `<loc>${url.origin}/post/${post.slug}</loc>`;
    xml += `<lastmod>${post.updated_at}</lastmod>`;
    xml += `<changefreq>daily</changefreq>`;
    xml += `<priority>0.6</priority>`;
    xml += `</url>`;
  });

  xml += `</urlset>`;

  const response = new Response(xml);

  response.headers.set("content-type", "application/xml");

  return response;
}

So, what we have here is a simple API GET route for /sitemap.xml and create an XML file structure with our "posts" (mocked) and return this on response changing the content type to XML.

Read about the XML sitemap tags here.

And we got this:

Browser preview
mysitemapgenerator