-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsitemap.xml.ts
59 lines (49 loc) · 1.27 KB
/
sitemap.xml.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import pages from '../src/generated/pages.json'
const S_MAXAGE = 1 * 60 * 60 // 1s * 60s/m * 60m/h = 1 hour
const STALE_WHILE_REVALIDATE = S_MAXAGE * 2
function urlTag({ location, lastmod }: { location: string; lastmod?: string }) {
return ` <url>
<loc>${process.env.NEXT_PUBLIC_ROOT_URL}${location}</loc>${
lastmod
? `
<lastmod>${lastmod}</lastmod>`
: ''
}
</url>`
}
function wrapSiteMap(content: string) {
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${content}
</urlset>
`
}
export default function SiteMap() {
// getServerSideProps will do the heavy lifting
}
interface PageInfo {
path: string
lastmod: string
}
function generateSiteMap() {
const sitemap = wrapSiteMap(
(pages as PageInfo[])
?.map((page) => urlTag({ location: page.path, lastmod: page.lastmod }))
.join('\n')
)
return sitemap
}
export async function getServerSideProps({ res }) {
const sitemap = generateSiteMap()
res.setHeader('Content-Type', 'text/xml')
res.setHeader(
'Cache-Control',
`public, s-maxage=${S_MAXAGE}, stale-while-revalidate=${STALE_WHILE_REVALIDATE}`
)
// we send the XML to the browser
res.write(sitemap)
res.end()
return {
props: {},
}
}