Skip to content

Instantly share code, notes, and snippets.

@n2o
Created October 23, 2024 12:13
Show Gist options
  • Save n2o/93c75e223929e6886fbc6d7b64140fd6 to your computer and use it in GitHub Desktop.
Save n2o/93c75e223929e6886fbc6d7b64140fd6 to your computer and use it in GitHub Desktop.
Automatic sitemap.xml for NextJS with Internationalization

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment