Introduction

This is a pretty straightforward example of creating a sitemap.xml page on your SvelteKit website. In this example we'll be including URLs for the homepage, the contact page, the blog, all the blog posts, and all the tag pages.

We're going to be getting pages from a Prismic repository but the same process can be done using any API that returns pages or you could just add static pages if you don't have any dynamically created pages.

Create the sitemap

Creating the sitemap is pretty simple. In your routes directory create a sitemap.xml folder with a +server.js file inside. Then you just need to export a GET handler that returns the xml.

routes/sitemap.xml/+server.js

import createClient from '$lib/prismicio';

// set the website url to a variable we can reference in the sitemap
const website = 'https://zachpatrick.com';

export async function GET({ fetch, request }) {
  const client = createClient({ fetch, request });
  
  /**
   * Get all the blog posts created in Prismic: /blog/[uid]
   */
  const posts = await client.getByType('post');

  /** 
   * - Get all the tags created in Prismic
   */
  const allTags = await client.getTags();

  return new Response(
    `
    <?xml version="1.0" encoding="UTF-8" ?>
    <urlset
      xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xhtml="https://www.w3.org/1999/xhtml"
      xmlns:mobile="https://www.google.com/schemas/sitemap-mobile/1.0"
      xmlns:news="https://www.google.com/schemas/sitemap-news/0.9"
      xmlns:image="https://www.google.com/schemas/sitemap-image/1.1"
      xmlns:video="https://www.google.com/schemas/sitemap-video/1.1"
    >
      <url>
        <loc>${website}</loc>
      </url>
      <url>
        <loc>${website}/contact</loc>
      </url>
      <url>
        <loc>${website}/blog</loc>
      </url>
      ${posts ? posts.map((post) => `<url>
        <loc>${website}/blog/${post.uid}</loc>
      </url>`).join('') : ''}
      ${allTags ? allTags.map((tag) => {
        return `<url>
              <loc>${website}/tags/${tag}</loc>
            </url>`
      }).join('') : ''}
    </urlset>`.trim(),
    {
      headers: {
        'Content-Type': 'application/xml'
      }
    }
  );
}

Was this post helpful?