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

Run React Effect Hook only Once in Strict Mode

Running React in strict mode with Next.js can lead to useEffect callbacks with zero dependencies to run twice in development. Here’s a way around that.

Jun 25, 2022

Generate Dynamic JSON Pages with Next.js

Two methods for generating JSON pages with Next.js. One that updates on every request, the other on every build.

Jun 10, 2021

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