Home

Render XML Page with Next.js

Learn how to generate an XML page with Next.js.

To render a page in Next.js as XML (or really any other non-HTML format), here’s a pattern that I’ve found works well:

const Sitemap = () => null;

export const getServerSideProps = async ({ res }) => {
// Fetch data and build page content ...
const content = "...";

res.setHeader("Content-Type", "text/xml");
res.write(content);
res.end();

return {
props: {},
};
};

export default Sitemap;

This pattern may look a little odd, so let’s break it down:

  • Nothing is rendered from the component. The page component is just an empty component that renders null.
  • getServerSideProps hijacks the Node.js response by 1) setting the appropriate content type header, and 2) returning with the content (as a string) to be rendered on the page.

Note that we still want to return the props object or Next gets mad.

Let's Connect

Keep Reading

Open External next/link Links in a New Tab

Add a component that dynamically swaps between next/link and a native anchor tag, and decides how to write the target attribute, all based on the href property.

Jun 30, 2022

Render JSON Page with Next.js

Build a JSON page component with Next.js.

Jul 26, 2022

Custom XML Sitemap from a Catch All Route in Next.js

Building an XML sitemap in Next.js is a bit of an odd process. Here’s how I’ve done it by leveraging getStaticPaths methods from page components.

Aug 02, 2022