Search code examples
xmlnext.js

How to send proper xml file with Next.js new app router?


I found the doc about sending non-UI content with route.ts, but it doesn't behave like intended.

It just sends back a string, and the browser doesn't see it as an XML file. It just displays text, non-parsed in tags.

Should something else be added for it to be recognized as an xml file? How would you do it?


Solution

  • Response is setting the content type to text/plain by default; this is why the browser is displaying it that way. You could remedy that by setting the correct type, like so:

    // app/api/route.js
    
    export async function GET() {
      const xmlContent = `<?xml version="1.0" encoding="UTF-8" ?>
      <rss version="2.0">
       
      <channel>
        <title>Next.js Documentation</title>
        <link>https://nextjs.org/docs</link>
        <description>The React Framework for the Web</description>
      </channel>
       
      </rss>`;
    
      return new Response(xmlContent, { headers: { "Content-Type": "text/xml" } });
    }