Skip to content

Commit

Permalink
added support for image tag in sitemap.xml
Browse files Browse the repository at this point in the history
  • Loading branch information
archanaagivale30 committed Jul 22, 2024
1 parent 6778e36 commit dd6745d
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,32 @@ describe('resolveRouteData', () => {
"
`)
})
it('should resolve sitemap.xml with images', () => {
expect(
resolveSitemap([
{
url: 'https://example.com',
lastModified: '2021-01-01',
changeFrequency: 'weekly',
priority: 0.5,
images: ['https://example.com/image.jpg'],
},
])
).toMatchInlineSnapshot(`
"<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>https://example.com</loc>
<image:image>
<image:loc>https://example.com/image.jpg</image:loc>
</image:image>
<lastmod>2021-01-01</lastmod>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
</urlset>
"
`)
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,16 @@ export function resolveSitemap(data: MetadataRoute.Sitemap): string {
const hasAlternates = data.some(
(item) => Object.keys(item.alternates ?? {}).length > 0
)
const hasImages = data.some(
(item) => Object.keys(item.images ?? {}).length > 0
)

let content = ''
content += '<?xml version="1.0" encoding="UTF-8"?>\n'
content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'
if (hasImages) {
content += ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"'
}
if (hasAlternates) {
content += ' xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
} else {
Expand All @@ -70,6 +76,11 @@ export function resolveSitemap(data: MetadataRoute.Sitemap): string {
}" />\n`
}
}
if (item.images?.length) {
for (const image of item.images) {
content += `<image:image>\n<image:loc>${image}</image:loc>\n</image:image>\n`
}
}
if (item.lastModified) {
const serializedDate =
item.lastModified instanceof Date
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/lib/metadata/types/metadata-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,7 @@ type SitemapFile = Array<{
alternates?: {
languages?: Languages<string>
}
images?: string[]
}>

type ResolvingMetadata = Promise<ResolvedMetadata>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MetadataRoute } from 'next'

export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: 'https://example.com',
lastModified: '2024-01-01',
changeFrequency: 'daily',
priority: 0.5,
},
{
url: 'https://example.com/about',
lastModified: '2024-01-01',
images: ['https://example.com/image.jpg'],
},
]
}

0 comments on commit dd6745d

Please sign in to comment.