Having a sitemap of your site in which search engines are informed of each and every one of the indexable URLs of your site is always a good idea. Although it is not an essential requirement nor does not entail the slightest penalty in SEO, it is true that search engines will index your site faster and also in the case of having sites with many URLs or that these are generated as we introduce content, such as a blog, we do not run the risk that search engines stop indexing some URLs that have not been able to reach.
It is also true that generating sitemap.xml, especially if we do not have any script to automate the process or your site is not in a CMS like wordpress that offer plugins to generate these sitmaps and your site generates new pages based on the content that is being created is a tedious task because every time we add content we would be forced to include the new URL manually. I personally have made dozens of scripts to generate the sitemap, but even making the script is a waste of time that many times we do not want to carry out.
With NextJs it didn't change much and forced us to make a script to generate a string with all the URLs of our site that we then returned with a "content-type": "application/xml"
. Not that it was very complicated but since the release of NextJs version 13.3 they have made it even easier.
To do this, if we use the app
folder to generate our application, we would only have to create a file called sitemap.js
inside the root and export a default function that returns an array of objects with the URLs of our sitemap.
// app/sitemap.js
export default function sitemap() {
return [
{
url: "mysite.com",
lastModified: new Date()
},
{
url: "mysite.com/about",
lastModified: new Date()
},
{
url: "mysite.com/contact",
lastModified: new Date()
}
];
}
So simple, now if we visit mysite.com/sitemap.xml we will see our sitemap created correctly. But suppose we have a blog and we have to add all the URLs of each post we add. In this case, we can also export an asynchronous function in which before returning the result we call our api to extract all the posts:
// app/sitemap.js
export default async function sitemap() {
// Static pages
const siteMap = [
{
url: "mysite.com",
lastModified: new Date()
},
{
url: "mysite.com/about",
lastModified: new Date()
},
{
url: "mysite.com/contact",
lastModified: new Date()
}
]
// Fetch all posts
const response = await fetch(`mysite.com/api/posts/get`);
const json = await response.json();
const posts = json.result.posts;
// Generate
posts.forEach(post => {
siteMap.push({
url: `mysite.com/post/${post.slug}`,
lastModified: new Date(post.date)
});
});
return siteMap;
}
With something as simple as this we can generate a sitemap with all our posts, every time a search engine visits our site mysite.com/sitemap.xml it will see the sitemap with all the URLs that have to be indexed always updated.