The current setup has been tested on Next Js 7.0.0.
You need to install Axios.
$ npm install axios
Add a server.js and sitemap.js files into the root of your NextJs app. If they are already present, update them accordingly.
If you wan you can also install Dotenv.
$ npm install dotenv
If you have installed Dotenv you can now set SITE_ROOT, SOURCE, API_SOURCE and DESTINATION in your .env file and uncomment require("dotenv").config(); in sitemap.js.
if you don't use Dotenv and you haven't set a SITE_ROOT and API_SOURCE please update https://example.com urls in sitemap.js.
In case you use dynamic routes in you next.js application you can map them using the axios request in sitemap.js.
Example:
Your app list some product this way:
http://your.domain/products/product-slug-1http://your.domain/products/product-slug-2http://your.domain/products/product-slug-3
In the current file we are using a POST request that retrieves all products slugs. It something like:
axios
.post(API_SOURCE, {
query: `{
productList: {
product: {
slug
}
}
}`
})
.then( /*...*/ )
.catch( /*...*/ );You need to update also the url following your preferences. See the following line
xml += `${SITE_ROOT}/products/${product.slug}`;
In order to create a sitemap, simply visit http://your.domain/sitemap.xml. A XML file with your sitemap will also be created in path/to/yourApp/.next/static/sitemap.xml unless you set a custom DESTINATION in your .env file.
if (index === productList.length - 1) { xml += "</urlset>"; }I correct this