Create an xml and open it from the client-side

Today I've been wondering if it was possible to create an xml file from the client-side using JavaScript.

Let's suppose that I want to create a sitemap after a user visits ./sitemap.xml.

In that case, I would create a function such as:

javascript
if(window.location.href.endsWith('sitemap.xml')){

    const xmlStr = (
        `<?xml version="1.0" encoding="UTF-8"?>
            <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                <url><loc>https://erikmartinjordan.com</loc></url>
            </urlset>
        `
    );

    window.document.write(xmlStr);

}

If I execute it, the function will render the xml content, but it won't be formatted as an xml tree.

This is because content-type is text/html (default value if we are displaying HTML content). The problem is that there is no way of changing this attribute from the client-side.

At this point, there are 2 options:

  1. Sending an xml response from the server:
javascript
response.set('Content-Type', 'text/xml');
  1. Using blob to generate a new file:
javascript
if(window.location.href.endsWith('sitemap.xml')){

    const xmlStr = (
        `<?xml version="1.0" encoding="UTF-8"?>
            <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                <url><loc>https://erikmartinjordan.com</loc></url>
            </urlset>
        `
    );
    
    let blob = new Blob([xmlStr], {type: "text/xml"});
    let url = URL.createObjectURL(blob);
    window.open(url, "_self");
    URL.revokeObjectURL(url);
    
}

Both options aren't optimal, since I want to serve the sitemap from the client without any redirections.

The second option seems better than the first one though, but if I use it to generate an xml, Google Search Console won't recognize it and you'll get the following error:

Your Sitemap appears to be an HTML page. Please use a supported sitemap format instead.

In conclusion, the only option is to generate an xml file from the server.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.