Ads by ProfitSence
Close

Create Sitemap with Sanity CMS

Last Updated on Wednesday 5th Oct 2022
			
					import {
    client
} from "$lib/client";

const fs = require('fs');

const url = "https://www.example.com"; // Your Domain Here

const routePages = [""];

			
	
  • In this Example, We use Sapper/SvelteKit.
  • It is based on route based File Managing System
  • Sometimes, We have Contact Page, About Page. So We use the fs package
			
					fs.readdirSync("./src/routes").forEach(file => {
  file = file.split('.')[0];
  if (file.charAt(0) !== '_' && file !== "sitemap" && file !== "index") {
    routePages.push(file);
  }
});

			
	

Heres the Sitemap renderer

			
					const render = (routePages, posts) => `<?xml version="1.0" encoding="UTF-8" ?>
<urlset 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  ${routePages
    .map(
      page => `
    <url>
      <loc>${url}/${page}</loc>
      <priority>0.85</priority>
    </url>`)
    .join("\n")}
  ${posts
    .map(
      post => `
    <url>
      <loc>${url}/blog/${post.slug}</loc>
      <priority>0.85</priority>
    </url>`)
    .join("\n")}
</urlset>`;

export function get(req, res, next) {
    res.setHeader("Cache-Control", `max-age=0, s-max-age=${600}`); // 10 minutes
    res.setHeader("Content-Type", "application/rss+xml");

    client.fetch(`{
        "posts": *[_type=="posts" ]|order(sticky desc, publishedAt desc){"slug":slug.current},
    }`, {// In case if you have variables for groq query Add Here}
    ).then((result) => {
        const sitemap = render(routePages, result.posts);
        res.end(sitemap);
    })
}