Internationalization of sitemaps
If you're using a sitemap to inform search engines about all pages of your site, you can attach locale-specific alternate entries (opens in a new tab) to every URL in the sitemap to indicate that a particular page is available in multiple languages or regions.
Note that by default, next-intl
returns the link
response header to instruct search engines that a page is available in multiple languages. While this sufficiently links localized pages for search engines, you may choose to provide this information in a sitemap in case you have more specific requirements.
Next.js supports providing alternate URLs per language via the alternates
entry (opens in a new tab) as of version 14.2. You can use your default locale for the main URL and provide alternate URLs based on all locales that your app supports. Keep in mind that also the default locale should be included in the alternates
object.
If you're using shared pathnames, you can iterate over an array of pathnames that your app supports and generate a sitemap entry for each pathname.
Example:
import {MetadataRoute} from 'next';
// Can be imported from shared config
const defaultLocale = 'en' as const;
const locales = ['en', 'de'] as const;
// Adapt this as necessary
const pathnames = ['/', '/about'];
const host = 'https://acme.com';
export default function sitemap(): MetadataRoute.Sitemap {
function getUrl(pathname: string, locale: string) {
return `${host}/${locale}${pathname === '/' ? '' : pathname}`;
}
return pathnames.map((pathname) => ({
url: getUrl(pathname, defaultLocale),
lastModified: new Date(),
alternates: {
languages: Object.fromEntries(
locales.map((locale) => [locale, getUrl(pathname, locale)])
)
}
}));
}
Note that your implementation may vary depending on your routing configuration (e.g. if you're using a localePrefix
other than always
or locale-specific domains).