A sitemap example for next.js
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(); | |
}; |
This comment has been minimized.
This comment has been minimized.
Hey @sudkumar thanks for the feedback, updated the gist :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
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