Last active
June 9, 2020 07:34
-
-
Save fredrikbergqvist/d2896af6563b38c3d880c0e135925ad1 to your computer and use it in GitHub Desktop.
A sitemap example for next.js
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 { NextPageContext } from "next"; | |
const blogPostsXml = (blogPosts: IBlogPostListItem[]) => { | |
let latestPost = 0; | |
let postsXml = ""; | |
blogPosts.map(post => { | |
const postDate = Date.parse(post.createdAt); | |
if (!latestPost || postDate > latestPost) { | |
latestPost = postDate; | |
} | |
postsXml += ` | |
<url> | |
<loc>${post.url}</loc> | |
<lastmod>${postDate}</lastmod> | |
<priority>0.80</priority> | |
</url>`; | |
}); | |
return { | |
postsXml, | |
latestPost | |
}; | |
}; | |
const sitemapXml = (blogPosts: IBlogPostListItem[]) => { | |
const { postsXml, latestPost } = blogPostsXml(blogPosts); | |
return `<?xml version="1.0" encoding="UTF-8"?> | |
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> | |
<url> | |
<loc>https://www.bergqvist.it/</loc> | |
<lastmod>${latestPost}</lastmod> | |
<priority>1.00</priority> | |
</url> | |
<url> | |
<loc>https://www.bergqvist.it/about</loc> | |
<priority>0.5</priority> | |
</url> | |
${postsXml} | |
</urlset>`; | |
}; | |
const Sitemap = () => {}; | |
Sitemap.getInitialProps = async ({ res }: NextPageContext) => { | |
const blogPosts = getBlogPosts(); | |
res.setHeader("Content-Type", "text/xml"); | |
res.write(sitemapXml(blogPosts)); | |
res.end(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @fredrikbergqvist, thank you for sharing. This is helpful.
There is a typo in the
sitemapXml
methodAlso, the
xml
declaration should start at first line