DEV Community

Adam Mellen
Adam Mellen

Posted on • Originally published at mellen.io on

Generating Sitemaps for SvelteKit Apps on Cloudflare Pages

Generating Sitemaps for SvelteKit Apps on Cloudflare Pages

Sitemaps are incredibly important for letting search engines know what pages are available to index. As part of my plans to improve my site that lets you play chess against ChatGPT, I wanted to make sure that I had a sitemap in place as I started to add new pages.

With SvelteKit you can easily generate a compliant sitemap.xml file as part of your build process!

Prerequisites

  • You need some prerenderable routes. If your site is completely static, you can add export const prerender = true; to your src/routes/+layout.js file.
  • You're using the @sveltejs/adapter-cloudflare adapter for SvelteKit

As long as you have these, you can easily generate your sitemap!

Install svelte-sitemap

For sitemaps I like to use svelte-sitemap which you can install as a dev dependency:

npm i --save-dev svelte-sitemap
Enter fullscreen mode Exit fullscreen mode

Add a postbuild script

To generate your sitemap, you can do so in a postbuild script so you never need to run it manually. You can add your postbuild script in package.json like so:

{
    "name": "my-cool-project",
    "scripts": {
        "postbuild": "npx svelte-sitemap --out-dir .svelte-kit/cloudflare --domain https://example.com"
    }
}
Enter fullscreen mode Exit fullscreen mode

Update your adapter

Once you've got your postbuild script set up, all you need to do now is make a few amends to your adapter in svelte.config.js!

-import adapter from '@sveltejs/adapter-auto';
+import adapter from '@sveltejs/adapter-cloudflare';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    kit: {
- adapter: adapter()
+ adapter: adapter({ routes: { include: ['/*'], exclude: ['<all>', '/sitemap.xml'] }})
    }
};

export default config;

Enter fullscreen mode Exit fullscreen mode

That's it!

Before you push that up, I would test it by running an npm run build and confirming that the file .svelte-kit/cloudflare/sitemap.xml is there.

As a final touch, make sure you've got a robots.txt, for instance in static/robots.txt like so:

User-agent: *
Disallow:
Sitemap: https://example.com/sitemap.xml
Enter fullscreen mode Exit fullscreen mode

Top comments (0)