Skip to content

Commit 9af1dcb

Browse files
authored
feat: Add alternates languages to sitemap (#6977)
feat: add alternates languages to sitemap (#6956)
1 parent 25b2206 commit 9af1dcb

File tree

1 file changed

+43
-14
lines changed

1 file changed

+43
-14
lines changed

apps/site/app/sitemap.ts

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,59 @@ import {
66
EXTERNAL_LINKS_SITEMAP,
77
} from '@/next.constants.mjs';
88
import { dynamicRouter } from '@/next.dynamic.mjs';
9-
import { availableLocaleCodes } from '@/next.locales.mjs';
9+
import { availableLocaleCodes, defaultLocale } from '@/next.locales.mjs';
1010

1111
// This is the combination of the Application Base URL and Base PATH
1212
const baseUrlAndPath = `${BASE_URL}${BASE_PATH}`;
1313

1414
// This allows us to generate a `sitemap.xml` file dynamically based on the needs of the Node.js Website
15-
// Next.js Sitemap Generation doesn't support `alternate` refs yet
16-
// @see https://github.com/vercel/next.js/discussions/55646
1715
const sitemap = async (): Promise<MetadataRoute.Sitemap> => {
18-
const paths: Array<string> = [];
16+
const routes = await dynamicRouter.getRoutesByLanguage(defaultLocale.code);
17+
const paths = [];
1918

20-
for (const locale of availableLocaleCodes) {
21-
const routes = await dynamicRouter.getRoutesByLanguage(locale);
19+
const currentDate = new Date().toISOString();
2220

23-
paths.push(...routes.map(route => `${baseUrlAndPath}/${locale}/${route}`));
24-
}
21+
for (const route of routes) {
22+
const availableLocalesForRoute = [];
2523

26-
const currentDate = new Date().toISOString();
24+
for (const locale of availableLocaleCodes.filter(
25+
locale => locale !== defaultLocale.code
26+
)) {
27+
const markdownFile = await dynamicRouter.getMarkdownFile(locale, route);
28+
const isAvailable = markdownFile.filename !== '';
29+
if (isAvailable) {
30+
availableLocalesForRoute.push(locale);
31+
}
32+
}
33+
34+
const alternatesPaths = availableLocalesForRoute.reduce(
35+
(acc, locale) => ({
36+
...acc,
37+
[locale]: `${baseUrlAndPath}/${locale}/${route}`,
38+
}),
39+
{}
40+
);
41+
42+
paths.push({
43+
url: `${baseUrlAndPath}/${defaultLocale.code}/${route}`,
44+
lastModified: currentDate,
45+
changeFrequency: 'always' as const,
46+
alternates: {
47+
languages: {
48+
...alternatesPaths,
49+
},
50+
},
51+
});
52+
}
2753

28-
return [...paths, ...EXTERNAL_LINKS_SITEMAP].map(route => ({
29-
url: route,
30-
lastModified: currentDate,
31-
changeFrequency: 'always',
32-
}));
54+
return [
55+
...paths,
56+
...EXTERNAL_LINKS_SITEMAP.map(route => ({
57+
url: route,
58+
lastModified: currentDate,
59+
changeFrequency: 'always' as const,
60+
})),
61+
];
3362
};
3463

3564
export default sitemap;

0 commit comments

Comments
 (0)