Unverified Commit e4cd547a authored by Juan Settecase's avatar Juan Settecase Committed by GitHub

feat: add support for localizations in sitemap generator (#53765)

### What?

Following up with [this
suggestion](https://github.com/vercel/next.js/discussions/53540) I went
ahead and implemented the proposal for the Next.js team to merge it if
they agree.

Things to keep in mind:
- Google has [three different
ways](https://developers.google.com/search/docs/specialty/international/localized-versions#methods-for-indicating-your-alternate-pages)
to do this. The three of them are equivalent
- Google seems to be the only search engine supporting this approach.
The rest of them should ignore it

### Why?

This is supported by
[Google](https://developers.google.com/search/docs/specialty/international/localized-versions#example_2)
to better understand the site when the same page is available in
multiple languages.

### How?

- I added a new key to the `MetadataRoute.Sitemap` type called
`alternates` which accepts just one sub key `languages` similar to the
current one in the
[Metadata](https://nextjs.org/docs/app/api-reference/functions/generate-metadata#alternates)
object
- I updated the `resolveSitemap` method to process the new key and
generate the expected sitemap
- I updated the related tests and documentation to reflect the new
syntax

---------
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent 491f6d85
...@@ -118,6 +118,90 @@ Output: ...@@ -118,6 +118,90 @@ Output:
</urlset> </urlset>
``` ```
### Generate a localized Sitemap
```ts filename="app/sitemap.ts" switcher
import { MetadataRoute } from 'next'
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: 'https://acme.com',
lastModified: new Date(),
alternates: {
languages: {
es: 'https://acme.com/es',
de: 'https://acme.com/de',
},
},
},
{
url: 'https://acme.com/about',
lastModified: new Date(),
alternates: {
languages: {
es: 'https://acme.com/es/about',
de: 'https://acme.com/de/about',
},
},
},
{
url: 'https://acme.com/blog',
lastModified: new Date(),
alternates: {
languages: {
es: 'https://acme.com/es/blog',
de: 'https://acme.com/de/blog',
},
},
},
]
}
```
Output:
```xml filename="acme.com/sitemap.xml"
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9 xmlns:xhtml="http://www.w3.org/1999/xhtml"">
<url>
<loc>https://acme.com</loc>
<xhtml:link
rel="alternate"
hreflang="es"
href="https://acme.com/es"/>
<xhtml:link
rel="alternate"
hreflang="de"
href="https://acme.com/de"/>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
</url>
<url>
<loc>https://acme.com/about</loc>
<xhtml:link
rel="alternate"
hreflang="es"
href="https://acme.com/es/about"/>
<xhtml:link
rel="alternate"
hreflang="de"
href="https://acme.com/de/about"/>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
</url>
<url>
<loc>https://acme.com/blog</loc>
<xhtml:link
rel="alternate"
hreflang="es"
href="https://acme.com/es/blog"/>
<xhtml:link
rel="alternate"
hreflang="de"
href="https://acme.com/de/blog"/>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
</url>
</urlset>
```
### Generating multiple sitemaps ### Generating multiple sitemaps
While a single sitemap will work for most applications. For large web applications, you may need to split a sitemap into multiple files. While a single sitemap will work for most applications. For large web applications, you may need to split a sitemap into multiple files.
...@@ -200,6 +284,9 @@ type Sitemap = Array<{ ...@@ -200,6 +284,9 @@ type Sitemap = Array<{
| 'yearly' | 'yearly'
| 'never' | 'never'
priority?: number priority?: number
alternates?: {
languages?: Languages<string>
}
}> }>
``` ```
......
...@@ -99,5 +99,32 @@ describe('resolveRouteData', () => { ...@@ -99,5 +99,32 @@ describe('resolveRouteData', () => {
" "
`) `)
}) })
it('should resolve sitemap.xml with alternates', () => {
expect(
resolveSitemap([
{
url: 'https://example.com',
lastModified: '2021-01-01',
alternates: {
languages: {
es: 'https://example.com/es',
de: 'https://example.com/de',
},
},
},
])
).toMatchInlineSnapshot(`
"<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url>
<loc>https://example.com</loc>
<xhtml:link rel="alternate" hreflang="es" href="https://example.com/es" />
<xhtml:link rel="alternate" hreflang="de" href="https://example.com/de" />
<lastmod>2021-01-01</lastmod>
</url>
</urlset>
"
`)
})
}) })
}) })
...@@ -44,14 +44,32 @@ export function resolveRobots(data: MetadataRoute.Robots): string { ...@@ -44,14 +44,32 @@ export function resolveRobots(data: MetadataRoute.Robots): string {
// TODO-METADATA: support multi sitemap files // TODO-METADATA: support multi sitemap files
// convert sitemap data to xml string // convert sitemap data to xml string
export function resolveSitemap(data: MetadataRoute.Sitemap): string { export function resolveSitemap(data: MetadataRoute.Sitemap): string {
const hasAlternates = data.some(
(item) => Object.keys(item.alternates ?? {}).length > 0
)
let content = '' let content = ''
content += '<?xml version="1.0" encoding="UTF-8"?>\n' content += '<?xml version="1.0" encoding="UTF-8"?>\n'
content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'
if (hasAlternates) {
content += ' xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
} else {
content += '>\n'
}
for (const item of data) { for (const item of data) {
content += '<url>\n' content += '<url>\n'
content += `<loc>${item.url}</loc>\n` content += `<loc>${item.url}</loc>\n`
const languages = item.alternates?.languages
if (languages && Object.keys(languages).length) {
// Since sitemap is separated from the page rendering, there's not metadataBase accessible yet.
// we give the default setting that won't effect the languages resolving.
for (const language in languages) {
content += `<xhtml:link rel="alternate" hreflang="${language}" href="${
languages[language as keyof typeof languages]
}" />\n`
}
}
if (item.lastModified) { if (item.lastModified) {
const serializedDate = const serializedDate =
item.lastModified instanceof Date item.lastModified instanceof Date
......
...@@ -426,7 +426,7 @@ type UnmatchedLang = 'x-default' ...@@ -426,7 +426,7 @@ type UnmatchedLang = 'x-default'
type HrefLang = LangCode | UnmatchedLang type HrefLang = LangCode | UnmatchedLang
type Languages<T> = { export type Languages<T> = {
[s in HrefLang]?: T [s in HrefLang]?: T
} }
......
import type { import type {
AlternateURLs, AlternateURLs,
Languages,
ResolvedAlternateURLs, ResolvedAlternateURLs,
} from './alternative-urls-types' } from './alternative-urls-types'
import type { import type {
...@@ -580,6 +581,9 @@ type SitemapFile = Array<{ ...@@ -580,6 +581,9 @@ type SitemapFile = Array<{
| 'yearly' | 'yearly'
| 'never' | 'never'
priority?: number priority?: number
alternates?: {
languages?: Languages<string>
}
}> }>
type ResolvingMetadata = Promise<ResolvedMetadata> type ResolvingMetadata = Promise<ResolvedMetadata>
......
import { MetadataRoute } from 'next'
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: 'https://example.com',
lastModified: '2021-01-01',
changeFrequency: 'daily',
priority: 0.5,
},
{
url: 'https://example.com/about',
lastModified: '2021-01-01',
alternates: {
languages: {
es: 'https://example.com/es/about',
de: 'https://example.com/de/about',
},
},
},
]
}
...@@ -73,6 +73,18 @@ createNextDescribe( ...@@ -73,6 +73,18 @@ createNextDescribe(
) )
expect(status).toBe(200) expect(status).toBe(200)
}) })
it('should support alternate.languages in sitemap', async () => {
const xml = await (await next.fetch('/lang/sitemap.xml')).text()
expect(xml).toContain('xmlns:xhtml="http://www.w3.org/1999/xhtml')
expect(xml).toContain(
`<xhtml:link rel="alternate" hreflang="es" href="https://example.com/es/about" />`
)
expect(xml).toContain(
`<xhtml:link rel="alternate" hreflang="de" href="https://example.com/de/about" />`
)
})
}) })
describe('social image routes', () => { describe('social image routes', () => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment