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

Overriding Next.js Link and Image Components

Next.js ships with these two incredibly useful utility components. You can further abstract these to clean up your code.

Feb 09, 2023

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

Resetting State on Next.js Route Change

Component state doesn't change when navigating between dynamic routes in Next.js that use the same component. useEffect can help.

May 21, 2022