Created
February 3, 2020 19:26
-
-
Save emilpriver/16b4781263b5d2403c5c4f30a61a2db9 to your computer and use it in GitHub Desktop.
NextJS Sitemap example using Nextjs SSR.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
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 ?