Access domain name dynamically in SvelteKit Sitemap

How to access doamin dynamically in SvelteKit sitemap end point

Svelte Sitemap

We have to specify the domain in sitemap, the usual practice is to store the domain in some object/variable and export it. In SvelteKit we can do the same.

In the development mode the domain can be localhost and for production it would be a real world domain.

Can I access the domain dynamically ?

Yes. Using url parameter in the get function as follows.

export async function GET({url}) {
  ......
  ......
  }

In the XML string we can access the domain using the hostname.

 import { get } from "svelte/store";

// @ts-ignore
export async function GET({url}) {
        
  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>https://${url.hostname}</loc>
        <changefreq>daily</changefreq>
        <priority>0.7</priority>
      </url> 
    </urlset>`,
    {
      headers: {
        'Content-Type': 'application/xml'
      }
    }
  );
}
svelte
sveltekit
sitemap

Write your comment