Generate the sitemap for our nextjs mdx blog

pending description

The least resistance way I found, was creating a route:

sitemap.xml/route.ts

Yes that sitemap.xml is a directory`.

And then it is pretty straight forward.

const GET = async (request: NextRequest): Promise<NextResponse> => {
  const articles = await getArticleSlugs();
  const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <!--We manually set the root-->
    <url>
      <loc>${`${process.env.NEXT_PUBLIC_DOMAIN}`}</loc>
    </url>
    ${articles
      .map(({ slug }) => {
        return `
      <url>
        <loc>${`${process.env.NEXT_PUBLIC_DOMAIN}/article/${slug}`}</loc>
      </url>
    `;
      })
      .join('')}
  </urlset>
`;
  return new NextResponse(xmlContent, {
    headers: {
      'Content-Type': 'application/xml',
    },
  });
};

Added a link to the root page, and then to the list of articles.

Et voilà, sitemap.xml

We use cookies to improve your experience and analyze our traffic. By using our site, you consent to our use of cookies. You can manage your preferences below: