danielkhoo.io

twitter

github

Setup Sitemap for Markdown NextJS Sites

Setting up dynamic sitemap generation for Markdown/MDX NextJS static sites is pretty simple assuming you already have some sort of setup for getting all the pages for your homepage. You'll need a handler /pages/api/sitemap.js file that returns the sitemap xml as a string.


export default function handler(req, res) {
  // getPosts is a fn that returns all the posts, you should already have this for a markdown/mdx site
  const posts = getPosts();

  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/xml');
  // Instructing the Vercel edge to cache the file
  res.setHeader('Cache-control', 'stale-while-revalidate, s-maxage=3600');

  // generate sitemap here
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
        <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        ${posts
          .map(
            ({ slug, data }) => `
            <url>
                <loc>${`https://yoursitename.com/${slug}`}</loc>
                <lastmod>${new Date(data.date).toISOString()}</lastmod>
            </url>`
          )
          .join('')}
        </urlset>`;
  res.end(xml);
}

Then add a rewrite to your next.config.js file to point /sitemap.xml to the new api endpoint.


export default {
  // ...Existing config
  async rewrites() {
    return [
      {
        source: '/sitemap.xml',
        destination: '/api/sitemap',
      },
    ]
  },
};

And that's it, you're good to go!