This script creates a sitemap based on the page.tsx
-files found in your app-directory.
Create a file called sitemap.ts
inside of your app/
directory of your NextJS application.
Then fill it with this script:
import { globby } from "globby"
import type { MetadataRoute } from "next"
async function getPages(): Promise<string[]> {
const paths = await globby(["./**/page.tsx"])
return paths.map((path) => {
// Remove the prefix 'app/' and all parts in brackets
let result = path
.replace(/^app\/\[.*?\]/g, "") // Remove all '[...]' after 'app/'
.replace("/page.tsx", "") // Remove 'page.tsx'
.replace(/\[.*?\]/g, "") // Remove all '[...]' in other parts
.replace(/\(.*?\)/g, "") // Remove all '(...)' in other parts
.replace(/\/\//g, "") // Remove all double slashes in other parts
// Add a slash at the beginning if not present
result = result.startsWith("/") ? result : "/" + result
// Remove trailing slash
return result.endsWith("/") ? result.slice(0, -1) : result
})
}
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const host = "https://consulting.schnaq.com"
const pages = await getPages()
const sitemap = pages.map((page) => {
return {
url: `${host}${page}`,
lastModified: new Date(),
alternates: {
languages: {
en: `${host}/en${page}`,
de: `${host}/de${page}`,
},
},
}
})
return sitemap
}
The generated sitemap can be found at your host prepended with /sitemap.xml
, e.g. https://consulting.schnaq.com/sitemap.xml