Skip to content

Instantly share code, notes, and snippets.

Embed
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 = "";
data.map(post => {
const postDate = Date.parse(post.modified);
if (!latestPost || postDate > latestPost) {
latestPost = postDate;
}
const projectURL = `https://priver.dev/project/${post.acf.slug}/`;
projectsXML += `
<url>
<loc>${projectURL}</loc>
<lastmod>${postDate}</lastmod>
<priority>0.50</priority>
</url>`;
});
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://priver.dev/</loc>
<lastmod>${latestPost}</lastmod>
<priority>1.00</priority>
</url>
<url>
<loc>https://priver.dev/about/</loc>
<priority>0.80</priority>
</url>
${projectsXML}
</urlset>`;
};
class Sitemap extends React.Component {
static async getInitialProps({ res }) {
const data = await axios
.get("https://domain.ltd/wp-json/wp/v2/works?filter=[orderby]=date")
.then(response => response.data);
res.setHeader("Content-Type", "text/xml");
res.write(sitemapXml(data));
res.end();
}
}
export default Sitemap;
@nawazsk

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 ?

@EzeRangel

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 = slugs.map(s => 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.