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");

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

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

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