New versions of NextJS (14+) can now automatically create dynamic sitemaps that also supports revalidation. The sitemap will get updated at regular intervals as exported through revalidate variable.
Sitemap can be created through a script sitemap.js placed in the root of the app directory.
app/
|-- layout.js
|-- page.js
|-- sitemap.js
sitemap.js script should look something like this. The exported function must return an array of urls. After build, NextJS will create a sitemap that will be accessible at the /sitemap.xml route.
// 24 hours revalidation
export const revalidate = 86400
// exported function must return an array of urls
export default async function Sitemap() {
// list of urls for creating sitemap.xml
const urls = [{
url: 'https://usefulangle.com/url-1',
lastModified: '2024-05-06T15:02:26.021Z',
changeFrequency: 'weekly',
priority: 1
},
{
url: 'https://usefulangle.com/url-2',
lastModified: '2024-04-06T15:02:26.021Z',
changeFrequency: 'weekly',
priority: 1
},
{
url: 'https://usefulangle.com/url-3',
lastModified: '2024-03-06T15:02:26.021Z',
changeFrequency: 'weekly',
priority: 1
}]
return urls
}