Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
NextJS Sitemap example using Nextjs SSR.
import React from "react";
import axios from "axios";
const sitemapXml = data => {
let latestPost = 0;
let projectsXML = ""; => {
const postDate = Date.parse(post.modified);
if (!latestPost || postDate > latestPost) {
latestPost = postDate;
const projectURL = `${post.acf.slug}/`;
projectsXML += `
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="">
class Sitemap extends React.Component {
static async getInitialProps({ res }) {
const data = await axios
.then(response =>;
res.setHeader("Content-Type", "text/xml");
export default Sitemap;

This comment has been minimized.

Copy link

nawazsk commented Apr 3, 2020

Hi @emilpriver, I have used your code with few modifications. I need to create sitemap for md files from '/posts/*.md'. I have my function to get the paths and data with async-await and promises so i didn't use axios. I'm able to see sitemap.xml in my local. But when I deploy to netlify, it throws prerender-error on /sitemap.xml. do you have any solution for this ?


This comment has been minimized.

Copy link

EzeRangel commented Jul 14, 2020

@nawazsk Perhaps you can read the slugs in your /posts directory and use them to build the dynamic pages. Something like:

const postsDirectory = join(process.cwd(), '/posts');

function getPostSlugs() {
  return fs.readdirSync(postsDirectory);

function getAllSlugs() {
  const slugs = getPostSlugs();
  const realSlugs = => s.replace(/\.md$/, ''));

  return realSlugs;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.