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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nawazsk Perhaps you can read the slugs in your
/posts
directory and use them to build the dynamic pages. Something like: