Skip to content

Instantly share code, notes, and snippets.

@emilpriver
Created February 3, 2020 19:26
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emilpriver/16b4781263b5d2403c5c4f30a61a2db9 to your computer and use it in GitHub Desktop.
Save emilpriver/16b4781263b5d2403c5c4f30a61a2db9 to your computer and use it in GitHub Desktop.
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
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
Copy link

@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