Sitemap with Next.js

SEO, Nextjs, SitemapFebruary 2, 202011254 views
Sitemap with Next.js

So, Nextjs is really hyped and a really good framework for developing. Nextjs is shiped with alot of stuffs, but not an generated sitemap (Which i understand is not added by default in Nextjs).

This is 1 way to create an dynamic sitemap without creating a server to handle Nextjs and use getInitialProps instead as normal pages does.


I wanted to be able to use /sitemap.xml as its a standard for sitemaps.By testing out different type of filename did i later on understand that you are able to use


as name and it will be rendered when entering /sitemap.xml in your browser. Something we will use in this small article.

Developing the XML feed.

Create a new file in pages/ folder in your projects map, the name of the file will be used when you want to access your sitemap.

import React from "react";
import axios from "axios";
const sitemapXML = data => {
let latestPost = 0;
let projectsXML = ""; => {
const postDate = Date.parse(post.modified);
if (!latestPost || postDate > latestPost) {
latestPost = postDate;
const projectURL = `${post.slug}/`;
projectsXML += `
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="">

First part of the code.
Here we create the XML feed with dynamic data.
We have some statics paths which is / and /about which we add manually.
but we also have some dynamic data, in my case is the dynamic data all my projects. So in the code do we loop thrue all my projects from an external source and add xml data to a variable which we later on uses to display the data.

class Sitemap extends React.Component {
static async getInitialProps({ res }) {
const data = await axios
.then(response =>; res.setHeader("Content-Type", "text/xml");
export default Sitemap;

In the last part do we use axios to fetch data from an api. This works exactly the same way we do normally fetch data when using SSR with Next.JS.
But instead of using render() or return() do we directly send the XML feed to the client. So now we have working XML feed which is rendered SSR and ready when you need it.

And exempel using the method is my website:

Github GIST if you want to copy the code

Hope this helps you :D