Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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();
};
@sudkumar

This comment has been minimized.

Copy link

sudkumar commented Jan 28, 2020

Hi @fredrikbergqvist, thank you for sharing. This is helpful.

There is a typo in the sitemapXml method

    </url>
-   ${blogPostsXml}
+   ${postsXml}
  </urlset>`;

Also, the xml declaration should start at first line

-     return `
-     <?xml version="1.0" encoding="UTF-8"?>
+     return `<?xml version="1.0" encoding="UTF-8"?>
@fredrikbergqvist

This comment has been minimized.

Copy link
Owner Author

fredrikbergqvist commented Jan 28, 2020

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
You can’t perform that action at this time.